1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296   }
297 
298   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
299     // Lambdas are only default-constructible or assignable in C++2a onwards.
300     if (MD->getParent()->isLambda() &&
301         ((isa<CXXConstructorDecl>(MD) &&
302           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
303          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
304       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
305         << !isa<CXXConstructorDecl>(MD);
306     }
307   }
308 
309   auto getReferencedObjCProp = [](const NamedDecl *D) ->
310                                       const ObjCPropertyDecl * {
311     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
312       return MD->findPropertyDecl();
313     return nullptr;
314   };
315   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
316     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
317       return true;
318   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
319       return true;
320   }
321 
322   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
323   // Only the variables omp_in and omp_out are allowed in the combiner.
324   // Only the variables omp_priv and omp_orig are allowed in the
325   // initializer-clause.
326   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
327   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
328       isa<VarDecl>(D)) {
329     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
330         << getCurFunction()->HasOMPDeclareReductionCombiner;
331     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
332     return true;
333   }
334 
335   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
336   //  List-items in map clauses on this construct may only refer to the declared
337   //  variable var and entities that could be referenced by a procedure defined
338   //  at the same location
339   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
340   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
341       isa<VarDecl>(D)) {
342     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
343         << DMD->getVarName().getAsString();
344     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
345     return true;
346   }
347 
348   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
349                              AvoidPartialAvailabilityChecks, ClassReceiver);
350 
351   DiagnoseUnusedOfDecl(*this, D, Loc);
352 
353   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
354 
355   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
356       !isUnevaluatedContext()) {
357     // C++ [expr.prim.req.nested] p3
358     //   A local parameter shall only appear as an unevaluated operand
359     //   (Clause 8) within the constraint-expression.
360     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
361         << D;
362     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
363     return true;
364   }
365 
366   return false;
367 }
368 
369 /// DiagnoseSentinelCalls - This routine checks whether a call or
370 /// message-send is to a declaration with the sentinel attribute, and
371 /// if so, it checks that the requirements of the sentinel are
372 /// satisfied.
373 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
374                                  ArrayRef<Expr *> Args) {
375   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
376   if (!attr)
377     return;
378 
379   // The number of formal parameters of the declaration.
380   unsigned numFormalParams;
381 
382   // The kind of declaration.  This is also an index into a %select in
383   // the diagnostic.
384   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
385 
386   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
387     numFormalParams = MD->param_size();
388     calleeType = CT_Method;
389   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
390     numFormalParams = FD->param_size();
391     calleeType = CT_Function;
392   } else if (isa<VarDecl>(D)) {
393     QualType type = cast<ValueDecl>(D)->getType();
394     const FunctionType *fn = nullptr;
395     if (const PointerType *ptr = type->getAs<PointerType>()) {
396       fn = ptr->getPointeeType()->getAs<FunctionType>();
397       if (!fn) return;
398       calleeType = CT_Function;
399     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
400       fn = ptr->getPointeeType()->castAs<FunctionType>();
401       calleeType = CT_Block;
402     } else {
403       return;
404     }
405 
406     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
407       numFormalParams = proto->getNumParams();
408     } else {
409       numFormalParams = 0;
410     }
411   } else {
412     return;
413   }
414 
415   // "nullPos" is the number of formal parameters at the end which
416   // effectively count as part of the variadic arguments.  This is
417   // useful if you would prefer to not have *any* formal parameters,
418   // but the language forces you to have at least one.
419   unsigned nullPos = attr->getNullPos();
420   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
421   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
422 
423   // The number of arguments which should follow the sentinel.
424   unsigned numArgsAfterSentinel = attr->getSentinel();
425 
426   // If there aren't enough arguments for all the formal parameters,
427   // the sentinel, and the args after the sentinel, complain.
428   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
429     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
430     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
431     return;
432   }
433 
434   // Otherwise, find the sentinel expression.
435   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
436   if (!sentinelExpr) return;
437   if (sentinelExpr->isValueDependent()) return;
438   if (Context.isSentinelNullExpr(sentinelExpr)) return;
439 
440   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
441   // or 'NULL' if those are actually defined in the context.  Only use
442   // 'nil' for ObjC methods, where it's much more likely that the
443   // variadic arguments form a list of object pointers.
444   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
445   std::string NullValue;
446   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
447     NullValue = "nil";
448   else if (getLangOpts().CPlusPlus11)
449     NullValue = "nullptr";
450   else if (PP.isMacroDefined("NULL"))
451     NullValue = "NULL";
452   else
453     NullValue = "(void*) 0";
454 
455   if (MissingNilLoc.isInvalid())
456     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
457   else
458     Diag(MissingNilLoc, diag::warn_missing_sentinel)
459       << int(calleeType)
460       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
461   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
462 }
463 
464 SourceRange Sema::getExprRange(Expr *E) const {
465   return E ? E->getSourceRange() : SourceRange();
466 }
467 
468 //===----------------------------------------------------------------------===//
469 //  Standard Promotions and Conversions
470 //===----------------------------------------------------------------------===//
471 
472 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
473 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
474   // Handle any placeholder expressions which made it here.
475   if (E->getType()->isPlaceholderType()) {
476     ExprResult result = CheckPlaceholderExpr(E);
477     if (result.isInvalid()) return ExprError();
478     E = result.get();
479   }
480 
481   QualType Ty = E->getType();
482   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
483 
484   if (Ty->isFunctionType()) {
485     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
486       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
487         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
488           return ExprError();
489 
490     E = ImpCastExprToType(E, Context.getPointerType(Ty),
491                           CK_FunctionToPointerDecay).get();
492   } else if (Ty->isArrayType()) {
493     // In C90 mode, arrays only promote to pointers if the array expression is
494     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
495     // type 'array of type' is converted to an expression that has type 'pointer
496     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
497     // that has type 'array of type' ...".  The relevant change is "an lvalue"
498     // (C90) to "an expression" (C99).
499     //
500     // C++ 4.2p1:
501     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
502     // T" can be converted to an rvalue of type "pointer to T".
503     //
504     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
505       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
506                             CK_ArrayToPointerDecay).get();
507   }
508   return E;
509 }
510 
511 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
512   // Check to see if we are dereferencing a null pointer.  If so,
513   // and if not volatile-qualified, this is undefined behavior that the
514   // optimizer will delete, so warn about it.  People sometimes try to use this
515   // to get a deterministic trap and are surprised by clang's behavior.  This
516   // only handles the pattern "*null", which is a very syntactic check.
517   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
518   if (UO && UO->getOpcode() == UO_Deref &&
519       UO->getSubExpr()->getType()->isPointerType()) {
520     const LangAS AS =
521         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
522     if ((!isTargetAddressSpace(AS) ||
523          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
524         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
525             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
526         !UO->getType().isVolatileQualified()) {
527       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
528                             S.PDiag(diag::warn_indirection_through_null)
529                                 << UO->getSubExpr()->getSourceRange());
530       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
531                             S.PDiag(diag::note_indirection_through_null));
532     }
533   }
534 }
535 
536 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
537                                     SourceLocation AssignLoc,
538                                     const Expr* RHS) {
539   const ObjCIvarDecl *IV = OIRE->getDecl();
540   if (!IV)
541     return;
542 
543   DeclarationName MemberName = IV->getDeclName();
544   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
545   if (!Member || !Member->isStr("isa"))
546     return;
547 
548   const Expr *Base = OIRE->getBase();
549   QualType BaseType = Base->getType();
550   if (OIRE->isArrow())
551     BaseType = BaseType->getPointeeType();
552   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
553     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
554       ObjCInterfaceDecl *ClassDeclared = nullptr;
555       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
556       if (!ClassDeclared->getSuperClass()
557           && (*ClassDeclared->ivar_begin()) == IV) {
558         if (RHS) {
559           NamedDecl *ObjectSetClass =
560             S.LookupSingleName(S.TUScope,
561                                &S.Context.Idents.get("object_setClass"),
562                                SourceLocation(), S.LookupOrdinaryName);
563           if (ObjectSetClass) {
564             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
565             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
566                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
567                                               "object_setClass(")
568                 << FixItHint::CreateReplacement(
569                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
570                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
571           }
572           else
573             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
574         } else {
575           NamedDecl *ObjectGetClass =
576             S.LookupSingleName(S.TUScope,
577                                &S.Context.Idents.get("object_getClass"),
578                                SourceLocation(), S.LookupOrdinaryName);
579           if (ObjectGetClass)
580             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
581                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
582                                               "object_getClass(")
583                 << FixItHint::CreateReplacement(
584                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
587         }
588         S.Diag(IV->getLocation(), diag::note_ivar_decl);
589       }
590     }
591 }
592 
593 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
594   // Handle any placeholder expressions which made it here.
595   if (E->getType()->isPlaceholderType()) {
596     ExprResult result = CheckPlaceholderExpr(E);
597     if (result.isInvalid()) return ExprError();
598     E = result.get();
599   }
600 
601   // C++ [conv.lval]p1:
602   //   A glvalue of a non-function, non-array type T can be
603   //   converted to a prvalue.
604   if (!E->isGLValue()) return E;
605 
606   QualType T = E->getType();
607   assert(!T.isNull() && "r-value conversion on typeless expression?");
608 
609   // We don't want to throw lvalue-to-rvalue casts on top of
610   // expressions of certain types in C++.
611   if (getLangOpts().CPlusPlus &&
612       (E->getType() == Context.OverloadTy ||
613        T->isDependentType() ||
614        T->isRecordType()))
615     return E;
616 
617   // The C standard is actually really unclear on this point, and
618   // DR106 tells us what the result should be but not why.  It's
619   // generally best to say that void types just doesn't undergo
620   // lvalue-to-rvalue at all.  Note that expressions of unqualified
621   // 'void' type are never l-values, but qualified void can be.
622   if (T->isVoidType())
623     return E;
624 
625   // OpenCL usually rejects direct accesses to values of 'half' type.
626   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
627       T->isHalfType()) {
628     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
629       << 0 << T;
630     return ExprError();
631   }
632 
633   CheckForNullPointerDereference(*this, E);
634   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
635     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
636                                      &Context.Idents.get("object_getClass"),
637                                      SourceLocation(), LookupOrdinaryName);
638     if (ObjectGetClass)
639       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
640           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
641           << FixItHint::CreateReplacement(
642                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
643     else
644       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
645   }
646   else if (const ObjCIvarRefExpr *OIRE =
647             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
648     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
649 
650   // C++ [conv.lval]p1:
651   //   [...] If T is a non-class type, the type of the prvalue is the
652   //   cv-unqualified version of T. Otherwise, the type of the
653   //   rvalue is T.
654   //
655   // C99 6.3.2.1p2:
656   //   If the lvalue has qualified type, the value has the unqualified
657   //   version of the type of the lvalue; otherwise, the value has the
658   //   type of the lvalue.
659   if (T.hasQualifiers())
660     T = T.getUnqualifiedType();
661 
662   // Under the MS ABI, lock down the inheritance model now.
663   if (T->isMemberPointerType() &&
664       Context.getTargetInfo().getCXXABI().isMicrosoft())
665     (void)isCompleteType(E->getExprLoc(), T);
666 
667   ExprResult Res = CheckLValueToRValueConversionOperand(E);
668   if (Res.isInvalid())
669     return Res;
670   E = Res.get();
671 
672   // Loading a __weak object implicitly retains the value, so we need a cleanup to
673   // balance that.
674   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
675     Cleanup.setExprNeedsCleanups(true);
676 
677   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
678     Cleanup.setExprNeedsCleanups(true);
679 
680   // C++ [conv.lval]p3:
681   //   If T is cv std::nullptr_t, the result is a null pointer constant.
682   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
683   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
684 
685   // C11 6.3.2.1p2:
686   //   ... if the lvalue has atomic type, the value has the non-atomic version
687   //   of the type of the lvalue ...
688   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
689     T = Atomic->getValueType().getUnqualifiedType();
690     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
691                                    nullptr, VK_RValue);
692   }
693 
694   return Res;
695 }
696 
697 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
698   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
699   if (Res.isInvalid())
700     return ExprError();
701   Res = DefaultLvalueConversion(Res.get());
702   if (Res.isInvalid())
703     return ExprError();
704   return Res;
705 }
706 
707 /// CallExprUnaryConversions - a special case of an unary conversion
708 /// performed on a function designator of a call expression.
709 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
710   QualType Ty = E->getType();
711   ExprResult Res = E;
712   // Only do implicit cast for a function type, but not for a pointer
713   // to function type.
714   if (Ty->isFunctionType()) {
715     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
716                             CK_FunctionToPointerDecay).get();
717     if (Res.isInvalid())
718       return ExprError();
719   }
720   Res = DefaultLvalueConversion(Res.get());
721   if (Res.isInvalid())
722     return ExprError();
723   return Res.get();
724 }
725 
726 /// UsualUnaryConversions - Performs various conversions that are common to most
727 /// operators (C99 6.3). The conversions of array and function types are
728 /// sometimes suppressed. For example, the array->pointer conversion doesn't
729 /// apply if the array is an argument to the sizeof or address (&) operators.
730 /// In these instances, this routine should *not* be called.
731 ExprResult Sema::UsualUnaryConversions(Expr *E) {
732   // First, convert to an r-value.
733   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
734   if (Res.isInvalid())
735     return ExprError();
736   E = Res.get();
737 
738   QualType Ty = E->getType();
739   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
740 
741   // Half FP have to be promoted to float unless it is natively supported
742   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
743     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
744 
745   // Try to perform integral promotions if the object has a theoretically
746   // promotable type.
747   if (Ty->isIntegralOrUnscopedEnumerationType()) {
748     // C99 6.3.1.1p2:
749     //
750     //   The following may be used in an expression wherever an int or
751     //   unsigned int may be used:
752     //     - an object or expression with an integer type whose integer
753     //       conversion rank is less than or equal to the rank of int
754     //       and unsigned int.
755     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
756     //
757     //   If an int can represent all values of the original type, the
758     //   value is converted to an int; otherwise, it is converted to an
759     //   unsigned int. These are called the integer promotions. All
760     //   other types are unchanged by the integer promotions.
761 
762     QualType PTy = Context.isPromotableBitField(E);
763     if (!PTy.isNull()) {
764       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
765       return E;
766     }
767     if (Ty->isPromotableIntegerType()) {
768       QualType PT = Context.getPromotedIntegerType(Ty);
769       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
770       return E;
771     }
772   }
773   return E;
774 }
775 
776 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
777 /// do not have a prototype. Arguments that have type float or __fp16
778 /// are promoted to double. All other argument types are converted by
779 /// UsualUnaryConversions().
780 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
781   QualType Ty = E->getType();
782   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
783 
784   ExprResult Res = UsualUnaryConversions(E);
785   if (Res.isInvalid())
786     return ExprError();
787   E = Res.get();
788 
789   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
790   // promote to double.
791   // Note that default argument promotion applies only to float (and
792   // half/fp16); it does not apply to _Float16.
793   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
794   if (BTy && (BTy->getKind() == BuiltinType::Half ||
795               BTy->getKind() == BuiltinType::Float)) {
796     if (getLangOpts().OpenCL &&
797         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
798         if (BTy->getKind() == BuiltinType::Half) {
799             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
800         }
801     } else {
802       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
803     }
804   }
805 
806   // C++ performs lvalue-to-rvalue conversion as a default argument
807   // promotion, even on class types, but note:
808   //   C++11 [conv.lval]p2:
809   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
810   //     operand or a subexpression thereof the value contained in the
811   //     referenced object is not accessed. Otherwise, if the glvalue
812   //     has a class type, the conversion copy-initializes a temporary
813   //     of type T from the glvalue and the result of the conversion
814   //     is a prvalue for the temporary.
815   // FIXME: add some way to gate this entire thing for correctness in
816   // potentially potentially evaluated contexts.
817   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
818     ExprResult Temp = PerformCopyInitialization(
819                        InitializedEntity::InitializeTemporary(E->getType()),
820                                                 E->getExprLoc(), E);
821     if (Temp.isInvalid())
822       return ExprError();
823     E = Temp.get();
824   }
825 
826   return E;
827 }
828 
829 /// Determine the degree of POD-ness for an expression.
830 /// Incomplete types are considered POD, since this check can be performed
831 /// when we're in an unevaluated context.
832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
833   if (Ty->isIncompleteType()) {
834     // C++11 [expr.call]p7:
835     //   After these conversions, if the argument does not have arithmetic,
836     //   enumeration, pointer, pointer to member, or class type, the program
837     //   is ill-formed.
838     //
839     // Since we've already performed array-to-pointer and function-to-pointer
840     // decay, the only such type in C++ is cv void. This also handles
841     // initializer lists as variadic arguments.
842     if (Ty->isVoidType())
843       return VAK_Invalid;
844 
845     if (Ty->isObjCObjectType())
846       return VAK_Invalid;
847     return VAK_Valid;
848   }
849 
850   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
851     return VAK_Invalid;
852 
853   if (Ty.isCXX98PODType(Context))
854     return VAK_Valid;
855 
856   // C++11 [expr.call]p7:
857   //   Passing a potentially-evaluated argument of class type (Clause 9)
858   //   having a non-trivial copy constructor, a non-trivial move constructor,
859   //   or a non-trivial destructor, with no corresponding parameter,
860   //   is conditionally-supported with implementation-defined semantics.
861   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
862     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
863       if (!Record->hasNonTrivialCopyConstructor() &&
864           !Record->hasNonTrivialMoveConstructor() &&
865           !Record->hasNonTrivialDestructor())
866         return VAK_ValidInCXX11;
867 
868   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
869     return VAK_Valid;
870 
871   if (Ty->isObjCObjectType())
872     return VAK_Invalid;
873 
874   if (getLangOpts().MSVCCompat)
875     return VAK_MSVCUndefined;
876 
877   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
878   // permitted to reject them. We should consider doing so.
879   return VAK_Undefined;
880 }
881 
882 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
883   // Don't allow one to pass an Objective-C interface to a vararg.
884   const QualType &Ty = E->getType();
885   VarArgKind VAK = isValidVarArgType(Ty);
886 
887   // Complain about passing non-POD types through varargs.
888   switch (VAK) {
889   case VAK_ValidInCXX11:
890     DiagRuntimeBehavior(
891         E->getBeginLoc(), nullptr,
892         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
893     LLVM_FALLTHROUGH;
894   case VAK_Valid:
895     if (Ty->isRecordType()) {
896       // This is unlikely to be what the user intended. If the class has a
897       // 'c_str' member function, the user probably meant to call that.
898       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
899                           PDiag(diag::warn_pass_class_arg_to_vararg)
900                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
901     }
902     break;
903 
904   case VAK_Undefined:
905   case VAK_MSVCUndefined:
906     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
907                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
908                             << getLangOpts().CPlusPlus11 << Ty << CT);
909     break;
910 
911   case VAK_Invalid:
912     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
913       Diag(E->getBeginLoc(),
914            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
915           << Ty << CT;
916     else if (Ty->isObjCObjectType())
917       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
918                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
919                               << Ty << CT);
920     else
921       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
922           << isa<InitListExpr>(E) << Ty << CT;
923     break;
924   }
925 }
926 
927 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
928 /// will create a trap if the resulting type is not a POD type.
929 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
930                                                   FunctionDecl *FDecl) {
931   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
932     // Strip the unbridged-cast placeholder expression off, if applicable.
933     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
934         (CT == VariadicMethod ||
935          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
936       E = stripARCUnbridgedCast(E);
937 
938     // Otherwise, do normal placeholder checking.
939     } else {
940       ExprResult ExprRes = CheckPlaceholderExpr(E);
941       if (ExprRes.isInvalid())
942         return ExprError();
943       E = ExprRes.get();
944     }
945   }
946 
947   ExprResult ExprRes = DefaultArgumentPromotion(E);
948   if (ExprRes.isInvalid())
949     return ExprError();
950   E = ExprRes.get();
951 
952   // Diagnostics regarding non-POD argument types are
953   // emitted along with format string checking in Sema::CheckFunctionCall().
954   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
955     // Turn this into a trap.
956     CXXScopeSpec SS;
957     SourceLocation TemplateKWLoc;
958     UnqualifiedId Name;
959     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
960                        E->getBeginLoc());
961     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
962                                           /*HasTrailingLParen=*/true,
963                                           /*IsAddressOfOperand=*/false);
964     if (TrapFn.isInvalid())
965       return ExprError();
966 
967     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
968                                     None, E->getEndLoc());
969     if (Call.isInvalid())
970       return ExprError();
971 
972     ExprResult Comma =
973         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
974     if (Comma.isInvalid())
975       return ExprError();
976     return Comma.get();
977   }
978 
979   if (!getLangOpts().CPlusPlus &&
980       RequireCompleteType(E->getExprLoc(), E->getType(),
981                           diag::err_call_incomplete_argument))
982     return ExprError();
983 
984   return E;
985 }
986 
987 /// Converts an integer to complex float type.  Helper function of
988 /// UsualArithmeticConversions()
989 ///
990 /// \return false if the integer expression is an integer type and is
991 /// successfully converted to the complex type.
992 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
993                                                   ExprResult &ComplexExpr,
994                                                   QualType IntTy,
995                                                   QualType ComplexTy,
996                                                   bool SkipCast) {
997   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
998   if (SkipCast) return false;
999   if (IntTy->isIntegerType()) {
1000     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1001     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1002     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1003                                   CK_FloatingRealToComplex);
1004   } else {
1005     assert(IntTy->isComplexIntegerType());
1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1007                                   CK_IntegralComplexToFloatingComplex);
1008   }
1009   return false;
1010 }
1011 
1012 /// Handle arithmetic conversion with complex types.  Helper function of
1013 /// UsualArithmeticConversions()
1014 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1015                                              ExprResult &RHS, QualType LHSType,
1016                                              QualType RHSType,
1017                                              bool IsCompAssign) {
1018   // if we have an integer operand, the result is the complex type.
1019   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1020                                              /*skipCast*/false))
1021     return LHSType;
1022   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1023                                              /*skipCast*/IsCompAssign))
1024     return RHSType;
1025 
1026   // This handles complex/complex, complex/float, or float/complex.
1027   // When both operands are complex, the shorter operand is converted to the
1028   // type of the longer, and that is the type of the result. This corresponds
1029   // to what is done when combining two real floating-point operands.
1030   // The fun begins when size promotion occur across type domains.
1031   // From H&S 6.3.4: When one operand is complex and the other is a real
1032   // floating-point type, the less precise type is converted, within it's
1033   // real or complex domain, to the precision of the other type. For example,
1034   // when combining a "long double" with a "double _Complex", the
1035   // "double _Complex" is promoted to "long double _Complex".
1036 
1037   // Compute the rank of the two types, regardless of whether they are complex.
1038   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1039 
1040   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1041   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1042   QualType LHSElementType =
1043       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1044   QualType RHSElementType =
1045       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1046 
1047   QualType ResultType = S.Context.getComplexType(LHSElementType);
1048   if (Order < 0) {
1049     // Promote the precision of the LHS if not an assignment.
1050     ResultType = S.Context.getComplexType(RHSElementType);
1051     if (!IsCompAssign) {
1052       if (LHSComplexType)
1053         LHS =
1054             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1055       else
1056         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1057     }
1058   } else if (Order > 0) {
1059     // Promote the precision of the RHS.
1060     if (RHSComplexType)
1061       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1062     else
1063       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1064   }
1065   return ResultType;
1066 }
1067 
1068 /// Handle arithmetic conversion from integer to float.  Helper function
1069 /// of UsualArithmeticConversions()
1070 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1071                                            ExprResult &IntExpr,
1072                                            QualType FloatTy, QualType IntTy,
1073                                            bool ConvertFloat, bool ConvertInt) {
1074   if (IntTy->isIntegerType()) {
1075     if (ConvertInt)
1076       // Convert intExpr to the lhs floating point type.
1077       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1078                                     CK_IntegralToFloating);
1079     return FloatTy;
1080   }
1081 
1082   // Convert both sides to the appropriate complex float.
1083   assert(IntTy->isComplexIntegerType());
1084   QualType result = S.Context.getComplexType(FloatTy);
1085 
1086   // _Complex int -> _Complex float
1087   if (ConvertInt)
1088     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1089                                   CK_IntegralComplexToFloatingComplex);
1090 
1091   // float -> _Complex float
1092   if (ConvertFloat)
1093     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1094                                     CK_FloatingRealToComplex);
1095 
1096   return result;
1097 }
1098 
1099 /// Handle arithmethic conversion with floating point types.  Helper
1100 /// function of UsualArithmeticConversions()
1101 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1102                                       ExprResult &RHS, QualType LHSType,
1103                                       QualType RHSType, bool IsCompAssign) {
1104   bool LHSFloat = LHSType->isRealFloatingType();
1105   bool RHSFloat = RHSType->isRealFloatingType();
1106 
1107   // If we have two real floating types, convert the smaller operand
1108   // to the bigger result.
1109   if (LHSFloat && RHSFloat) {
1110     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1111     if (order > 0) {
1112       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1113       return LHSType;
1114     }
1115 
1116     assert(order < 0 && "illegal float comparison");
1117     if (!IsCompAssign)
1118       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1119     return RHSType;
1120   }
1121 
1122   if (LHSFloat) {
1123     // Half FP has to be promoted to float unless it is natively supported
1124     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1125       LHSType = S.Context.FloatTy;
1126 
1127     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1128                                       /*ConvertFloat=*/!IsCompAssign,
1129                                       /*ConvertInt=*/ true);
1130   }
1131   assert(RHSFloat);
1132   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1133                                     /*convertInt=*/ true,
1134                                     /*convertFloat=*/!IsCompAssign);
1135 }
1136 
1137 /// Diagnose attempts to convert between __float128 and long double if
1138 /// there is no support for such conversion. Helper function of
1139 /// UsualArithmeticConversions().
1140 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1141                                       QualType RHSType) {
1142   /*  No issue converting if at least one of the types is not a floating point
1143       type or the two types have the same rank.
1144   */
1145   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1146       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1147     return false;
1148 
1149   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1150          "The remaining types must be floating point types.");
1151 
1152   auto *LHSComplex = LHSType->getAs<ComplexType>();
1153   auto *RHSComplex = RHSType->getAs<ComplexType>();
1154 
1155   QualType LHSElemType = LHSComplex ?
1156     LHSComplex->getElementType() : LHSType;
1157   QualType RHSElemType = RHSComplex ?
1158     RHSComplex->getElementType() : RHSType;
1159 
1160   // No issue if the two types have the same representation
1161   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1162       &S.Context.getFloatTypeSemantics(RHSElemType))
1163     return false;
1164 
1165   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1166                                 RHSElemType == S.Context.LongDoubleTy);
1167   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1168                             RHSElemType == S.Context.Float128Ty);
1169 
1170   // We've handled the situation where __float128 and long double have the same
1171   // representation. We allow all conversions for all possible long double types
1172   // except PPC's double double.
1173   return Float128AndLongDouble &&
1174     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1175      &llvm::APFloat::PPCDoubleDouble());
1176 }
1177 
1178 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1179 
1180 namespace {
1181 /// These helper callbacks are placed in an anonymous namespace to
1182 /// permit their use as function template parameters.
1183 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1184   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1185 }
1186 
1187 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1188   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1189                              CK_IntegralComplexCast);
1190 }
1191 }
1192 
1193 /// Handle integer arithmetic conversions.  Helper function of
1194 /// UsualArithmeticConversions()
1195 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1196 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1197                                         ExprResult &RHS, QualType LHSType,
1198                                         QualType RHSType, bool IsCompAssign) {
1199   // The rules for this case are in C99 6.3.1.8
1200   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1201   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1202   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1203   if (LHSSigned == RHSSigned) {
1204     // Same signedness; use the higher-ranked type
1205     if (order >= 0) {
1206       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1207       return LHSType;
1208     } else if (!IsCompAssign)
1209       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1210     return RHSType;
1211   } else if (order != (LHSSigned ? 1 : -1)) {
1212     // The unsigned type has greater than or equal rank to the
1213     // signed type, so use the unsigned type
1214     if (RHSSigned) {
1215       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1216       return LHSType;
1217     } else if (!IsCompAssign)
1218       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1219     return RHSType;
1220   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1221     // The two types are different widths; if we are here, that
1222     // means the signed type is larger than the unsigned type, so
1223     // use the signed type.
1224     if (LHSSigned) {
1225       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1226       return LHSType;
1227     } else if (!IsCompAssign)
1228       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1229     return RHSType;
1230   } else {
1231     // The signed type is higher-ranked than the unsigned type,
1232     // but isn't actually any bigger (like unsigned int and long
1233     // on most 32-bit systems).  Use the unsigned type corresponding
1234     // to the signed type.
1235     QualType result =
1236       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1237     RHS = (*doRHSCast)(S, RHS.get(), result);
1238     if (!IsCompAssign)
1239       LHS = (*doLHSCast)(S, LHS.get(), result);
1240     return result;
1241   }
1242 }
1243 
1244 /// Handle conversions with GCC complex int extension.  Helper function
1245 /// of UsualArithmeticConversions()
1246 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1247                                            ExprResult &RHS, QualType LHSType,
1248                                            QualType RHSType,
1249                                            bool IsCompAssign) {
1250   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1251   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1252 
1253   if (LHSComplexInt && RHSComplexInt) {
1254     QualType LHSEltType = LHSComplexInt->getElementType();
1255     QualType RHSEltType = RHSComplexInt->getElementType();
1256     QualType ScalarType =
1257       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1258         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1259 
1260     return S.Context.getComplexType(ScalarType);
1261   }
1262 
1263   if (LHSComplexInt) {
1264     QualType LHSEltType = LHSComplexInt->getElementType();
1265     QualType ScalarType =
1266       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1267         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1268     QualType ComplexType = S.Context.getComplexType(ScalarType);
1269     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1270                               CK_IntegralRealToComplex);
1271 
1272     return ComplexType;
1273   }
1274 
1275   assert(RHSComplexInt);
1276 
1277   QualType RHSEltType = RHSComplexInt->getElementType();
1278   QualType ScalarType =
1279     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1280       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1281   QualType ComplexType = S.Context.getComplexType(ScalarType);
1282 
1283   if (!IsCompAssign)
1284     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1285                               CK_IntegralRealToComplex);
1286   return ComplexType;
1287 }
1288 
1289 /// Return the rank of a given fixed point or integer type. The value itself
1290 /// doesn't matter, but the values must be increasing with proper increasing
1291 /// rank as described in N1169 4.1.1.
1292 static unsigned GetFixedPointRank(QualType Ty) {
1293   const auto *BTy = Ty->getAs<BuiltinType>();
1294   assert(BTy && "Expected a builtin type.");
1295 
1296   switch (BTy->getKind()) {
1297   case BuiltinType::ShortFract:
1298   case BuiltinType::UShortFract:
1299   case BuiltinType::SatShortFract:
1300   case BuiltinType::SatUShortFract:
1301     return 1;
1302   case BuiltinType::Fract:
1303   case BuiltinType::UFract:
1304   case BuiltinType::SatFract:
1305   case BuiltinType::SatUFract:
1306     return 2;
1307   case BuiltinType::LongFract:
1308   case BuiltinType::ULongFract:
1309   case BuiltinType::SatLongFract:
1310   case BuiltinType::SatULongFract:
1311     return 3;
1312   case BuiltinType::ShortAccum:
1313   case BuiltinType::UShortAccum:
1314   case BuiltinType::SatShortAccum:
1315   case BuiltinType::SatUShortAccum:
1316     return 4;
1317   case BuiltinType::Accum:
1318   case BuiltinType::UAccum:
1319   case BuiltinType::SatAccum:
1320   case BuiltinType::SatUAccum:
1321     return 5;
1322   case BuiltinType::LongAccum:
1323   case BuiltinType::ULongAccum:
1324   case BuiltinType::SatLongAccum:
1325   case BuiltinType::SatULongAccum:
1326     return 6;
1327   default:
1328     if (BTy->isInteger())
1329       return 0;
1330     llvm_unreachable("Unexpected fixed point or integer type");
1331   }
1332 }
1333 
1334 /// handleFixedPointConversion - Fixed point operations between fixed
1335 /// point types and integers or other fixed point types do not fall under
1336 /// usual arithmetic conversion since these conversions could result in loss
1337 /// of precsision (N1169 4.1.4). These operations should be calculated with
1338 /// the full precision of their result type (N1169 4.1.6.2.1).
1339 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1340                                            QualType RHSTy) {
1341   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1342          "Expected at least one of the operands to be a fixed point type");
1343   assert((LHSTy->isFixedPointOrIntegerType() ||
1344           RHSTy->isFixedPointOrIntegerType()) &&
1345          "Special fixed point arithmetic operation conversions are only "
1346          "applied to ints or other fixed point types");
1347 
1348   // If one operand has signed fixed-point type and the other operand has
1349   // unsigned fixed-point type, then the unsigned fixed-point operand is
1350   // converted to its corresponding signed fixed-point type and the resulting
1351   // type is the type of the converted operand.
1352   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1353     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1354   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1355     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1356 
1357   // The result type is the type with the highest rank, whereby a fixed-point
1358   // conversion rank is always greater than an integer conversion rank; if the
1359   // type of either of the operands is a saturating fixedpoint type, the result
1360   // type shall be the saturating fixed-point type corresponding to the type
1361   // with the highest rank; the resulting value is converted (taking into
1362   // account rounding and overflow) to the precision of the resulting type.
1363   // Same ranks between signed and unsigned types are resolved earlier, so both
1364   // types are either signed or both unsigned at this point.
1365   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1366   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1367 
1368   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1369 
1370   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1371     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1372 
1373   return ResultTy;
1374 }
1375 
1376 /// Check that the usual arithmetic conversions can be performed on this pair of
1377 /// expressions that might be of enumeration type.
1378 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1379                                            SourceLocation Loc,
1380                                            Sema::ArithConvKind ACK) {
1381   // C++2a [expr.arith.conv]p1:
1382   //   If one operand is of enumeration type and the other operand is of a
1383   //   different enumeration type or a floating-point type, this behavior is
1384   //   deprecated ([depr.arith.conv.enum]).
1385   //
1386   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1387   // Eventually we will presumably reject these cases (in C++23 onwards?).
1388   QualType L = LHS->getType(), R = RHS->getType();
1389   bool LEnum = L->isUnscopedEnumerationType(),
1390        REnum = R->isUnscopedEnumerationType();
1391   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1392   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1393       (REnum && L->isFloatingType())) {
1394     S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1395                     ? diag::warn_arith_conv_enum_float_cxx2a
1396                     : diag::warn_arith_conv_enum_float)
1397         << LHS->getSourceRange() << RHS->getSourceRange()
1398         << (int)ACK << LEnum << L << R;
1399   } else if (!IsCompAssign && LEnum && REnum &&
1400              !S.Context.hasSameUnqualifiedType(L, R)) {
1401     unsigned DiagID;
1402     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1403         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1404       // If either enumeration type is unnamed, it's less likely that the
1405       // user cares about this, but this situation is still deprecated in
1406       // C++2a. Use a different warning group.
1407       DiagID = S.getLangOpts().CPlusPlus2a
1408                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1409                     : diag::warn_arith_conv_mixed_anon_enum_types;
1410     } else if (ACK == Sema::ACK_Conditional) {
1411       // Conditional expressions are separated out because they have
1412       // historically had a different warning flag.
1413       DiagID = S.getLangOpts().CPlusPlus2a
1414                    ? diag::warn_conditional_mixed_enum_types_cxx2a
1415                    : diag::warn_conditional_mixed_enum_types;
1416     } else if (ACK == Sema::ACK_Comparison) {
1417       // Comparison expressions are separated out because they have
1418       // historically had a different warning flag.
1419       DiagID = S.getLangOpts().CPlusPlus2a
1420                    ? diag::warn_comparison_mixed_enum_types_cxx2a
1421                    : diag::warn_comparison_mixed_enum_types;
1422     } else {
1423       DiagID = S.getLangOpts().CPlusPlus2a
1424                    ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1425                    : diag::warn_arith_conv_mixed_enum_types;
1426     }
1427     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1428                         << (int)ACK << L << R;
1429   }
1430 }
1431 
1432 /// UsualArithmeticConversions - Performs various conversions that are common to
1433 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1434 /// routine returns the first non-arithmetic type found. The client is
1435 /// responsible for emitting appropriate error diagnostics.
1436 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1437                                           SourceLocation Loc,
1438                                           ArithConvKind ACK) {
1439   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1440 
1441   if (ACK != ACK_CompAssign) {
1442     LHS = UsualUnaryConversions(LHS.get());
1443     if (LHS.isInvalid())
1444       return QualType();
1445   }
1446 
1447   RHS = UsualUnaryConversions(RHS.get());
1448   if (RHS.isInvalid())
1449     return QualType();
1450 
1451   // For conversion purposes, we ignore any qualifiers.
1452   // For example, "const float" and "float" are equivalent.
1453   QualType LHSType =
1454     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1455   QualType RHSType =
1456     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1457 
1458   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1459   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1460     LHSType = AtomicLHS->getValueType();
1461 
1462   // If both types are identical, no conversion is needed.
1463   if (LHSType == RHSType)
1464     return LHSType;
1465 
1466   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1467   // The caller can deal with this (e.g. pointer + int).
1468   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1469     return QualType();
1470 
1471   // Apply unary and bitfield promotions to the LHS's type.
1472   QualType LHSUnpromotedType = LHSType;
1473   if (LHSType->isPromotableIntegerType())
1474     LHSType = Context.getPromotedIntegerType(LHSType);
1475   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1476   if (!LHSBitfieldPromoteTy.isNull())
1477     LHSType = LHSBitfieldPromoteTy;
1478   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1479     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1480 
1481   // If both types are identical, no conversion is needed.
1482   if (LHSType == RHSType)
1483     return LHSType;
1484 
1485   // At this point, we have two different arithmetic types.
1486 
1487   // Diagnose attempts to convert between __float128 and long double where
1488   // such conversions currently can't be handled.
1489   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1490     return QualType();
1491 
1492   // Handle complex types first (C99 6.3.1.8p1).
1493   if (LHSType->isComplexType() || RHSType->isComplexType())
1494     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1495                                         ACK == ACK_CompAssign);
1496 
1497   // Now handle "real" floating types (i.e. float, double, long double).
1498   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1499     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1500                                  ACK == ACK_CompAssign);
1501 
1502   // Handle GCC complex int extension.
1503   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1504     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1505                                       ACK == ACK_CompAssign);
1506 
1507   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1508     return handleFixedPointConversion(*this, LHSType, RHSType);
1509 
1510   // Finally, we have two differing integer types.
1511   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1512            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1513 }
1514 
1515 //===----------------------------------------------------------------------===//
1516 //  Semantic Analysis for various Expression Types
1517 //===----------------------------------------------------------------------===//
1518 
1519 
1520 ExprResult
1521 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1522                                 SourceLocation DefaultLoc,
1523                                 SourceLocation RParenLoc,
1524                                 Expr *ControllingExpr,
1525                                 ArrayRef<ParsedType> ArgTypes,
1526                                 ArrayRef<Expr *> ArgExprs) {
1527   unsigned NumAssocs = ArgTypes.size();
1528   assert(NumAssocs == ArgExprs.size());
1529 
1530   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1531   for (unsigned i = 0; i < NumAssocs; ++i) {
1532     if (ArgTypes[i])
1533       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1534     else
1535       Types[i] = nullptr;
1536   }
1537 
1538   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1539                                              ControllingExpr,
1540                                              llvm::makeArrayRef(Types, NumAssocs),
1541                                              ArgExprs);
1542   delete [] Types;
1543   return ER;
1544 }
1545 
1546 ExprResult
1547 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1548                                  SourceLocation DefaultLoc,
1549                                  SourceLocation RParenLoc,
1550                                  Expr *ControllingExpr,
1551                                  ArrayRef<TypeSourceInfo *> Types,
1552                                  ArrayRef<Expr *> Exprs) {
1553   unsigned NumAssocs = Types.size();
1554   assert(NumAssocs == Exprs.size());
1555 
1556   // Decay and strip qualifiers for the controlling expression type, and handle
1557   // placeholder type replacement. See committee discussion from WG14 DR423.
1558   {
1559     EnterExpressionEvaluationContext Unevaluated(
1560         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1561     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1562     if (R.isInvalid())
1563       return ExprError();
1564     ControllingExpr = R.get();
1565   }
1566 
1567   // The controlling expression is an unevaluated operand, so side effects are
1568   // likely unintended.
1569   if (!inTemplateInstantiation() &&
1570       ControllingExpr->HasSideEffects(Context, false))
1571     Diag(ControllingExpr->getExprLoc(),
1572          diag::warn_side_effects_unevaluated_context);
1573 
1574   bool TypeErrorFound = false,
1575        IsResultDependent = ControllingExpr->isTypeDependent(),
1576        ContainsUnexpandedParameterPack
1577          = ControllingExpr->containsUnexpandedParameterPack();
1578 
1579   for (unsigned i = 0; i < NumAssocs; ++i) {
1580     if (Exprs[i]->containsUnexpandedParameterPack())
1581       ContainsUnexpandedParameterPack = true;
1582 
1583     if (Types[i]) {
1584       if (Types[i]->getType()->containsUnexpandedParameterPack())
1585         ContainsUnexpandedParameterPack = true;
1586 
1587       if (Types[i]->getType()->isDependentType()) {
1588         IsResultDependent = true;
1589       } else {
1590         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1591         // complete object type other than a variably modified type."
1592         unsigned D = 0;
1593         if (Types[i]->getType()->isIncompleteType())
1594           D = diag::err_assoc_type_incomplete;
1595         else if (!Types[i]->getType()->isObjectType())
1596           D = diag::err_assoc_type_nonobject;
1597         else if (Types[i]->getType()->isVariablyModifiedType())
1598           D = diag::err_assoc_type_variably_modified;
1599 
1600         if (D != 0) {
1601           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1602             << Types[i]->getTypeLoc().getSourceRange()
1603             << Types[i]->getType();
1604           TypeErrorFound = true;
1605         }
1606 
1607         // C11 6.5.1.1p2 "No two generic associations in the same generic
1608         // selection shall specify compatible types."
1609         for (unsigned j = i+1; j < NumAssocs; ++j)
1610           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1611               Context.typesAreCompatible(Types[i]->getType(),
1612                                          Types[j]->getType())) {
1613             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1614                  diag::err_assoc_compatible_types)
1615               << Types[j]->getTypeLoc().getSourceRange()
1616               << Types[j]->getType()
1617               << Types[i]->getType();
1618             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1619                  diag::note_compat_assoc)
1620               << Types[i]->getTypeLoc().getSourceRange()
1621               << Types[i]->getType();
1622             TypeErrorFound = true;
1623           }
1624       }
1625     }
1626   }
1627   if (TypeErrorFound)
1628     return ExprError();
1629 
1630   // If we determined that the generic selection is result-dependent, don't
1631   // try to compute the result expression.
1632   if (IsResultDependent)
1633     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1634                                         Exprs, DefaultLoc, RParenLoc,
1635                                         ContainsUnexpandedParameterPack);
1636 
1637   SmallVector<unsigned, 1> CompatIndices;
1638   unsigned DefaultIndex = -1U;
1639   for (unsigned i = 0; i < NumAssocs; ++i) {
1640     if (!Types[i])
1641       DefaultIndex = i;
1642     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1643                                         Types[i]->getType()))
1644       CompatIndices.push_back(i);
1645   }
1646 
1647   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1648   // type compatible with at most one of the types named in its generic
1649   // association list."
1650   if (CompatIndices.size() > 1) {
1651     // We strip parens here because the controlling expression is typically
1652     // parenthesized in macro definitions.
1653     ControllingExpr = ControllingExpr->IgnoreParens();
1654     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1655         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1656         << (unsigned)CompatIndices.size();
1657     for (unsigned I : CompatIndices) {
1658       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1659            diag::note_compat_assoc)
1660         << Types[I]->getTypeLoc().getSourceRange()
1661         << Types[I]->getType();
1662     }
1663     return ExprError();
1664   }
1665 
1666   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1667   // its controlling expression shall have type compatible with exactly one of
1668   // the types named in its generic association list."
1669   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1670     // We strip parens here because the controlling expression is typically
1671     // parenthesized in macro definitions.
1672     ControllingExpr = ControllingExpr->IgnoreParens();
1673     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1674         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1675     return ExprError();
1676   }
1677 
1678   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1679   // type name that is compatible with the type of the controlling expression,
1680   // then the result expression of the generic selection is the expression
1681   // in that generic association. Otherwise, the result expression of the
1682   // generic selection is the expression in the default generic association."
1683   unsigned ResultIndex =
1684     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1685 
1686   return GenericSelectionExpr::Create(
1687       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1688       ContainsUnexpandedParameterPack, ResultIndex);
1689 }
1690 
1691 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1692 /// location of the token and the offset of the ud-suffix within it.
1693 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1694                                      unsigned Offset) {
1695   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1696                                         S.getLangOpts());
1697 }
1698 
1699 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1700 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1701 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1702                                                  IdentifierInfo *UDSuffix,
1703                                                  SourceLocation UDSuffixLoc,
1704                                                  ArrayRef<Expr*> Args,
1705                                                  SourceLocation LitEndLoc) {
1706   assert(Args.size() <= 2 && "too many arguments for literal operator");
1707 
1708   QualType ArgTy[2];
1709   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1710     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1711     if (ArgTy[ArgIdx]->isArrayType())
1712       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1713   }
1714 
1715   DeclarationName OpName =
1716     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1717   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1718   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1719 
1720   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1721   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1722                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1723                               /*AllowStringTemplate*/ false,
1724                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1725     return ExprError();
1726 
1727   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1728 }
1729 
1730 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1731 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1732 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1733 /// multiple tokens.  However, the common case is that StringToks points to one
1734 /// string.
1735 ///
1736 ExprResult
1737 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1738   assert(!StringToks.empty() && "Must have at least one string!");
1739 
1740   StringLiteralParser Literal(StringToks, PP);
1741   if (Literal.hadError)
1742     return ExprError();
1743 
1744   SmallVector<SourceLocation, 4> StringTokLocs;
1745   for (const Token &Tok : StringToks)
1746     StringTokLocs.push_back(Tok.getLocation());
1747 
1748   QualType CharTy = Context.CharTy;
1749   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1750   if (Literal.isWide()) {
1751     CharTy = Context.getWideCharType();
1752     Kind = StringLiteral::Wide;
1753   } else if (Literal.isUTF8()) {
1754     if (getLangOpts().Char8)
1755       CharTy = Context.Char8Ty;
1756     Kind = StringLiteral::UTF8;
1757   } else if (Literal.isUTF16()) {
1758     CharTy = Context.Char16Ty;
1759     Kind = StringLiteral::UTF16;
1760   } else if (Literal.isUTF32()) {
1761     CharTy = Context.Char32Ty;
1762     Kind = StringLiteral::UTF32;
1763   } else if (Literal.isPascal()) {
1764     CharTy = Context.UnsignedCharTy;
1765   }
1766 
1767   // Warn on initializing an array of char from a u8 string literal; this
1768   // becomes ill-formed in C++2a.
1769   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1770       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1771     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1772 
1773     // Create removals for all 'u8' prefixes in the string literal(s). This
1774     // ensures C++2a compatibility (but may change the program behavior when
1775     // built by non-Clang compilers for which the execution character set is
1776     // not always UTF-8).
1777     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1778     SourceLocation RemovalDiagLoc;
1779     for (const Token &Tok : StringToks) {
1780       if (Tok.getKind() == tok::utf8_string_literal) {
1781         if (RemovalDiagLoc.isInvalid())
1782           RemovalDiagLoc = Tok.getLocation();
1783         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1784             Tok.getLocation(),
1785             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1786                                            getSourceManager(), getLangOpts())));
1787       }
1788     }
1789     Diag(RemovalDiagLoc, RemovalDiag);
1790   }
1791 
1792   QualType StrTy =
1793       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1794 
1795   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1796   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1797                                              Kind, Literal.Pascal, StrTy,
1798                                              &StringTokLocs[0],
1799                                              StringTokLocs.size());
1800   if (Literal.getUDSuffix().empty())
1801     return Lit;
1802 
1803   // We're building a user-defined literal.
1804   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1805   SourceLocation UDSuffixLoc =
1806     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1807                    Literal.getUDSuffixOffset());
1808 
1809   // Make sure we're allowed user-defined literals here.
1810   if (!UDLScope)
1811     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1812 
1813   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1814   //   operator "" X (str, len)
1815   QualType SizeType = Context.getSizeType();
1816 
1817   DeclarationName OpName =
1818     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1819   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1820   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1821 
1822   QualType ArgTy[] = {
1823     Context.getArrayDecayedType(StrTy), SizeType
1824   };
1825 
1826   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1827   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1828                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1829                                 /*AllowStringTemplate*/ true,
1830                                 /*DiagnoseMissing*/ true)) {
1831 
1832   case LOLR_Cooked: {
1833     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1834     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1835                                                     StringTokLocs[0]);
1836     Expr *Args[] = { Lit, LenArg };
1837 
1838     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1839   }
1840 
1841   case LOLR_StringTemplate: {
1842     TemplateArgumentListInfo ExplicitArgs;
1843 
1844     unsigned CharBits = Context.getIntWidth(CharTy);
1845     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1846     llvm::APSInt Value(CharBits, CharIsUnsigned);
1847 
1848     TemplateArgument TypeArg(CharTy);
1849     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1850     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1851 
1852     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1853       Value = Lit->getCodeUnit(I);
1854       TemplateArgument Arg(Context, Value, CharTy);
1855       TemplateArgumentLocInfo ArgInfo;
1856       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1857     }
1858     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1859                                     &ExplicitArgs);
1860   }
1861   case LOLR_Raw:
1862   case LOLR_Template:
1863   case LOLR_ErrorNoDiagnostic:
1864     llvm_unreachable("unexpected literal operator lookup result");
1865   case LOLR_Error:
1866     return ExprError();
1867   }
1868   llvm_unreachable("unexpected literal operator lookup result");
1869 }
1870 
1871 DeclRefExpr *
1872 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1873                        SourceLocation Loc,
1874                        const CXXScopeSpec *SS) {
1875   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1876   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1877 }
1878 
1879 DeclRefExpr *
1880 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1881                        const DeclarationNameInfo &NameInfo,
1882                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1883                        SourceLocation TemplateKWLoc,
1884                        const TemplateArgumentListInfo *TemplateArgs) {
1885   NestedNameSpecifierLoc NNS =
1886       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1887   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1888                           TemplateArgs);
1889 }
1890 
1891 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1892   // A declaration named in an unevaluated operand never constitutes an odr-use.
1893   if (isUnevaluatedContext())
1894     return NOUR_Unevaluated;
1895 
1896   // C++2a [basic.def.odr]p4:
1897   //   A variable x whose name appears as a potentially-evaluated expression e
1898   //   is odr-used by e unless [...] x is a reference that is usable in
1899   //   constant expressions.
1900   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1901     if (VD->getType()->isReferenceType() &&
1902         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1903         VD->isUsableInConstantExpressions(Context))
1904       return NOUR_Constant;
1905   }
1906 
1907   // All remaining non-variable cases constitute an odr-use. For variables, we
1908   // need to wait and see how the expression is used.
1909   return NOUR_None;
1910 }
1911 
1912 /// BuildDeclRefExpr - Build an expression that references a
1913 /// declaration that does not require a closure capture.
1914 DeclRefExpr *
1915 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1916                        const DeclarationNameInfo &NameInfo,
1917                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1918                        SourceLocation TemplateKWLoc,
1919                        const TemplateArgumentListInfo *TemplateArgs) {
1920   bool RefersToCapturedVariable =
1921       isa<VarDecl>(D) &&
1922       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1923 
1924   DeclRefExpr *E = DeclRefExpr::Create(
1925       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1926       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1927   MarkDeclRefReferenced(E);
1928 
1929   // C++ [except.spec]p17:
1930   //   An exception-specification is considered to be needed when:
1931   //   - in an expression, the function is the unique lookup result or
1932   //     the selected member of a set of overloaded functions.
1933   //
1934   // We delay doing this until after we've built the function reference and
1935   // marked it as used so that:
1936   //  a) if the function is defaulted, we get errors from defining it before /
1937   //     instead of errors from computing its exception specification, and
1938   //  b) if the function is a defaulted comparison, we can use the body we
1939   //     build when defining it as input to the exception specification
1940   //     computation rather than computing a new body.
1941   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1942     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1943       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1944         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1945     }
1946   }
1947 
1948   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1949       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1950       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1951     getCurFunction()->recordUseOfWeak(E);
1952 
1953   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1954   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1955     FD = IFD->getAnonField();
1956   if (FD) {
1957     UnusedPrivateFields.remove(FD);
1958     // Just in case we're building an illegal pointer-to-member.
1959     if (FD->isBitField())
1960       E->setObjectKind(OK_BitField);
1961   }
1962 
1963   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1964   // designates a bit-field.
1965   if (auto *BD = dyn_cast<BindingDecl>(D))
1966     if (auto *BE = BD->getBinding())
1967       E->setObjectKind(BE->getObjectKind());
1968 
1969   return E;
1970 }
1971 
1972 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1973 /// possibly a list of template arguments.
1974 ///
1975 /// If this produces template arguments, it is permitted to call
1976 /// DecomposeTemplateName.
1977 ///
1978 /// This actually loses a lot of source location information for
1979 /// non-standard name kinds; we should consider preserving that in
1980 /// some way.
1981 void
1982 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1983                              TemplateArgumentListInfo &Buffer,
1984                              DeclarationNameInfo &NameInfo,
1985                              const TemplateArgumentListInfo *&TemplateArgs) {
1986   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1987     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1988     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1989 
1990     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1991                                        Id.TemplateId->NumArgs);
1992     translateTemplateArguments(TemplateArgsPtr, Buffer);
1993 
1994     TemplateName TName = Id.TemplateId->Template.get();
1995     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1996     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1997     TemplateArgs = &Buffer;
1998   } else {
1999     NameInfo = GetNameFromUnqualifiedId(Id);
2000     TemplateArgs = nullptr;
2001   }
2002 }
2003 
2004 static void emitEmptyLookupTypoDiagnostic(
2005     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2006     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2007     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2008   DeclContext *Ctx =
2009       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2010   if (!TC) {
2011     // Emit a special diagnostic for failed member lookups.
2012     // FIXME: computing the declaration context might fail here (?)
2013     if (Ctx)
2014       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2015                                                  << SS.getRange();
2016     else
2017       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2018     return;
2019   }
2020 
2021   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2022   bool DroppedSpecifier =
2023       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2024   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2025                         ? diag::note_implicit_param_decl
2026                         : diag::note_previous_decl;
2027   if (!Ctx)
2028     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2029                          SemaRef.PDiag(NoteID));
2030   else
2031     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2032                                  << Typo << Ctx << DroppedSpecifier
2033                                  << SS.getRange(),
2034                          SemaRef.PDiag(NoteID));
2035 }
2036 
2037 /// Diagnose an empty lookup.
2038 ///
2039 /// \return false if new lookup candidates were found
2040 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2041                                CorrectionCandidateCallback &CCC,
2042                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2043                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2044   DeclarationName Name = R.getLookupName();
2045 
2046   unsigned diagnostic = diag::err_undeclared_var_use;
2047   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2048   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2049       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2050       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2051     diagnostic = diag::err_undeclared_use;
2052     diagnostic_suggest = diag::err_undeclared_use_suggest;
2053   }
2054 
2055   // If the original lookup was an unqualified lookup, fake an
2056   // unqualified lookup.  This is useful when (for example) the
2057   // original lookup would not have found something because it was a
2058   // dependent name.
2059   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2060   while (DC) {
2061     if (isa<CXXRecordDecl>(DC)) {
2062       LookupQualifiedName(R, DC);
2063 
2064       if (!R.empty()) {
2065         // Don't give errors about ambiguities in this lookup.
2066         R.suppressDiagnostics();
2067 
2068         // During a default argument instantiation the CurContext points
2069         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2070         // function parameter list, hence add an explicit check.
2071         bool isDefaultArgument =
2072             !CodeSynthesisContexts.empty() &&
2073             CodeSynthesisContexts.back().Kind ==
2074                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2075         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2076         bool isInstance = CurMethod &&
2077                           CurMethod->isInstance() &&
2078                           DC == CurMethod->getParent() && !isDefaultArgument;
2079 
2080         // Give a code modification hint to insert 'this->'.
2081         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2082         // Actually quite difficult!
2083         if (getLangOpts().MSVCCompat)
2084           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2085         if (isInstance) {
2086           Diag(R.getNameLoc(), diagnostic) << Name
2087             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2088           CheckCXXThisCapture(R.getNameLoc());
2089         } else {
2090           Diag(R.getNameLoc(), diagnostic) << Name;
2091         }
2092 
2093         // Do we really want to note all of these?
2094         for (NamedDecl *D : R)
2095           Diag(D->getLocation(), diag::note_dependent_var_use);
2096 
2097         // Return true if we are inside a default argument instantiation
2098         // and the found name refers to an instance member function, otherwise
2099         // the function calling DiagnoseEmptyLookup will try to create an
2100         // implicit member call and this is wrong for default argument.
2101         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2102           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2103           return true;
2104         }
2105 
2106         // Tell the callee to try to recover.
2107         return false;
2108       }
2109 
2110       R.clear();
2111     }
2112 
2113     DC = DC->getLookupParent();
2114   }
2115 
2116   // We didn't find anything, so try to correct for a typo.
2117   TypoCorrection Corrected;
2118   if (S && Out) {
2119     SourceLocation TypoLoc = R.getNameLoc();
2120     assert(!ExplicitTemplateArgs &&
2121            "Diagnosing an empty lookup with explicit template args!");
2122     *Out = CorrectTypoDelayed(
2123         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2124         [=](const TypoCorrection &TC) {
2125           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2126                                         diagnostic, diagnostic_suggest);
2127         },
2128         nullptr, CTK_ErrorRecovery);
2129     if (*Out)
2130       return true;
2131   } else if (S &&
2132              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2133                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2134     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2135     bool DroppedSpecifier =
2136         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2137     R.setLookupName(Corrected.getCorrection());
2138 
2139     bool AcceptableWithRecovery = false;
2140     bool AcceptableWithoutRecovery = false;
2141     NamedDecl *ND = Corrected.getFoundDecl();
2142     if (ND) {
2143       if (Corrected.isOverloaded()) {
2144         OverloadCandidateSet OCS(R.getNameLoc(),
2145                                  OverloadCandidateSet::CSK_Normal);
2146         OverloadCandidateSet::iterator Best;
2147         for (NamedDecl *CD : Corrected) {
2148           if (FunctionTemplateDecl *FTD =
2149                    dyn_cast<FunctionTemplateDecl>(CD))
2150             AddTemplateOverloadCandidate(
2151                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2152                 Args, OCS);
2153           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2154             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2155               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2156                                    Args, OCS);
2157         }
2158         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2159         case OR_Success:
2160           ND = Best->FoundDecl;
2161           Corrected.setCorrectionDecl(ND);
2162           break;
2163         default:
2164           // FIXME: Arbitrarily pick the first declaration for the note.
2165           Corrected.setCorrectionDecl(ND);
2166           break;
2167         }
2168       }
2169       R.addDecl(ND);
2170       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2171         CXXRecordDecl *Record = nullptr;
2172         if (Corrected.getCorrectionSpecifier()) {
2173           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2174           Record = Ty->getAsCXXRecordDecl();
2175         }
2176         if (!Record)
2177           Record = cast<CXXRecordDecl>(
2178               ND->getDeclContext()->getRedeclContext());
2179         R.setNamingClass(Record);
2180       }
2181 
2182       auto *UnderlyingND = ND->getUnderlyingDecl();
2183       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2184                                isa<FunctionTemplateDecl>(UnderlyingND);
2185       // FIXME: If we ended up with a typo for a type name or
2186       // Objective-C class name, we're in trouble because the parser
2187       // is in the wrong place to recover. Suggest the typo
2188       // correction, but don't make it a fix-it since we're not going
2189       // to recover well anyway.
2190       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2191                                   getAsTypeTemplateDecl(UnderlyingND) ||
2192                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2193     } else {
2194       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2195       // because we aren't able to recover.
2196       AcceptableWithoutRecovery = true;
2197     }
2198 
2199     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2200       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2201                             ? diag::note_implicit_param_decl
2202                             : diag::note_previous_decl;
2203       if (SS.isEmpty())
2204         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2205                      PDiag(NoteID), AcceptableWithRecovery);
2206       else
2207         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2208                                   << Name << computeDeclContext(SS, false)
2209                                   << DroppedSpecifier << SS.getRange(),
2210                      PDiag(NoteID), AcceptableWithRecovery);
2211 
2212       // Tell the callee whether to try to recover.
2213       return !AcceptableWithRecovery;
2214     }
2215   }
2216   R.clear();
2217 
2218   // Emit a special diagnostic for failed member lookups.
2219   // FIXME: computing the declaration context might fail here (?)
2220   if (!SS.isEmpty()) {
2221     Diag(R.getNameLoc(), diag::err_no_member)
2222       << Name << computeDeclContext(SS, false)
2223       << SS.getRange();
2224     return true;
2225   }
2226 
2227   // Give up, we can't recover.
2228   Diag(R.getNameLoc(), diagnostic) << Name;
2229   return true;
2230 }
2231 
2232 /// In Microsoft mode, if we are inside a template class whose parent class has
2233 /// dependent base classes, and we can't resolve an unqualified identifier, then
2234 /// assume the identifier is a member of a dependent base class.  We can only
2235 /// recover successfully in static methods, instance methods, and other contexts
2236 /// where 'this' is available.  This doesn't precisely match MSVC's
2237 /// instantiation model, but it's close enough.
2238 static Expr *
2239 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2240                                DeclarationNameInfo &NameInfo,
2241                                SourceLocation TemplateKWLoc,
2242                                const TemplateArgumentListInfo *TemplateArgs) {
2243   // Only try to recover from lookup into dependent bases in static methods or
2244   // contexts where 'this' is available.
2245   QualType ThisType = S.getCurrentThisType();
2246   const CXXRecordDecl *RD = nullptr;
2247   if (!ThisType.isNull())
2248     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2249   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2250     RD = MD->getParent();
2251   if (!RD || !RD->hasAnyDependentBases())
2252     return nullptr;
2253 
2254   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2255   // is available, suggest inserting 'this->' as a fixit.
2256   SourceLocation Loc = NameInfo.getLoc();
2257   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2258   DB << NameInfo.getName() << RD;
2259 
2260   if (!ThisType.isNull()) {
2261     DB << FixItHint::CreateInsertion(Loc, "this->");
2262     return CXXDependentScopeMemberExpr::Create(
2263         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2264         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2265         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2266   }
2267 
2268   // Synthesize a fake NNS that points to the derived class.  This will
2269   // perform name lookup during template instantiation.
2270   CXXScopeSpec SS;
2271   auto *NNS =
2272       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2273   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2274   return DependentScopeDeclRefExpr::Create(
2275       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2276       TemplateArgs);
2277 }
2278 
2279 ExprResult
2280 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2281                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2282                         bool HasTrailingLParen, bool IsAddressOfOperand,
2283                         CorrectionCandidateCallback *CCC,
2284                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2285   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2286          "cannot be direct & operand and have a trailing lparen");
2287   if (SS.isInvalid())
2288     return ExprError();
2289 
2290   TemplateArgumentListInfo TemplateArgsBuffer;
2291 
2292   // Decompose the UnqualifiedId into the following data.
2293   DeclarationNameInfo NameInfo;
2294   const TemplateArgumentListInfo *TemplateArgs;
2295   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2296 
2297   DeclarationName Name = NameInfo.getName();
2298   IdentifierInfo *II = Name.getAsIdentifierInfo();
2299   SourceLocation NameLoc = NameInfo.getLoc();
2300 
2301   if (II && II->isEditorPlaceholder()) {
2302     // FIXME: When typed placeholders are supported we can create a typed
2303     // placeholder expression node.
2304     return ExprError();
2305   }
2306 
2307   // C++ [temp.dep.expr]p3:
2308   //   An id-expression is type-dependent if it contains:
2309   //     -- an identifier that was declared with a dependent type,
2310   //        (note: handled after lookup)
2311   //     -- a template-id that is dependent,
2312   //        (note: handled in BuildTemplateIdExpr)
2313   //     -- a conversion-function-id that specifies a dependent type,
2314   //     -- a nested-name-specifier that contains a class-name that
2315   //        names a dependent type.
2316   // Determine whether this is a member of an unknown specialization;
2317   // we need to handle these differently.
2318   bool DependentID = false;
2319   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2320       Name.getCXXNameType()->isDependentType()) {
2321     DependentID = true;
2322   } else if (SS.isSet()) {
2323     if (DeclContext *DC = computeDeclContext(SS, false)) {
2324       if (RequireCompleteDeclContext(SS, DC))
2325         return ExprError();
2326     } else {
2327       DependentID = true;
2328     }
2329   }
2330 
2331   if (DependentID)
2332     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2333                                       IsAddressOfOperand, TemplateArgs);
2334 
2335   // Perform the required lookup.
2336   LookupResult R(*this, NameInfo,
2337                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2338                      ? LookupObjCImplicitSelfParam
2339                      : LookupOrdinaryName);
2340   if (TemplateKWLoc.isValid() || TemplateArgs) {
2341     // Lookup the template name again to correctly establish the context in
2342     // which it was found. This is really unfortunate as we already did the
2343     // lookup to determine that it was a template name in the first place. If
2344     // this becomes a performance hit, we can work harder to preserve those
2345     // results until we get here but it's likely not worth it.
2346     bool MemberOfUnknownSpecialization;
2347     AssumedTemplateKind AssumedTemplate;
2348     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2349                            MemberOfUnknownSpecialization, TemplateKWLoc,
2350                            &AssumedTemplate))
2351       return ExprError();
2352 
2353     if (MemberOfUnknownSpecialization ||
2354         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2355       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2356                                         IsAddressOfOperand, TemplateArgs);
2357   } else {
2358     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2359     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2360 
2361     // If the result might be in a dependent base class, this is a dependent
2362     // id-expression.
2363     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2364       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2365                                         IsAddressOfOperand, TemplateArgs);
2366 
2367     // If this reference is in an Objective-C method, then we need to do
2368     // some special Objective-C lookup, too.
2369     if (IvarLookupFollowUp) {
2370       ExprResult E(LookupInObjCMethod(R, S, II, true));
2371       if (E.isInvalid())
2372         return ExprError();
2373 
2374       if (Expr *Ex = E.getAs<Expr>())
2375         return Ex;
2376     }
2377   }
2378 
2379   if (R.isAmbiguous())
2380     return ExprError();
2381 
2382   // This could be an implicitly declared function reference (legal in C90,
2383   // extension in C99, forbidden in C++).
2384   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2385     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2386     if (D) R.addDecl(D);
2387   }
2388 
2389   // Determine whether this name might be a candidate for
2390   // argument-dependent lookup.
2391   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2392 
2393   if (R.empty() && !ADL) {
2394     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2395       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2396                                                    TemplateKWLoc, TemplateArgs))
2397         return E;
2398     }
2399 
2400     // Don't diagnose an empty lookup for inline assembly.
2401     if (IsInlineAsmIdentifier)
2402       return ExprError();
2403 
2404     // If this name wasn't predeclared and if this is not a function
2405     // call, diagnose the problem.
2406     TypoExpr *TE = nullptr;
2407     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2408                                                        : nullptr);
2409     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2410     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2411            "Typo correction callback misconfigured");
2412     if (CCC) {
2413       // Make sure the callback knows what the typo being diagnosed is.
2414       CCC->setTypoName(II);
2415       if (SS.isValid())
2416         CCC->setTypoNNS(SS.getScopeRep());
2417     }
2418     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2419     // a template name, but we happen to have always already looked up the name
2420     // before we get here if it must be a template name.
2421     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2422                             None, &TE)) {
2423       if (TE && KeywordReplacement) {
2424         auto &State = getTypoExprState(TE);
2425         auto BestTC = State.Consumer->getNextCorrection();
2426         if (BestTC.isKeyword()) {
2427           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2428           if (State.DiagHandler)
2429             State.DiagHandler(BestTC);
2430           KeywordReplacement->startToken();
2431           KeywordReplacement->setKind(II->getTokenID());
2432           KeywordReplacement->setIdentifierInfo(II);
2433           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2434           // Clean up the state associated with the TypoExpr, since it has
2435           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2436           clearDelayedTypo(TE);
2437           // Signal that a correction to a keyword was performed by returning a
2438           // valid-but-null ExprResult.
2439           return (Expr*)nullptr;
2440         }
2441         State.Consumer->resetCorrectionStream();
2442       }
2443       return TE ? TE : ExprError();
2444     }
2445 
2446     assert(!R.empty() &&
2447            "DiagnoseEmptyLookup returned false but added no results");
2448 
2449     // If we found an Objective-C instance variable, let
2450     // LookupInObjCMethod build the appropriate expression to
2451     // reference the ivar.
2452     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2453       R.clear();
2454       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2455       // In a hopelessly buggy code, Objective-C instance variable
2456       // lookup fails and no expression will be built to reference it.
2457       if (!E.isInvalid() && !E.get())
2458         return ExprError();
2459       return E;
2460     }
2461   }
2462 
2463   // This is guaranteed from this point on.
2464   assert(!R.empty() || ADL);
2465 
2466   // Check whether this might be a C++ implicit instance member access.
2467   // C++ [class.mfct.non-static]p3:
2468   //   When an id-expression that is not part of a class member access
2469   //   syntax and not used to form a pointer to member is used in the
2470   //   body of a non-static member function of class X, if name lookup
2471   //   resolves the name in the id-expression to a non-static non-type
2472   //   member of some class C, the id-expression is transformed into a
2473   //   class member access expression using (*this) as the
2474   //   postfix-expression to the left of the . operator.
2475   //
2476   // But we don't actually need to do this for '&' operands if R
2477   // resolved to a function or overloaded function set, because the
2478   // expression is ill-formed if it actually works out to be a
2479   // non-static member function:
2480   //
2481   // C++ [expr.ref]p4:
2482   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2483   //   [t]he expression can be used only as the left-hand operand of a
2484   //   member function call.
2485   //
2486   // There are other safeguards against such uses, but it's important
2487   // to get this right here so that we don't end up making a
2488   // spuriously dependent expression if we're inside a dependent
2489   // instance method.
2490   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2491     bool MightBeImplicitMember;
2492     if (!IsAddressOfOperand)
2493       MightBeImplicitMember = true;
2494     else if (!SS.isEmpty())
2495       MightBeImplicitMember = false;
2496     else if (R.isOverloadedResult())
2497       MightBeImplicitMember = false;
2498     else if (R.isUnresolvableResult())
2499       MightBeImplicitMember = true;
2500     else
2501       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2502                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2503                               isa<MSPropertyDecl>(R.getFoundDecl());
2504 
2505     if (MightBeImplicitMember)
2506       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2507                                              R, TemplateArgs, S);
2508   }
2509 
2510   if (TemplateArgs || TemplateKWLoc.isValid()) {
2511 
2512     // In C++1y, if this is a variable template id, then check it
2513     // in BuildTemplateIdExpr().
2514     // The single lookup result must be a variable template declaration.
2515     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2516         Id.TemplateId->Kind == TNK_Var_template) {
2517       assert(R.getAsSingle<VarTemplateDecl>() &&
2518              "There should only be one declaration found.");
2519     }
2520 
2521     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2522   }
2523 
2524   return BuildDeclarationNameExpr(SS, R, ADL);
2525 }
2526 
2527 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2528 /// declaration name, generally during template instantiation.
2529 /// There's a large number of things which don't need to be done along
2530 /// this path.
2531 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2532     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2533     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2534   DeclContext *DC = computeDeclContext(SS, false);
2535   if (!DC)
2536     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2537                                      NameInfo, /*TemplateArgs=*/nullptr);
2538 
2539   if (RequireCompleteDeclContext(SS, DC))
2540     return ExprError();
2541 
2542   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2543   LookupQualifiedName(R, DC);
2544 
2545   if (R.isAmbiguous())
2546     return ExprError();
2547 
2548   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2549     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2550                                      NameInfo, /*TemplateArgs=*/nullptr);
2551 
2552   if (R.empty()) {
2553     Diag(NameInfo.getLoc(), diag::err_no_member)
2554       << NameInfo.getName() << DC << SS.getRange();
2555     return ExprError();
2556   }
2557 
2558   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2559     // Diagnose a missing typename if this resolved unambiguously to a type in
2560     // a dependent context.  If we can recover with a type, downgrade this to
2561     // a warning in Microsoft compatibility mode.
2562     unsigned DiagID = diag::err_typename_missing;
2563     if (RecoveryTSI && getLangOpts().MSVCCompat)
2564       DiagID = diag::ext_typename_missing;
2565     SourceLocation Loc = SS.getBeginLoc();
2566     auto D = Diag(Loc, DiagID);
2567     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2568       << SourceRange(Loc, NameInfo.getEndLoc());
2569 
2570     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2571     // context.
2572     if (!RecoveryTSI)
2573       return ExprError();
2574 
2575     // Only issue the fixit if we're prepared to recover.
2576     D << FixItHint::CreateInsertion(Loc, "typename ");
2577 
2578     // Recover by pretending this was an elaborated type.
2579     QualType Ty = Context.getTypeDeclType(TD);
2580     TypeLocBuilder TLB;
2581     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2582 
2583     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2584     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2585     QTL.setElaboratedKeywordLoc(SourceLocation());
2586     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2587 
2588     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2589 
2590     return ExprEmpty();
2591   }
2592 
2593   // Defend against this resolving to an implicit member access. We usually
2594   // won't get here if this might be a legitimate a class member (we end up in
2595   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2596   // a pointer-to-member or in an unevaluated context in C++11.
2597   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2598     return BuildPossibleImplicitMemberExpr(SS,
2599                                            /*TemplateKWLoc=*/SourceLocation(),
2600                                            R, /*TemplateArgs=*/nullptr, S);
2601 
2602   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2603 }
2604 
2605 /// The parser has read a name in, and Sema has detected that we're currently
2606 /// inside an ObjC method. Perform some additional checks and determine if we
2607 /// should form a reference to an ivar.
2608 ///
2609 /// Ideally, most of this would be done by lookup, but there's
2610 /// actually quite a lot of extra work involved.
2611 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2612                                         IdentifierInfo *II) {
2613   SourceLocation Loc = Lookup.getNameLoc();
2614   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2615 
2616   // Check for error condition which is already reported.
2617   if (!CurMethod)
2618     return DeclResult(true);
2619 
2620   // There are two cases to handle here.  1) scoped lookup could have failed,
2621   // in which case we should look for an ivar.  2) scoped lookup could have
2622   // found a decl, but that decl is outside the current instance method (i.e.
2623   // a global variable).  In these two cases, we do a lookup for an ivar with
2624   // this name, if the lookup sucedes, we replace it our current decl.
2625 
2626   // If we're in a class method, we don't normally want to look for
2627   // ivars.  But if we don't find anything else, and there's an
2628   // ivar, that's an error.
2629   bool IsClassMethod = CurMethod->isClassMethod();
2630 
2631   bool LookForIvars;
2632   if (Lookup.empty())
2633     LookForIvars = true;
2634   else if (IsClassMethod)
2635     LookForIvars = false;
2636   else
2637     LookForIvars = (Lookup.isSingleResult() &&
2638                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2639   ObjCInterfaceDecl *IFace = nullptr;
2640   if (LookForIvars) {
2641     IFace = CurMethod->getClassInterface();
2642     ObjCInterfaceDecl *ClassDeclared;
2643     ObjCIvarDecl *IV = nullptr;
2644     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2645       // Diagnose using an ivar in a class method.
2646       if (IsClassMethod) {
2647         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2648         return DeclResult(true);
2649       }
2650 
2651       // Diagnose the use of an ivar outside of the declaring class.
2652       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2653           !declaresSameEntity(ClassDeclared, IFace) &&
2654           !getLangOpts().DebuggerSupport)
2655         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2656 
2657       // Success.
2658       return IV;
2659     }
2660   } else if (CurMethod->isInstanceMethod()) {
2661     // We should warn if a local variable hides an ivar.
2662     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2663       ObjCInterfaceDecl *ClassDeclared;
2664       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2665         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2666             declaresSameEntity(IFace, ClassDeclared))
2667           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2668       }
2669     }
2670   } else if (Lookup.isSingleResult() &&
2671              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2672     // If accessing a stand-alone ivar in a class method, this is an error.
2673     if (const ObjCIvarDecl *IV =
2674             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2675       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2676       return DeclResult(true);
2677     }
2678   }
2679 
2680   // Didn't encounter an error, didn't find an ivar.
2681   return DeclResult(false);
2682 }
2683 
2684 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2685                                   ObjCIvarDecl *IV) {
2686   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2687   assert(CurMethod && CurMethod->isInstanceMethod() &&
2688          "should not reference ivar from this context");
2689 
2690   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2691   assert(IFace && "should not reference ivar from this context");
2692 
2693   // If we're referencing an invalid decl, just return this as a silent
2694   // error node.  The error diagnostic was already emitted on the decl.
2695   if (IV->isInvalidDecl())
2696     return ExprError();
2697 
2698   // Check if referencing a field with __attribute__((deprecated)).
2699   if (DiagnoseUseOfDecl(IV, Loc))
2700     return ExprError();
2701 
2702   // FIXME: This should use a new expr for a direct reference, don't
2703   // turn this into Self->ivar, just return a BareIVarExpr or something.
2704   IdentifierInfo &II = Context.Idents.get("self");
2705   UnqualifiedId SelfName;
2706   SelfName.setIdentifier(&II, SourceLocation());
2707   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2708   CXXScopeSpec SelfScopeSpec;
2709   SourceLocation TemplateKWLoc;
2710   ExprResult SelfExpr =
2711       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2712                         /*HasTrailingLParen=*/false,
2713                         /*IsAddressOfOperand=*/false);
2714   if (SelfExpr.isInvalid())
2715     return ExprError();
2716 
2717   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2718   if (SelfExpr.isInvalid())
2719     return ExprError();
2720 
2721   MarkAnyDeclReferenced(Loc, IV, true);
2722 
2723   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2724   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2725       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2726     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2727 
2728   ObjCIvarRefExpr *Result = new (Context)
2729       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2730                       IV->getLocation(), SelfExpr.get(), true, true);
2731 
2732   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2733     if (!isUnevaluatedContext() &&
2734         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2735       getCurFunction()->recordUseOfWeak(Result);
2736   }
2737   if (getLangOpts().ObjCAutoRefCount)
2738     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2739       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2740 
2741   return Result;
2742 }
2743 
2744 /// The parser has read a name in, and Sema has detected that we're currently
2745 /// inside an ObjC method. Perform some additional checks and determine if we
2746 /// should form a reference to an ivar. If so, build an expression referencing
2747 /// that ivar.
2748 ExprResult
2749 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2750                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2751   // FIXME: Integrate this lookup step into LookupParsedName.
2752   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2753   if (Ivar.isInvalid())
2754     return ExprError();
2755   if (Ivar.isUsable())
2756     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2757                             cast<ObjCIvarDecl>(Ivar.get()));
2758 
2759   if (Lookup.empty() && II && AllowBuiltinCreation)
2760     LookupBuiltin(Lookup);
2761 
2762   // Sentinel value saying that we didn't do anything special.
2763   return ExprResult(false);
2764 }
2765 
2766 /// Cast a base object to a member's actual type.
2767 ///
2768 /// Logically this happens in three phases:
2769 ///
2770 /// * First we cast from the base type to the naming class.
2771 ///   The naming class is the class into which we were looking
2772 ///   when we found the member;  it's the qualifier type if a
2773 ///   qualifier was provided, and otherwise it's the base type.
2774 ///
2775 /// * Next we cast from the naming class to the declaring class.
2776 ///   If the member we found was brought into a class's scope by
2777 ///   a using declaration, this is that class;  otherwise it's
2778 ///   the class declaring the member.
2779 ///
2780 /// * Finally we cast from the declaring class to the "true"
2781 ///   declaring class of the member.  This conversion does not
2782 ///   obey access control.
2783 ExprResult
2784 Sema::PerformObjectMemberConversion(Expr *From,
2785                                     NestedNameSpecifier *Qualifier,
2786                                     NamedDecl *FoundDecl,
2787                                     NamedDecl *Member) {
2788   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2789   if (!RD)
2790     return From;
2791 
2792   QualType DestRecordType;
2793   QualType DestType;
2794   QualType FromRecordType;
2795   QualType FromType = From->getType();
2796   bool PointerConversions = false;
2797   if (isa<FieldDecl>(Member)) {
2798     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2799     auto FromPtrType = FromType->getAs<PointerType>();
2800     DestRecordType = Context.getAddrSpaceQualType(
2801         DestRecordType, FromPtrType
2802                             ? FromType->getPointeeType().getAddressSpace()
2803                             : FromType.getAddressSpace());
2804 
2805     if (FromPtrType) {
2806       DestType = Context.getPointerType(DestRecordType);
2807       FromRecordType = FromPtrType->getPointeeType();
2808       PointerConversions = true;
2809     } else {
2810       DestType = DestRecordType;
2811       FromRecordType = FromType;
2812     }
2813   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2814     if (Method->isStatic())
2815       return From;
2816 
2817     DestType = Method->getThisType();
2818     DestRecordType = DestType->getPointeeType();
2819 
2820     if (FromType->getAs<PointerType>()) {
2821       FromRecordType = FromType->getPointeeType();
2822       PointerConversions = true;
2823     } else {
2824       FromRecordType = FromType;
2825       DestType = DestRecordType;
2826     }
2827 
2828     LangAS FromAS = FromRecordType.getAddressSpace();
2829     LangAS DestAS = DestRecordType.getAddressSpace();
2830     if (FromAS != DestAS) {
2831       QualType FromRecordTypeWithoutAS =
2832           Context.removeAddrSpaceQualType(FromRecordType);
2833       QualType FromTypeWithDestAS =
2834           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2835       if (PointerConversions)
2836         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2837       From = ImpCastExprToType(From, FromTypeWithDestAS,
2838                                CK_AddressSpaceConversion, From->getValueKind())
2839                  .get();
2840     }
2841   } else {
2842     // No conversion necessary.
2843     return From;
2844   }
2845 
2846   if (DestType->isDependentType() || FromType->isDependentType())
2847     return From;
2848 
2849   // If the unqualified types are the same, no conversion is necessary.
2850   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2851     return From;
2852 
2853   SourceRange FromRange = From->getSourceRange();
2854   SourceLocation FromLoc = FromRange.getBegin();
2855 
2856   ExprValueKind VK = From->getValueKind();
2857 
2858   // C++ [class.member.lookup]p8:
2859   //   [...] Ambiguities can often be resolved by qualifying a name with its
2860   //   class name.
2861   //
2862   // If the member was a qualified name and the qualified referred to a
2863   // specific base subobject type, we'll cast to that intermediate type
2864   // first and then to the object in which the member is declared. That allows
2865   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2866   //
2867   //   class Base { public: int x; };
2868   //   class Derived1 : public Base { };
2869   //   class Derived2 : public Base { };
2870   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2871   //
2872   //   void VeryDerived::f() {
2873   //     x = 17; // error: ambiguous base subobjects
2874   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2875   //   }
2876   if (Qualifier && Qualifier->getAsType()) {
2877     QualType QType = QualType(Qualifier->getAsType(), 0);
2878     assert(QType->isRecordType() && "lookup done with non-record type");
2879 
2880     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2881 
2882     // In C++98, the qualifier type doesn't actually have to be a base
2883     // type of the object type, in which case we just ignore it.
2884     // Otherwise build the appropriate casts.
2885     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2886       CXXCastPath BasePath;
2887       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2888                                        FromLoc, FromRange, &BasePath))
2889         return ExprError();
2890 
2891       if (PointerConversions)
2892         QType = Context.getPointerType(QType);
2893       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2894                                VK, &BasePath).get();
2895 
2896       FromType = QType;
2897       FromRecordType = QRecordType;
2898 
2899       // If the qualifier type was the same as the destination type,
2900       // we're done.
2901       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2902         return From;
2903     }
2904   }
2905 
2906   bool IgnoreAccess = false;
2907 
2908   // If we actually found the member through a using declaration, cast
2909   // down to the using declaration's type.
2910   //
2911   // Pointer equality is fine here because only one declaration of a
2912   // class ever has member declarations.
2913   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2914     assert(isa<UsingShadowDecl>(FoundDecl));
2915     QualType URecordType = Context.getTypeDeclType(
2916                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2917 
2918     // We only need to do this if the naming-class to declaring-class
2919     // conversion is non-trivial.
2920     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2921       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2922       CXXCastPath BasePath;
2923       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2924                                        FromLoc, FromRange, &BasePath))
2925         return ExprError();
2926 
2927       QualType UType = URecordType;
2928       if (PointerConversions)
2929         UType = Context.getPointerType(UType);
2930       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2931                                VK, &BasePath).get();
2932       FromType = UType;
2933       FromRecordType = URecordType;
2934     }
2935 
2936     // We don't do access control for the conversion from the
2937     // declaring class to the true declaring class.
2938     IgnoreAccess = true;
2939   }
2940 
2941   CXXCastPath BasePath;
2942   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2943                                    FromLoc, FromRange, &BasePath,
2944                                    IgnoreAccess))
2945     return ExprError();
2946 
2947   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2948                            VK, &BasePath);
2949 }
2950 
2951 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2952                                       const LookupResult &R,
2953                                       bool HasTrailingLParen) {
2954   // Only when used directly as the postfix-expression of a call.
2955   if (!HasTrailingLParen)
2956     return false;
2957 
2958   // Never if a scope specifier was provided.
2959   if (SS.isSet())
2960     return false;
2961 
2962   // Only in C++ or ObjC++.
2963   if (!getLangOpts().CPlusPlus)
2964     return false;
2965 
2966   // Turn off ADL when we find certain kinds of declarations during
2967   // normal lookup:
2968   for (NamedDecl *D : R) {
2969     // C++0x [basic.lookup.argdep]p3:
2970     //     -- a declaration of a class member
2971     // Since using decls preserve this property, we check this on the
2972     // original decl.
2973     if (D->isCXXClassMember())
2974       return false;
2975 
2976     // C++0x [basic.lookup.argdep]p3:
2977     //     -- a block-scope function declaration that is not a
2978     //        using-declaration
2979     // NOTE: we also trigger this for function templates (in fact, we
2980     // don't check the decl type at all, since all other decl types
2981     // turn off ADL anyway).
2982     if (isa<UsingShadowDecl>(D))
2983       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2984     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2985       return false;
2986 
2987     // C++0x [basic.lookup.argdep]p3:
2988     //     -- a declaration that is neither a function or a function
2989     //        template
2990     // And also for builtin functions.
2991     if (isa<FunctionDecl>(D)) {
2992       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2993 
2994       // But also builtin functions.
2995       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2996         return false;
2997     } else if (!isa<FunctionTemplateDecl>(D))
2998       return false;
2999   }
3000 
3001   return true;
3002 }
3003 
3004 
3005 /// Diagnoses obvious problems with the use of the given declaration
3006 /// as an expression.  This is only actually called for lookups that
3007 /// were not overloaded, and it doesn't promise that the declaration
3008 /// will in fact be used.
3009 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3010   if (D->isInvalidDecl())
3011     return true;
3012 
3013   if (isa<TypedefNameDecl>(D)) {
3014     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3015     return true;
3016   }
3017 
3018   if (isa<ObjCInterfaceDecl>(D)) {
3019     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3020     return true;
3021   }
3022 
3023   if (isa<NamespaceDecl>(D)) {
3024     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3025     return true;
3026   }
3027 
3028   return false;
3029 }
3030 
3031 // Certain multiversion types should be treated as overloaded even when there is
3032 // only one result.
3033 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3034   assert(R.isSingleResult() && "Expected only a single result");
3035   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3036   return FD &&
3037          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3038 }
3039 
3040 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3041                                           LookupResult &R, bool NeedsADL,
3042                                           bool AcceptInvalidDecl) {
3043   // If this is a single, fully-resolved result and we don't need ADL,
3044   // just build an ordinary singleton decl ref.
3045   if (!NeedsADL && R.isSingleResult() &&
3046       !R.getAsSingle<FunctionTemplateDecl>() &&
3047       !ShouldLookupResultBeMultiVersionOverload(R))
3048     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3049                                     R.getRepresentativeDecl(), nullptr,
3050                                     AcceptInvalidDecl);
3051 
3052   // We only need to check the declaration if there's exactly one
3053   // result, because in the overloaded case the results can only be
3054   // functions and function templates.
3055   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3056       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3057     return ExprError();
3058 
3059   // Otherwise, just build an unresolved lookup expression.  Suppress
3060   // any lookup-related diagnostics; we'll hash these out later, when
3061   // we've picked a target.
3062   R.suppressDiagnostics();
3063 
3064   UnresolvedLookupExpr *ULE
3065     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3066                                    SS.getWithLocInContext(Context),
3067                                    R.getLookupNameInfo(),
3068                                    NeedsADL, R.isOverloadedResult(),
3069                                    R.begin(), R.end());
3070 
3071   return ULE;
3072 }
3073 
3074 static void
3075 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3076                                    ValueDecl *var, DeclContext *DC);
3077 
3078 /// Complete semantic analysis for a reference to the given declaration.
3079 ExprResult Sema::BuildDeclarationNameExpr(
3080     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3081     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3082     bool AcceptInvalidDecl) {
3083   assert(D && "Cannot refer to a NULL declaration");
3084   assert(!isa<FunctionTemplateDecl>(D) &&
3085          "Cannot refer unambiguously to a function template");
3086 
3087   SourceLocation Loc = NameInfo.getLoc();
3088   if (CheckDeclInExpr(*this, Loc, D))
3089     return ExprError();
3090 
3091   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3092     // Specifically diagnose references to class templates that are missing
3093     // a template argument list.
3094     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3095     return ExprError();
3096   }
3097 
3098   // Make sure that we're referring to a value.
3099   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3100   if (!VD) {
3101     Diag(Loc, diag::err_ref_non_value)
3102       << D << SS.getRange();
3103     Diag(D->getLocation(), diag::note_declared_at);
3104     return ExprError();
3105   }
3106 
3107   // Check whether this declaration can be used. Note that we suppress
3108   // this check when we're going to perform argument-dependent lookup
3109   // on this function name, because this might not be the function
3110   // that overload resolution actually selects.
3111   if (DiagnoseUseOfDecl(VD, Loc))
3112     return ExprError();
3113 
3114   // Only create DeclRefExpr's for valid Decl's.
3115   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3116     return ExprError();
3117 
3118   // Handle members of anonymous structs and unions.  If we got here,
3119   // and the reference is to a class member indirect field, then this
3120   // must be the subject of a pointer-to-member expression.
3121   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3122     if (!indirectField->isCXXClassMember())
3123       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3124                                                       indirectField);
3125 
3126   {
3127     QualType type = VD->getType();
3128     if (type.isNull())
3129       return ExprError();
3130     ExprValueKind valueKind = VK_RValue;
3131 
3132     switch (D->getKind()) {
3133     // Ignore all the non-ValueDecl kinds.
3134 #define ABSTRACT_DECL(kind)
3135 #define VALUE(type, base)
3136 #define DECL(type, base) \
3137     case Decl::type:
3138 #include "clang/AST/DeclNodes.inc"
3139       llvm_unreachable("invalid value decl kind");
3140 
3141     // These shouldn't make it here.
3142     case Decl::ObjCAtDefsField:
3143       llvm_unreachable("forming non-member reference to ivar?");
3144 
3145     // Enum constants are always r-values and never references.
3146     // Unresolved using declarations are dependent.
3147     case Decl::EnumConstant:
3148     case Decl::UnresolvedUsingValue:
3149     case Decl::OMPDeclareReduction:
3150     case Decl::OMPDeclareMapper:
3151       valueKind = VK_RValue;
3152       break;
3153 
3154     // Fields and indirect fields that got here must be for
3155     // pointer-to-member expressions; we just call them l-values for
3156     // internal consistency, because this subexpression doesn't really
3157     // exist in the high-level semantics.
3158     case Decl::Field:
3159     case Decl::IndirectField:
3160     case Decl::ObjCIvar:
3161       assert(getLangOpts().CPlusPlus &&
3162              "building reference to field in C?");
3163 
3164       // These can't have reference type in well-formed programs, but
3165       // for internal consistency we do this anyway.
3166       type = type.getNonReferenceType();
3167       valueKind = VK_LValue;
3168       break;
3169 
3170     // Non-type template parameters are either l-values or r-values
3171     // depending on the type.
3172     case Decl::NonTypeTemplateParm: {
3173       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3174         type = reftype->getPointeeType();
3175         valueKind = VK_LValue; // even if the parameter is an r-value reference
3176         break;
3177       }
3178 
3179       // For non-references, we need to strip qualifiers just in case
3180       // the template parameter was declared as 'const int' or whatever.
3181       valueKind = VK_RValue;
3182       type = type.getUnqualifiedType();
3183       break;
3184     }
3185 
3186     case Decl::Var:
3187     case Decl::VarTemplateSpecialization:
3188     case Decl::VarTemplatePartialSpecialization:
3189     case Decl::Decomposition:
3190     case Decl::OMPCapturedExpr:
3191       // In C, "extern void blah;" is valid and is an r-value.
3192       if (!getLangOpts().CPlusPlus &&
3193           !type.hasQualifiers() &&
3194           type->isVoidType()) {
3195         valueKind = VK_RValue;
3196         break;
3197       }
3198       LLVM_FALLTHROUGH;
3199 
3200     case Decl::ImplicitParam:
3201     case Decl::ParmVar: {
3202       // These are always l-values.
3203       valueKind = VK_LValue;
3204       type = type.getNonReferenceType();
3205 
3206       // FIXME: Does the addition of const really only apply in
3207       // potentially-evaluated contexts? Since the variable isn't actually
3208       // captured in an unevaluated context, it seems that the answer is no.
3209       if (!isUnevaluatedContext()) {
3210         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3211         if (!CapturedType.isNull())
3212           type = CapturedType;
3213       }
3214 
3215       break;
3216     }
3217 
3218     case Decl::Binding: {
3219       // These are always lvalues.
3220       valueKind = VK_LValue;
3221       type = type.getNonReferenceType();
3222       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3223       // decides how that's supposed to work.
3224       auto *BD = cast<BindingDecl>(VD);
3225       if (BD->getDeclContext() != CurContext) {
3226         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3227         if (DD && DD->hasLocalStorage())
3228           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3229       }
3230       break;
3231     }
3232 
3233     case Decl::Function: {
3234       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3235         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3236           type = Context.BuiltinFnTy;
3237           valueKind = VK_RValue;
3238           break;
3239         }
3240       }
3241 
3242       const FunctionType *fty = type->castAs<FunctionType>();
3243 
3244       // If we're referring to a function with an __unknown_anytype
3245       // result type, make the entire expression __unknown_anytype.
3246       if (fty->getReturnType() == Context.UnknownAnyTy) {
3247         type = Context.UnknownAnyTy;
3248         valueKind = VK_RValue;
3249         break;
3250       }
3251 
3252       // Functions are l-values in C++.
3253       if (getLangOpts().CPlusPlus) {
3254         valueKind = VK_LValue;
3255         break;
3256       }
3257 
3258       // C99 DR 316 says that, if a function type comes from a
3259       // function definition (without a prototype), that type is only
3260       // used for checking compatibility. Therefore, when referencing
3261       // the function, we pretend that we don't have the full function
3262       // type.
3263       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3264           isa<FunctionProtoType>(fty))
3265         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3266                                               fty->getExtInfo());
3267 
3268       // Functions are r-values in C.
3269       valueKind = VK_RValue;
3270       break;
3271     }
3272 
3273     case Decl::CXXDeductionGuide:
3274       llvm_unreachable("building reference to deduction guide");
3275 
3276     case Decl::MSProperty:
3277       valueKind = VK_LValue;
3278       break;
3279 
3280     case Decl::CXXMethod:
3281       // If we're referring to a method with an __unknown_anytype
3282       // result type, make the entire expression __unknown_anytype.
3283       // This should only be possible with a type written directly.
3284       if (const FunctionProtoType *proto
3285             = dyn_cast<FunctionProtoType>(VD->getType()))
3286         if (proto->getReturnType() == Context.UnknownAnyTy) {
3287           type = Context.UnknownAnyTy;
3288           valueKind = VK_RValue;
3289           break;
3290         }
3291 
3292       // C++ methods are l-values if static, r-values if non-static.
3293       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3294         valueKind = VK_LValue;
3295         break;
3296       }
3297       LLVM_FALLTHROUGH;
3298 
3299     case Decl::CXXConversion:
3300     case Decl::CXXDestructor:
3301     case Decl::CXXConstructor:
3302       valueKind = VK_RValue;
3303       break;
3304     }
3305 
3306     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3307                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3308                             TemplateArgs);
3309   }
3310 }
3311 
3312 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3313                                     SmallString<32> &Target) {
3314   Target.resize(CharByteWidth * (Source.size() + 1));
3315   char *ResultPtr = &Target[0];
3316   const llvm::UTF8 *ErrorPtr;
3317   bool success =
3318       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3319   (void)success;
3320   assert(success);
3321   Target.resize(ResultPtr - &Target[0]);
3322 }
3323 
3324 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3325                                      PredefinedExpr::IdentKind IK) {
3326   // Pick the current block, lambda, captured statement or function.
3327   Decl *currentDecl = nullptr;
3328   if (const BlockScopeInfo *BSI = getCurBlock())
3329     currentDecl = BSI->TheDecl;
3330   else if (const LambdaScopeInfo *LSI = getCurLambda())
3331     currentDecl = LSI->CallOperator;
3332   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3333     currentDecl = CSI->TheCapturedDecl;
3334   else
3335     currentDecl = getCurFunctionOrMethodDecl();
3336 
3337   if (!currentDecl) {
3338     Diag(Loc, diag::ext_predef_outside_function);
3339     currentDecl = Context.getTranslationUnitDecl();
3340   }
3341 
3342   QualType ResTy;
3343   StringLiteral *SL = nullptr;
3344   if (cast<DeclContext>(currentDecl)->isDependentContext())
3345     ResTy = Context.DependentTy;
3346   else {
3347     // Pre-defined identifiers are of type char[x], where x is the length of
3348     // the string.
3349     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3350     unsigned Length = Str.length();
3351 
3352     llvm::APInt LengthI(32, Length + 1);
3353     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3354       ResTy =
3355           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3356       SmallString<32> RawChars;
3357       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3358                               Str, RawChars);
3359       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3360                                            ArrayType::Normal,
3361                                            /*IndexTypeQuals*/ 0);
3362       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3363                                  /*Pascal*/ false, ResTy, Loc);
3364     } else {
3365       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3366       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3367                                            ArrayType::Normal,
3368                                            /*IndexTypeQuals*/ 0);
3369       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3370                                  /*Pascal*/ false, ResTy, Loc);
3371     }
3372   }
3373 
3374   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3375 }
3376 
3377 static std::pair<QualType, StringLiteral *>
3378 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3379                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3380   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3381 
3382   if (OpType->isDependentType()) {
3383       Result.first = Context.DependentTy;
3384       return Result;
3385   }
3386 
3387   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3388   llvm::APInt Length(32, Str.length() + 1);
3389   Result.first =
3390       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3391   Result.first = Context.getConstantArrayType(
3392       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3393   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3394                                         /*Pascal*/ false, Result.first, OpLoc);
3395   return Result;
3396 }
3397 
3398 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3399                                        TypeSourceInfo *Operand) {
3400   QualType ResultTy;
3401   StringLiteral *SL;
3402   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3403       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3404 
3405   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3406                                 PredefinedExpr::UniqueStableNameType, SL,
3407                                 Operand);
3408 }
3409 
3410 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3411                                        Expr *E) {
3412   QualType ResultTy;
3413   StringLiteral *SL;
3414   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3415       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3416 
3417   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3418                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3419 }
3420 
3421 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3422                                            SourceLocation L, SourceLocation R,
3423                                            ParsedType Ty) {
3424   TypeSourceInfo *TInfo = nullptr;
3425   QualType T = GetTypeFromParser(Ty, &TInfo);
3426 
3427   if (T.isNull())
3428     return ExprError();
3429   if (!TInfo)
3430     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3431 
3432   return BuildUniqueStableName(OpLoc, TInfo);
3433 }
3434 
3435 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3436                                            SourceLocation L, SourceLocation R,
3437                                            Expr *E) {
3438   return BuildUniqueStableName(OpLoc, E);
3439 }
3440 
3441 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3442   PredefinedExpr::IdentKind IK;
3443 
3444   switch (Kind) {
3445   default: llvm_unreachable("Unknown simple primary expr!");
3446   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3447   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3448   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3449   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3450   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3451   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3452   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3453   }
3454 
3455   return BuildPredefinedExpr(Loc, IK);
3456 }
3457 
3458 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3459   SmallString<16> CharBuffer;
3460   bool Invalid = false;
3461   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3462   if (Invalid)
3463     return ExprError();
3464 
3465   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3466                             PP, Tok.getKind());
3467   if (Literal.hadError())
3468     return ExprError();
3469 
3470   QualType Ty;
3471   if (Literal.isWide())
3472     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3473   else if (Literal.isUTF8() && getLangOpts().Char8)
3474     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3475   else if (Literal.isUTF16())
3476     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3477   else if (Literal.isUTF32())
3478     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3479   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3480     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3481   else
3482     Ty = Context.CharTy;  // 'x' -> char in C++
3483 
3484   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3485   if (Literal.isWide())
3486     Kind = CharacterLiteral::Wide;
3487   else if (Literal.isUTF16())
3488     Kind = CharacterLiteral::UTF16;
3489   else if (Literal.isUTF32())
3490     Kind = CharacterLiteral::UTF32;
3491   else if (Literal.isUTF8())
3492     Kind = CharacterLiteral::UTF8;
3493 
3494   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3495                                              Tok.getLocation());
3496 
3497   if (Literal.getUDSuffix().empty())
3498     return Lit;
3499 
3500   // We're building a user-defined literal.
3501   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3502   SourceLocation UDSuffixLoc =
3503     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3504 
3505   // Make sure we're allowed user-defined literals here.
3506   if (!UDLScope)
3507     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3508 
3509   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3510   //   operator "" X (ch)
3511   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3512                                         Lit, Tok.getLocation());
3513 }
3514 
3515 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3516   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3517   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3518                                 Context.IntTy, Loc);
3519 }
3520 
3521 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3522                                   QualType Ty, SourceLocation Loc) {
3523   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3524 
3525   using llvm::APFloat;
3526   APFloat Val(Format);
3527 
3528   APFloat::opStatus result = Literal.GetFloatValue(Val);
3529 
3530   // Overflow is always an error, but underflow is only an error if
3531   // we underflowed to zero (APFloat reports denormals as underflow).
3532   if ((result & APFloat::opOverflow) ||
3533       ((result & APFloat::opUnderflow) && Val.isZero())) {
3534     unsigned diagnostic;
3535     SmallString<20> buffer;
3536     if (result & APFloat::opOverflow) {
3537       diagnostic = diag::warn_float_overflow;
3538       APFloat::getLargest(Format).toString(buffer);
3539     } else {
3540       diagnostic = diag::warn_float_underflow;
3541       APFloat::getSmallest(Format).toString(buffer);
3542     }
3543 
3544     S.Diag(Loc, diagnostic)
3545       << Ty
3546       << StringRef(buffer.data(), buffer.size());
3547   }
3548 
3549   bool isExact = (result == APFloat::opOK);
3550   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3551 }
3552 
3553 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3554   assert(E && "Invalid expression");
3555 
3556   if (E->isValueDependent())
3557     return false;
3558 
3559   QualType QT = E->getType();
3560   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3561     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3562     return true;
3563   }
3564 
3565   llvm::APSInt ValueAPS;
3566   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3567 
3568   if (R.isInvalid())
3569     return true;
3570 
3571   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3572   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3573     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3574         << ValueAPS.toString(10) << ValueIsPositive;
3575     return true;
3576   }
3577 
3578   return false;
3579 }
3580 
3581 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3582   // Fast path for a single digit (which is quite common).  A single digit
3583   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3584   if (Tok.getLength() == 1) {
3585     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3586     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3587   }
3588 
3589   SmallString<128> SpellingBuffer;
3590   // NumericLiteralParser wants to overread by one character.  Add padding to
3591   // the buffer in case the token is copied to the buffer.  If getSpelling()
3592   // returns a StringRef to the memory buffer, it should have a null char at
3593   // the EOF, so it is also safe.
3594   SpellingBuffer.resize(Tok.getLength() + 1);
3595 
3596   // Get the spelling of the token, which eliminates trigraphs, etc.
3597   bool Invalid = false;
3598   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3599   if (Invalid)
3600     return ExprError();
3601 
3602   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3603   if (Literal.hadError)
3604     return ExprError();
3605 
3606   if (Literal.hasUDSuffix()) {
3607     // We're building a user-defined literal.
3608     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3609     SourceLocation UDSuffixLoc =
3610       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3611 
3612     // Make sure we're allowed user-defined literals here.
3613     if (!UDLScope)
3614       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3615 
3616     QualType CookedTy;
3617     if (Literal.isFloatingLiteral()) {
3618       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3619       // long double, the literal is treated as a call of the form
3620       //   operator "" X (f L)
3621       CookedTy = Context.LongDoubleTy;
3622     } else {
3623       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3624       // unsigned long long, the literal is treated as a call of the form
3625       //   operator "" X (n ULL)
3626       CookedTy = Context.UnsignedLongLongTy;
3627     }
3628 
3629     DeclarationName OpName =
3630       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3631     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3632     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3633 
3634     SourceLocation TokLoc = Tok.getLocation();
3635 
3636     // Perform literal operator lookup to determine if we're building a raw
3637     // literal or a cooked one.
3638     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3639     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3640                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3641                                   /*AllowStringTemplate*/ false,
3642                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3643     case LOLR_ErrorNoDiagnostic:
3644       // Lookup failure for imaginary constants isn't fatal, there's still the
3645       // GNU extension producing _Complex types.
3646       break;
3647     case LOLR_Error:
3648       return ExprError();
3649     case LOLR_Cooked: {
3650       Expr *Lit;
3651       if (Literal.isFloatingLiteral()) {
3652         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3653       } else {
3654         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3655         if (Literal.GetIntegerValue(ResultVal))
3656           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3657               << /* Unsigned */ 1;
3658         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3659                                      Tok.getLocation());
3660       }
3661       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3662     }
3663 
3664     case LOLR_Raw: {
3665       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3666       // literal is treated as a call of the form
3667       //   operator "" X ("n")
3668       unsigned Length = Literal.getUDSuffixOffset();
3669       QualType StrTy = Context.getConstantArrayType(
3670           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3671           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3672       Expr *Lit = StringLiteral::Create(
3673           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3674           /*Pascal*/false, StrTy, &TokLoc, 1);
3675       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3676     }
3677 
3678     case LOLR_Template: {
3679       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3680       // template), L is treated as a call fo the form
3681       //   operator "" X <'c1', 'c2', ... 'ck'>()
3682       // where n is the source character sequence c1 c2 ... ck.
3683       TemplateArgumentListInfo ExplicitArgs;
3684       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3685       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3686       llvm::APSInt Value(CharBits, CharIsUnsigned);
3687       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3688         Value = TokSpelling[I];
3689         TemplateArgument Arg(Context, Value, Context.CharTy);
3690         TemplateArgumentLocInfo ArgInfo;
3691         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3692       }
3693       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3694                                       &ExplicitArgs);
3695     }
3696     case LOLR_StringTemplate:
3697       llvm_unreachable("unexpected literal operator lookup result");
3698     }
3699   }
3700 
3701   Expr *Res;
3702 
3703   if (Literal.isFixedPointLiteral()) {
3704     QualType Ty;
3705 
3706     if (Literal.isAccum) {
3707       if (Literal.isHalf) {
3708         Ty = Context.ShortAccumTy;
3709       } else if (Literal.isLong) {
3710         Ty = Context.LongAccumTy;
3711       } else {
3712         Ty = Context.AccumTy;
3713       }
3714     } else if (Literal.isFract) {
3715       if (Literal.isHalf) {
3716         Ty = Context.ShortFractTy;
3717       } else if (Literal.isLong) {
3718         Ty = Context.LongFractTy;
3719       } else {
3720         Ty = Context.FractTy;
3721       }
3722     }
3723 
3724     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3725 
3726     bool isSigned = !Literal.isUnsigned;
3727     unsigned scale = Context.getFixedPointScale(Ty);
3728     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3729 
3730     llvm::APInt Val(bit_width, 0, isSigned);
3731     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3732     bool ValIsZero = Val.isNullValue() && !Overflowed;
3733 
3734     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3735     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3736       // Clause 6.4.4 - The value of a constant shall be in the range of
3737       // representable values for its type, with exception for constants of a
3738       // fract type with a value of exactly 1; such a constant shall denote
3739       // the maximal value for the type.
3740       --Val;
3741     else if (Val.ugt(MaxVal) || Overflowed)
3742       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3743 
3744     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3745                                               Tok.getLocation(), scale);
3746   } else if (Literal.isFloatingLiteral()) {
3747     QualType Ty;
3748     if (Literal.isHalf){
3749       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3750         Ty = Context.HalfTy;
3751       else {
3752         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3753         return ExprError();
3754       }
3755     } else if (Literal.isFloat)
3756       Ty = Context.FloatTy;
3757     else if (Literal.isLong)
3758       Ty = Context.LongDoubleTy;
3759     else if (Literal.isFloat16)
3760       Ty = Context.Float16Ty;
3761     else if (Literal.isFloat128)
3762       Ty = Context.Float128Ty;
3763     else
3764       Ty = Context.DoubleTy;
3765 
3766     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3767 
3768     if (Ty == Context.DoubleTy) {
3769       if (getLangOpts().SinglePrecisionConstants) {
3770         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3771         if (BTy->getKind() != BuiltinType::Float) {
3772           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3773         }
3774       } else if (getLangOpts().OpenCL &&
3775                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3776         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3777         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3778         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3779       }
3780     }
3781   } else if (!Literal.isIntegerLiteral()) {
3782     return ExprError();
3783   } else {
3784     QualType Ty;
3785 
3786     // 'long long' is a C99 or C++11 feature.
3787     if (!getLangOpts().C99 && Literal.isLongLong) {
3788       if (getLangOpts().CPlusPlus)
3789         Diag(Tok.getLocation(),
3790              getLangOpts().CPlusPlus11 ?
3791              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3792       else
3793         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3794     }
3795 
3796     // Get the value in the widest-possible width.
3797     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3798     llvm::APInt ResultVal(MaxWidth, 0);
3799 
3800     if (Literal.GetIntegerValue(ResultVal)) {
3801       // If this value didn't fit into uintmax_t, error and force to ull.
3802       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3803           << /* Unsigned */ 1;
3804       Ty = Context.UnsignedLongLongTy;
3805       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3806              "long long is not intmax_t?");
3807     } else {
3808       // If this value fits into a ULL, try to figure out what else it fits into
3809       // according to the rules of C99 6.4.4.1p5.
3810 
3811       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3812       // be an unsigned int.
3813       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3814 
3815       // Check from smallest to largest, picking the smallest type we can.
3816       unsigned Width = 0;
3817 
3818       // Microsoft specific integer suffixes are explicitly sized.
3819       if (Literal.MicrosoftInteger) {
3820         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3821           Width = 8;
3822           Ty = Context.CharTy;
3823         } else {
3824           Width = Literal.MicrosoftInteger;
3825           Ty = Context.getIntTypeForBitwidth(Width,
3826                                              /*Signed=*/!Literal.isUnsigned);
3827         }
3828       }
3829 
3830       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3831         // Are int/unsigned possibilities?
3832         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3833 
3834         // Does it fit in a unsigned int?
3835         if (ResultVal.isIntN(IntSize)) {
3836           // Does it fit in a signed int?
3837           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3838             Ty = Context.IntTy;
3839           else if (AllowUnsigned)
3840             Ty = Context.UnsignedIntTy;
3841           Width = IntSize;
3842         }
3843       }
3844 
3845       // Are long/unsigned long possibilities?
3846       if (Ty.isNull() && !Literal.isLongLong) {
3847         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3848 
3849         // Does it fit in a unsigned long?
3850         if (ResultVal.isIntN(LongSize)) {
3851           // Does it fit in a signed long?
3852           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3853             Ty = Context.LongTy;
3854           else if (AllowUnsigned)
3855             Ty = Context.UnsignedLongTy;
3856           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3857           // is compatible.
3858           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3859             const unsigned LongLongSize =
3860                 Context.getTargetInfo().getLongLongWidth();
3861             Diag(Tok.getLocation(),
3862                  getLangOpts().CPlusPlus
3863                      ? Literal.isLong
3864                            ? diag::warn_old_implicitly_unsigned_long_cxx
3865                            : /*C++98 UB*/ diag::
3866                                  ext_old_implicitly_unsigned_long_cxx
3867                      : diag::warn_old_implicitly_unsigned_long)
3868                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3869                                             : /*will be ill-formed*/ 1);
3870             Ty = Context.UnsignedLongTy;
3871           }
3872           Width = LongSize;
3873         }
3874       }
3875 
3876       // Check long long if needed.
3877       if (Ty.isNull()) {
3878         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3879 
3880         // Does it fit in a unsigned long long?
3881         if (ResultVal.isIntN(LongLongSize)) {
3882           // Does it fit in a signed long long?
3883           // To be compatible with MSVC, hex integer literals ending with the
3884           // LL or i64 suffix are always signed in Microsoft mode.
3885           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3886               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3887             Ty = Context.LongLongTy;
3888           else if (AllowUnsigned)
3889             Ty = Context.UnsignedLongLongTy;
3890           Width = LongLongSize;
3891         }
3892       }
3893 
3894       // If we still couldn't decide a type, we probably have something that
3895       // does not fit in a signed long long, but has no U suffix.
3896       if (Ty.isNull()) {
3897         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3898         Ty = Context.UnsignedLongLongTy;
3899         Width = Context.getTargetInfo().getLongLongWidth();
3900       }
3901 
3902       if (ResultVal.getBitWidth() != Width)
3903         ResultVal = ResultVal.trunc(Width);
3904     }
3905     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3906   }
3907 
3908   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3909   if (Literal.isImaginary) {
3910     Res = new (Context) ImaginaryLiteral(Res,
3911                                         Context.getComplexType(Res->getType()));
3912 
3913     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3914   }
3915   return Res;
3916 }
3917 
3918 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3919   assert(E && "ActOnParenExpr() missing expr");
3920   return new (Context) ParenExpr(L, R, E);
3921 }
3922 
3923 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3924                                          SourceLocation Loc,
3925                                          SourceRange ArgRange) {
3926   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3927   // scalar or vector data type argument..."
3928   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3929   // type (C99 6.2.5p18) or void.
3930   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3931     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3932       << T << ArgRange;
3933     return true;
3934   }
3935 
3936   assert((T->isVoidType() || !T->isIncompleteType()) &&
3937          "Scalar types should always be complete");
3938   return false;
3939 }
3940 
3941 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3942                                            SourceLocation Loc,
3943                                            SourceRange ArgRange,
3944                                            UnaryExprOrTypeTrait TraitKind) {
3945   // Invalid types must be hard errors for SFINAE in C++.
3946   if (S.LangOpts.CPlusPlus)
3947     return true;
3948 
3949   // C99 6.5.3.4p1:
3950   if (T->isFunctionType() &&
3951       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3952        TraitKind == UETT_PreferredAlignOf)) {
3953     // sizeof(function)/alignof(function) is allowed as an extension.
3954     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3955       << TraitKind << ArgRange;
3956     return false;
3957   }
3958 
3959   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3960   // this is an error (OpenCL v1.1 s6.3.k)
3961   if (T->isVoidType()) {
3962     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3963                                         : diag::ext_sizeof_alignof_void_type;
3964     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3965     return false;
3966   }
3967 
3968   return true;
3969 }
3970 
3971 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3972                                              SourceLocation Loc,
3973                                              SourceRange ArgRange,
3974                                              UnaryExprOrTypeTrait TraitKind) {
3975   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3976   // runtime doesn't allow it.
3977   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3978     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3979       << T << (TraitKind == UETT_SizeOf)
3980       << ArgRange;
3981     return true;
3982   }
3983 
3984   return false;
3985 }
3986 
3987 /// Check whether E is a pointer from a decayed array type (the decayed
3988 /// pointer type is equal to T) and emit a warning if it is.
3989 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3990                                      Expr *E) {
3991   // Don't warn if the operation changed the type.
3992   if (T != E->getType())
3993     return;
3994 
3995   // Now look for array decays.
3996   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3997   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3998     return;
3999 
4000   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4001                                              << ICE->getType()
4002                                              << ICE->getSubExpr()->getType();
4003 }
4004 
4005 /// Check the constraints on expression operands to unary type expression
4006 /// and type traits.
4007 ///
4008 /// Completes any types necessary and validates the constraints on the operand
4009 /// expression. The logic mostly mirrors the type-based overload, but may modify
4010 /// the expression as it completes the type for that expression through template
4011 /// instantiation, etc.
4012 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4013                                             UnaryExprOrTypeTrait ExprKind) {
4014   QualType ExprTy = E->getType();
4015   assert(!ExprTy->isReferenceType());
4016 
4017   bool IsUnevaluatedOperand =
4018       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4019        ExprKind == UETT_PreferredAlignOf);
4020   if (IsUnevaluatedOperand) {
4021     ExprResult Result = CheckUnevaluatedOperand(E);
4022     if (Result.isInvalid())
4023       return true;
4024     E = Result.get();
4025   }
4026 
4027   if (ExprKind == UETT_VecStep)
4028     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4029                                         E->getSourceRange());
4030 
4031   // Whitelist some types as extensions
4032   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4033                                       E->getSourceRange(), ExprKind))
4034     return false;
4035 
4036   // 'alignof' applied to an expression only requires the base element type of
4037   // the expression to be complete. 'sizeof' requires the expression's type to
4038   // be complete (and will attempt to complete it if it's an array of unknown
4039   // bound).
4040   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4041     if (RequireCompleteSizedType(
4042             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4043             diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4044             E->getSourceRange()))
4045       return true;
4046   } else {
4047     if (RequireCompleteSizedExprType(
4048             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4049             E->getSourceRange()))
4050       return true;
4051   }
4052 
4053   // Completing the expression's type may have changed it.
4054   ExprTy = E->getType();
4055   assert(!ExprTy->isReferenceType());
4056 
4057   if (ExprTy->isFunctionType()) {
4058     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4059       << ExprKind << E->getSourceRange();
4060     return true;
4061   }
4062 
4063   // The operand for sizeof and alignof is in an unevaluated expression context,
4064   // so side effects could result in unintended consequences.
4065   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4066       E->HasSideEffects(Context, false))
4067     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4068 
4069   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4070                                        E->getSourceRange(), ExprKind))
4071     return true;
4072 
4073   if (ExprKind == UETT_SizeOf) {
4074     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4075       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4076         QualType OType = PVD->getOriginalType();
4077         QualType Type = PVD->getType();
4078         if (Type->isPointerType() && OType->isArrayType()) {
4079           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4080             << Type << OType;
4081           Diag(PVD->getLocation(), diag::note_declared_at);
4082         }
4083       }
4084     }
4085 
4086     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4087     // decays into a pointer and returns an unintended result. This is most
4088     // likely a typo for "sizeof(array) op x".
4089     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4090       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4091                                BO->getLHS());
4092       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4093                                BO->getRHS());
4094     }
4095   }
4096 
4097   return false;
4098 }
4099 
4100 /// Check the constraints on operands to unary expression and type
4101 /// traits.
4102 ///
4103 /// This will complete any types necessary, and validate the various constraints
4104 /// on those operands.
4105 ///
4106 /// The UsualUnaryConversions() function is *not* called by this routine.
4107 /// C99 6.3.2.1p[2-4] all state:
4108 ///   Except when it is the operand of the sizeof operator ...
4109 ///
4110 /// C++ [expr.sizeof]p4
4111 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4112 ///   standard conversions are not applied to the operand of sizeof.
4113 ///
4114 /// This policy is followed for all of the unary trait expressions.
4115 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4116                                             SourceLocation OpLoc,
4117                                             SourceRange ExprRange,
4118                                             UnaryExprOrTypeTrait ExprKind) {
4119   if (ExprType->isDependentType())
4120     return false;
4121 
4122   // C++ [expr.sizeof]p2:
4123   //     When applied to a reference or a reference type, the result
4124   //     is the size of the referenced type.
4125   // C++11 [expr.alignof]p3:
4126   //     When alignof is applied to a reference type, the result
4127   //     shall be the alignment of the referenced type.
4128   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4129     ExprType = Ref->getPointeeType();
4130 
4131   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4132   //   When alignof or _Alignof is applied to an array type, the result
4133   //   is the alignment of the element type.
4134   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4135       ExprKind == UETT_OpenMPRequiredSimdAlign)
4136     ExprType = Context.getBaseElementType(ExprType);
4137 
4138   if (ExprKind == UETT_VecStep)
4139     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4140 
4141   // Whitelist some types as extensions
4142   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4143                                       ExprKind))
4144     return false;
4145 
4146   if (RequireCompleteSizedType(
4147           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4148           ExprKind, ExprRange))
4149     return true;
4150 
4151   if (ExprType->isFunctionType()) {
4152     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4153       << ExprKind << ExprRange;
4154     return true;
4155   }
4156 
4157   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4158                                        ExprKind))
4159     return true;
4160 
4161   return false;
4162 }
4163 
4164 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4165   // Cannot know anything else if the expression is dependent.
4166   if (E->isTypeDependent())
4167     return false;
4168 
4169   if (E->getObjectKind() == OK_BitField) {
4170     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4171        << 1 << E->getSourceRange();
4172     return true;
4173   }
4174 
4175   ValueDecl *D = nullptr;
4176   Expr *Inner = E->IgnoreParens();
4177   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4178     D = DRE->getDecl();
4179   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4180     D = ME->getMemberDecl();
4181   }
4182 
4183   // If it's a field, require the containing struct to have a
4184   // complete definition so that we can compute the layout.
4185   //
4186   // This can happen in C++11 onwards, either by naming the member
4187   // in a way that is not transformed into a member access expression
4188   // (in an unevaluated operand, for instance), or by naming the member
4189   // in a trailing-return-type.
4190   //
4191   // For the record, since __alignof__ on expressions is a GCC
4192   // extension, GCC seems to permit this but always gives the
4193   // nonsensical answer 0.
4194   //
4195   // We don't really need the layout here --- we could instead just
4196   // directly check for all the appropriate alignment-lowing
4197   // attributes --- but that would require duplicating a lot of
4198   // logic that just isn't worth duplicating for such a marginal
4199   // use-case.
4200   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4201     // Fast path this check, since we at least know the record has a
4202     // definition if we can find a member of it.
4203     if (!FD->getParent()->isCompleteDefinition()) {
4204       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4205         << E->getSourceRange();
4206       return true;
4207     }
4208 
4209     // Otherwise, if it's a field, and the field doesn't have
4210     // reference type, then it must have a complete type (or be a
4211     // flexible array member, which we explicitly want to
4212     // white-list anyway), which makes the following checks trivial.
4213     if (!FD->getType()->isReferenceType())
4214       return false;
4215   }
4216 
4217   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4218 }
4219 
4220 bool Sema::CheckVecStepExpr(Expr *E) {
4221   E = E->IgnoreParens();
4222 
4223   // Cannot know anything else if the expression is dependent.
4224   if (E->isTypeDependent())
4225     return false;
4226 
4227   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4228 }
4229 
4230 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4231                                         CapturingScopeInfo *CSI) {
4232   assert(T->isVariablyModifiedType());
4233   assert(CSI != nullptr);
4234 
4235   // We're going to walk down into the type and look for VLA expressions.
4236   do {
4237     const Type *Ty = T.getTypePtr();
4238     switch (Ty->getTypeClass()) {
4239 #define TYPE(Class, Base)
4240 #define ABSTRACT_TYPE(Class, Base)
4241 #define NON_CANONICAL_TYPE(Class, Base)
4242 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4243 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4244 #include "clang/AST/TypeNodes.inc"
4245       T = QualType();
4246       break;
4247     // These types are never variably-modified.
4248     case Type::Builtin:
4249     case Type::Complex:
4250     case Type::Vector:
4251     case Type::ExtVector:
4252     case Type::Record:
4253     case Type::Enum:
4254     case Type::Elaborated:
4255     case Type::TemplateSpecialization:
4256     case Type::ObjCObject:
4257     case Type::ObjCInterface:
4258     case Type::ObjCObjectPointer:
4259     case Type::ObjCTypeParam:
4260     case Type::Pipe:
4261       llvm_unreachable("type class is never variably-modified!");
4262     case Type::Adjusted:
4263       T = cast<AdjustedType>(Ty)->getOriginalType();
4264       break;
4265     case Type::Decayed:
4266       T = cast<DecayedType>(Ty)->getPointeeType();
4267       break;
4268     case Type::Pointer:
4269       T = cast<PointerType>(Ty)->getPointeeType();
4270       break;
4271     case Type::BlockPointer:
4272       T = cast<BlockPointerType>(Ty)->getPointeeType();
4273       break;
4274     case Type::LValueReference:
4275     case Type::RValueReference:
4276       T = cast<ReferenceType>(Ty)->getPointeeType();
4277       break;
4278     case Type::MemberPointer:
4279       T = cast<MemberPointerType>(Ty)->getPointeeType();
4280       break;
4281     case Type::ConstantArray:
4282     case Type::IncompleteArray:
4283       // Losing element qualification here is fine.
4284       T = cast<ArrayType>(Ty)->getElementType();
4285       break;
4286     case Type::VariableArray: {
4287       // Losing element qualification here is fine.
4288       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4289 
4290       // Unknown size indication requires no size computation.
4291       // Otherwise, evaluate and record it.
4292       auto Size = VAT->getSizeExpr();
4293       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4294           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4295         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4296 
4297       T = VAT->getElementType();
4298       break;
4299     }
4300     case Type::FunctionProto:
4301     case Type::FunctionNoProto:
4302       T = cast<FunctionType>(Ty)->getReturnType();
4303       break;
4304     case Type::Paren:
4305     case Type::TypeOf:
4306     case Type::UnaryTransform:
4307     case Type::Attributed:
4308     case Type::SubstTemplateTypeParm:
4309     case Type::PackExpansion:
4310     case Type::MacroQualified:
4311       // Keep walking after single level desugaring.
4312       T = T.getSingleStepDesugaredType(Context);
4313       break;
4314     case Type::Typedef:
4315       T = cast<TypedefType>(Ty)->desugar();
4316       break;
4317     case Type::Decltype:
4318       T = cast<DecltypeType>(Ty)->desugar();
4319       break;
4320     case Type::Auto:
4321     case Type::DeducedTemplateSpecialization:
4322       T = cast<DeducedType>(Ty)->getDeducedType();
4323       break;
4324     case Type::TypeOfExpr:
4325       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4326       break;
4327     case Type::Atomic:
4328       T = cast<AtomicType>(Ty)->getValueType();
4329       break;
4330     }
4331   } while (!T.isNull() && T->isVariablyModifiedType());
4332 }
4333 
4334 /// Build a sizeof or alignof expression given a type operand.
4335 ExprResult
4336 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4337                                      SourceLocation OpLoc,
4338                                      UnaryExprOrTypeTrait ExprKind,
4339                                      SourceRange R) {
4340   if (!TInfo)
4341     return ExprError();
4342 
4343   QualType T = TInfo->getType();
4344 
4345   if (!T->isDependentType() &&
4346       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4347     return ExprError();
4348 
4349   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4350     if (auto *TT = T->getAs<TypedefType>()) {
4351       for (auto I = FunctionScopes.rbegin(),
4352                 E = std::prev(FunctionScopes.rend());
4353            I != E; ++I) {
4354         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4355         if (CSI == nullptr)
4356           break;
4357         DeclContext *DC = nullptr;
4358         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4359           DC = LSI->CallOperator;
4360         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4361           DC = CRSI->TheCapturedDecl;
4362         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4363           DC = BSI->TheDecl;
4364         if (DC) {
4365           if (DC->containsDecl(TT->getDecl()))
4366             break;
4367           captureVariablyModifiedType(Context, T, CSI);
4368         }
4369       }
4370     }
4371   }
4372 
4373   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4374   return new (Context) UnaryExprOrTypeTraitExpr(
4375       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4376 }
4377 
4378 /// Build a sizeof or alignof expression given an expression
4379 /// operand.
4380 ExprResult
4381 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4382                                      UnaryExprOrTypeTrait ExprKind) {
4383   ExprResult PE = CheckPlaceholderExpr(E);
4384   if (PE.isInvalid())
4385     return ExprError();
4386 
4387   E = PE.get();
4388 
4389   // Verify that the operand is valid.
4390   bool isInvalid = false;
4391   if (E->isTypeDependent()) {
4392     // Delay type-checking for type-dependent expressions.
4393   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4394     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4395   } else if (ExprKind == UETT_VecStep) {
4396     isInvalid = CheckVecStepExpr(E);
4397   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4398       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4399       isInvalid = true;
4400   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4401     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4402     isInvalid = true;
4403   } else {
4404     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4405   }
4406 
4407   if (isInvalid)
4408     return ExprError();
4409 
4410   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4411     PE = TransformToPotentiallyEvaluated(E);
4412     if (PE.isInvalid()) return ExprError();
4413     E = PE.get();
4414   }
4415 
4416   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4417   return new (Context) UnaryExprOrTypeTraitExpr(
4418       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4419 }
4420 
4421 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4422 /// expr and the same for @c alignof and @c __alignof
4423 /// Note that the ArgRange is invalid if isType is false.
4424 ExprResult
4425 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4426                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4427                                     void *TyOrEx, SourceRange ArgRange) {
4428   // If error parsing type, ignore.
4429   if (!TyOrEx) return ExprError();
4430 
4431   if (IsType) {
4432     TypeSourceInfo *TInfo;
4433     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4434     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4435   }
4436 
4437   Expr *ArgEx = (Expr *)TyOrEx;
4438   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4439   return Result;
4440 }
4441 
4442 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4443                                      bool IsReal) {
4444   if (V.get()->isTypeDependent())
4445     return S.Context.DependentTy;
4446 
4447   // _Real and _Imag are only l-values for normal l-values.
4448   if (V.get()->getObjectKind() != OK_Ordinary) {
4449     V = S.DefaultLvalueConversion(V.get());
4450     if (V.isInvalid())
4451       return QualType();
4452   }
4453 
4454   // These operators return the element type of a complex type.
4455   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4456     return CT->getElementType();
4457 
4458   // Otherwise they pass through real integer and floating point types here.
4459   if (V.get()->getType()->isArithmeticType())
4460     return V.get()->getType();
4461 
4462   // Test for placeholders.
4463   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4464   if (PR.isInvalid()) return QualType();
4465   if (PR.get() != V.get()) {
4466     V = PR;
4467     return CheckRealImagOperand(S, V, Loc, IsReal);
4468   }
4469 
4470   // Reject anything else.
4471   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4472     << (IsReal ? "__real" : "__imag");
4473   return QualType();
4474 }
4475 
4476 
4477 
4478 ExprResult
4479 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4480                           tok::TokenKind Kind, Expr *Input) {
4481   UnaryOperatorKind Opc;
4482   switch (Kind) {
4483   default: llvm_unreachable("Unknown unary op!");
4484   case tok::plusplus:   Opc = UO_PostInc; break;
4485   case tok::minusminus: Opc = UO_PostDec; break;
4486   }
4487 
4488   // Since this might is a postfix expression, get rid of ParenListExprs.
4489   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4490   if (Result.isInvalid()) return ExprError();
4491   Input = Result.get();
4492 
4493   return BuildUnaryOp(S, OpLoc, Opc, Input);
4494 }
4495 
4496 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4497 ///
4498 /// \return true on error
4499 static bool checkArithmeticOnObjCPointer(Sema &S,
4500                                          SourceLocation opLoc,
4501                                          Expr *op) {
4502   assert(op->getType()->isObjCObjectPointerType());
4503   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4504       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4505     return false;
4506 
4507   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4508     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4509     << op->getSourceRange();
4510   return true;
4511 }
4512 
4513 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4514   auto *BaseNoParens = Base->IgnoreParens();
4515   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4516     return MSProp->getPropertyDecl()->getType()->isArrayType();
4517   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4518 }
4519 
4520 ExprResult
4521 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4522                               Expr *idx, SourceLocation rbLoc) {
4523   if (base && !base->getType().isNull() &&
4524       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4525     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4526                                     /*Length=*/nullptr, rbLoc);
4527 
4528   // Since this might be a postfix expression, get rid of ParenListExprs.
4529   if (isa<ParenListExpr>(base)) {
4530     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4531     if (result.isInvalid()) return ExprError();
4532     base = result.get();
4533   }
4534 
4535   // A comma-expression as the index is deprecated in C++2a onwards.
4536   if (getLangOpts().CPlusPlus2a &&
4537       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4538        (isa<CXXOperatorCallExpr>(idx) &&
4539         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4540     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4541       << SourceRange(base->getBeginLoc(), rbLoc);
4542   }
4543 
4544   // Handle any non-overload placeholder types in the base and index
4545   // expressions.  We can't handle overloads here because the other
4546   // operand might be an overloadable type, in which case the overload
4547   // resolution for the operator overload should get the first crack
4548   // at the overload.
4549   bool IsMSPropertySubscript = false;
4550   if (base->getType()->isNonOverloadPlaceholderType()) {
4551     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4552     if (!IsMSPropertySubscript) {
4553       ExprResult result = CheckPlaceholderExpr(base);
4554       if (result.isInvalid())
4555         return ExprError();
4556       base = result.get();
4557     }
4558   }
4559   if (idx->getType()->isNonOverloadPlaceholderType()) {
4560     ExprResult result = CheckPlaceholderExpr(idx);
4561     if (result.isInvalid()) return ExprError();
4562     idx = result.get();
4563   }
4564 
4565   // Build an unanalyzed expression if either operand is type-dependent.
4566   if (getLangOpts().CPlusPlus &&
4567       (base->isTypeDependent() || idx->isTypeDependent())) {
4568     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4569                                             VK_LValue, OK_Ordinary, rbLoc);
4570   }
4571 
4572   // MSDN, property (C++)
4573   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4574   // This attribute can also be used in the declaration of an empty array in a
4575   // class or structure definition. For example:
4576   // __declspec(property(get=GetX, put=PutX)) int x[];
4577   // The above statement indicates that x[] can be used with one or more array
4578   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4579   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4580   if (IsMSPropertySubscript) {
4581     // Build MS property subscript expression if base is MS property reference
4582     // or MS property subscript.
4583     return new (Context) MSPropertySubscriptExpr(
4584         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4585   }
4586 
4587   // Use C++ overloaded-operator rules if either operand has record
4588   // type.  The spec says to do this if either type is *overloadable*,
4589   // but enum types can't declare subscript operators or conversion
4590   // operators, so there's nothing interesting for overload resolution
4591   // to do if there aren't any record types involved.
4592   //
4593   // ObjC pointers have their own subscripting logic that is not tied
4594   // to overload resolution and so should not take this path.
4595   if (getLangOpts().CPlusPlus &&
4596       (base->getType()->isRecordType() ||
4597        (!base->getType()->isObjCObjectPointerType() &&
4598         idx->getType()->isRecordType()))) {
4599     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4600   }
4601 
4602   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4603 
4604   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4605     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4606 
4607   return Res;
4608 }
4609 
4610 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4611   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4612   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4613 
4614   // For expressions like `&(*s).b`, the base is recorded and what should be
4615   // checked.
4616   const MemberExpr *Member = nullptr;
4617   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4618     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4619 
4620   LastRecord.PossibleDerefs.erase(StrippedExpr);
4621 }
4622 
4623 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4624   QualType ResultTy = E->getType();
4625   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4626 
4627   // Bail if the element is an array since it is not memory access.
4628   if (isa<ArrayType>(ResultTy))
4629     return;
4630 
4631   if (ResultTy->hasAttr(attr::NoDeref)) {
4632     LastRecord.PossibleDerefs.insert(E);
4633     return;
4634   }
4635 
4636   // Check if the base type is a pointer to a member access of a struct
4637   // marked with noderef.
4638   const Expr *Base = E->getBase();
4639   QualType BaseTy = Base->getType();
4640   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4641     // Not a pointer access
4642     return;
4643 
4644   const MemberExpr *Member = nullptr;
4645   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4646          Member->isArrow())
4647     Base = Member->getBase();
4648 
4649   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4650     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4651       LastRecord.PossibleDerefs.insert(E);
4652   }
4653 }
4654 
4655 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4656                                           Expr *LowerBound,
4657                                           SourceLocation ColonLoc, Expr *Length,
4658                                           SourceLocation RBLoc) {
4659   if (Base->getType()->isPlaceholderType() &&
4660       !Base->getType()->isSpecificPlaceholderType(
4661           BuiltinType::OMPArraySection)) {
4662     ExprResult Result = CheckPlaceholderExpr(Base);
4663     if (Result.isInvalid())
4664       return ExprError();
4665     Base = Result.get();
4666   }
4667   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4668     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4669     if (Result.isInvalid())
4670       return ExprError();
4671     Result = DefaultLvalueConversion(Result.get());
4672     if (Result.isInvalid())
4673       return ExprError();
4674     LowerBound = Result.get();
4675   }
4676   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4677     ExprResult Result = CheckPlaceholderExpr(Length);
4678     if (Result.isInvalid())
4679       return ExprError();
4680     Result = DefaultLvalueConversion(Result.get());
4681     if (Result.isInvalid())
4682       return ExprError();
4683     Length = Result.get();
4684   }
4685 
4686   // Build an unanalyzed expression if either operand is type-dependent.
4687   if (Base->isTypeDependent() ||
4688       (LowerBound &&
4689        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4690       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4691     return new (Context)
4692         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4693                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4694   }
4695 
4696   // Perform default conversions.
4697   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4698   QualType ResultTy;
4699   if (OriginalTy->isAnyPointerType()) {
4700     ResultTy = OriginalTy->getPointeeType();
4701   } else if (OriginalTy->isArrayType()) {
4702     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4703   } else {
4704     return ExprError(
4705         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4706         << Base->getSourceRange());
4707   }
4708   // C99 6.5.2.1p1
4709   if (LowerBound) {
4710     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4711                                                       LowerBound);
4712     if (Res.isInvalid())
4713       return ExprError(Diag(LowerBound->getExprLoc(),
4714                             diag::err_omp_typecheck_section_not_integer)
4715                        << 0 << LowerBound->getSourceRange());
4716     LowerBound = Res.get();
4717 
4718     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4719         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4720       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4721           << 0 << LowerBound->getSourceRange();
4722   }
4723   if (Length) {
4724     auto Res =
4725         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4726     if (Res.isInvalid())
4727       return ExprError(Diag(Length->getExprLoc(),
4728                             diag::err_omp_typecheck_section_not_integer)
4729                        << 1 << Length->getSourceRange());
4730     Length = Res.get();
4731 
4732     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4733         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4734       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4735           << 1 << Length->getSourceRange();
4736   }
4737 
4738   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4739   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4740   // type. Note that functions are not objects, and that (in C99 parlance)
4741   // incomplete types are not object types.
4742   if (ResultTy->isFunctionType()) {
4743     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4744         << ResultTy << Base->getSourceRange();
4745     return ExprError();
4746   }
4747 
4748   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4749                           diag::err_omp_section_incomplete_type, Base))
4750     return ExprError();
4751 
4752   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4753     Expr::EvalResult Result;
4754     if (LowerBound->EvaluateAsInt(Result, Context)) {
4755       // OpenMP 4.5, [2.4 Array Sections]
4756       // The array section must be a subset of the original array.
4757       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4758       if (LowerBoundValue.isNegative()) {
4759         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4760             << LowerBound->getSourceRange();
4761         return ExprError();
4762       }
4763     }
4764   }
4765 
4766   if (Length) {
4767     Expr::EvalResult Result;
4768     if (Length->EvaluateAsInt(Result, Context)) {
4769       // OpenMP 4.5, [2.4 Array Sections]
4770       // The length must evaluate to non-negative integers.
4771       llvm::APSInt LengthValue = Result.Val.getInt();
4772       if (LengthValue.isNegative()) {
4773         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4774             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4775             << Length->getSourceRange();
4776         return ExprError();
4777       }
4778     }
4779   } else if (ColonLoc.isValid() &&
4780              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4781                                       !OriginalTy->isVariableArrayType()))) {
4782     // OpenMP 4.5, [2.4 Array Sections]
4783     // When the size of the array dimension is not known, the length must be
4784     // specified explicitly.
4785     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4786         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4787     return ExprError();
4788   }
4789 
4790   if (!Base->getType()->isSpecificPlaceholderType(
4791           BuiltinType::OMPArraySection)) {
4792     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4793     if (Result.isInvalid())
4794       return ExprError();
4795     Base = Result.get();
4796   }
4797   return new (Context)
4798       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4799                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4800 }
4801 
4802 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4803                                           SourceLocation RParenLoc,
4804                                           ArrayRef<Expr *> Dims,
4805                                           ArrayRef<SourceRange> Brackets) {
4806   if (Base->getType()->isPlaceholderType()) {
4807     ExprResult Result = CheckPlaceholderExpr(Base);
4808     if (Result.isInvalid())
4809       return ExprError();
4810     Result = DefaultLvalueConversion(Result.get());
4811     if (Result.isInvalid())
4812       return ExprError();
4813     Base = Result.get();
4814   }
4815   QualType BaseTy = Base->getType();
4816   // Delay analysis of the types/expressions if instantiation/specialization is
4817   // required.
4818   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4819     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4820                                        LParenLoc, RParenLoc, Dims, Brackets);
4821   if (!BaseTy->isPointerType() ||
4822       (!Base->isTypeDependent() &&
4823        BaseTy->getPointeeType()->isIncompleteType()))
4824     return ExprError(Diag(Base->getExprLoc(),
4825                           diag::err_omp_non_pointer_type_array_shaping_base)
4826                      << Base->getSourceRange());
4827 
4828   SmallVector<Expr *, 4> NewDims;
4829   bool ErrorFound = false;
4830   for (Expr *Dim : Dims) {
4831     if (Dim->getType()->isPlaceholderType()) {
4832       ExprResult Result = CheckPlaceholderExpr(Dim);
4833       if (Result.isInvalid()) {
4834         ErrorFound = true;
4835         continue;
4836       }
4837       Result = DefaultLvalueConversion(Result.get());
4838       if (Result.isInvalid()) {
4839         ErrorFound = true;
4840         continue;
4841       }
4842       Dim = Result.get();
4843     }
4844     if (!Dim->isTypeDependent()) {
4845       ExprResult Result =
4846           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4847       if (Result.isInvalid()) {
4848         ErrorFound = true;
4849         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4850             << Dim->getSourceRange();
4851         continue;
4852       }
4853       Dim = Result.get();
4854       Expr::EvalResult EvResult;
4855       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
4856         // OpenMP 5.0, [2.1.4 Array Shaping]
4857         // Each si is an integral type expression that must evaluate to a
4858         // positive integer.
4859         llvm::APSInt Value = EvResult.Val.getInt();
4860         if (!Value.isStrictlyPositive()) {
4861           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
4862               << Value.toString(/*Radix=*/10, /*Signed=*/true)
4863               << Dim->getSourceRange();
4864           ErrorFound = true;
4865           continue;
4866         }
4867       }
4868     }
4869     NewDims.push_back(Dim);
4870   }
4871   if (ErrorFound)
4872     return ExprError();
4873   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
4874                                      LParenLoc, RParenLoc, NewDims, Brackets);
4875 }
4876 
4877 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
4878                                       SourceLocation LLoc, SourceLocation RLoc,
4879                                       ArrayRef<OMPIteratorData> Data) {
4880   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
4881   bool IsCorrect = true;
4882   for (const OMPIteratorData &D : Data) {
4883     TypeSourceInfo *TInfo = nullptr;
4884     SourceLocation StartLoc;
4885     QualType DeclTy;
4886     if (!D.Type.getAsOpaquePtr()) {
4887       // OpenMP 5.0, 2.1.6 Iterators
4888       // In an iterator-specifier, if the iterator-type is not specified then
4889       // the type of that iterator is of int type.
4890       DeclTy = Context.IntTy;
4891       StartLoc = D.DeclIdentLoc;
4892     } else {
4893       DeclTy = GetTypeFromParser(D.Type, &TInfo);
4894       StartLoc = TInfo->getTypeLoc().getBeginLoc();
4895     }
4896 
4897     bool IsDeclTyDependent = DeclTy->isDependentType() ||
4898                              DeclTy->containsUnexpandedParameterPack() ||
4899                              DeclTy->isInstantiationDependentType();
4900     if (!IsDeclTyDependent) {
4901       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
4902         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4903         // The iterator-type must be an integral or pointer type.
4904         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4905             << DeclTy;
4906         IsCorrect = false;
4907         continue;
4908       }
4909       if (DeclTy.isConstant(Context)) {
4910         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4911         // The iterator-type must not be const qualified.
4912         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4913             << DeclTy;
4914         IsCorrect = false;
4915         continue;
4916       }
4917     }
4918 
4919     // Iterator declaration.
4920     assert(D.DeclIdent && "Identifier expected.");
4921     // Always try to create iterator declarator to avoid extra error messages
4922     // about unknown declarations use.
4923     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
4924                                D.DeclIdent, DeclTy, TInfo, SC_None);
4925     VD->setImplicit();
4926     if (S) {
4927       // Check for conflicting previous declaration.
4928       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
4929       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4930                             ForVisibleRedeclaration);
4931       Previous.suppressDiagnostics();
4932       LookupName(Previous, S);
4933 
4934       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
4935                            /*AllowInlineNamespace=*/false);
4936       if (!Previous.empty()) {
4937         NamedDecl *Old = Previous.getRepresentativeDecl();
4938         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
4939         Diag(Old->getLocation(), diag::note_previous_definition);
4940       } else {
4941         PushOnScopeChains(VD, S);
4942       }
4943     } else {
4944       CurContext->addDecl(VD);
4945     }
4946     Expr *Begin = D.Range.Begin;
4947     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
4948       ExprResult BeginRes =
4949           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
4950       Begin = BeginRes.get();
4951     }
4952     Expr *End = D.Range.End;
4953     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
4954       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
4955       End = EndRes.get();
4956     }
4957     Expr *Step = D.Range.Step;
4958     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
4959       if (!Step->getType()->isIntegralType(Context)) {
4960         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
4961             << Step << Step->getSourceRange();
4962         IsCorrect = false;
4963         continue;
4964       }
4965       llvm::APSInt Result;
4966       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
4967       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
4968       // If the step expression of a range-specification equals zero, the
4969       // behavior is unspecified.
4970       if (IsConstant && Result.isNullValue()) {
4971         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
4972             << Step << Step->getSourceRange();
4973         IsCorrect = false;
4974         continue;
4975       }
4976     }
4977     if (!Begin || !End || !IsCorrect) {
4978       IsCorrect = false;
4979       continue;
4980     }
4981     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
4982     IDElem.IteratorDecl = VD;
4983     IDElem.AssignmentLoc = D.AssignLoc;
4984     IDElem.Range.Begin = Begin;
4985     IDElem.Range.End = End;
4986     IDElem.Range.Step = Step;
4987     IDElem.ColonLoc = D.ColonLoc;
4988     IDElem.SecondColonLoc = D.SecColonLoc;
4989   }
4990   if (!IsCorrect) {
4991     // Invalidate all created iterator declarations if error is found.
4992     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
4993       if (Decl *ID = D.IteratorDecl)
4994         ID->setInvalidDecl();
4995     }
4996     return ExprError();
4997   }
4998   SmallVector<OMPIteratorHelperData, 4> Helpers;
4999   if (!CurContext->isDependentContext()) {
5000     // Build number of ityeration for each iteration range.
5001     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5002     // ((Begini-Stepi-1-Endi) / -Stepi);
5003     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5004       // (Endi - Begini)
5005       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5006                                           D.Range.Begin);
5007       if(!Res.isUsable()) {
5008         IsCorrect = false;
5009         continue;
5010       }
5011       ExprResult St, St1;
5012       if (D.Range.Step) {
5013         St = D.Range.Step;
5014         // (Endi - Begini) + Stepi
5015         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5016         if (!Res.isUsable()) {
5017           IsCorrect = false;
5018           continue;
5019         }
5020         // (Endi - Begini) + Stepi - 1
5021         Res =
5022             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5023                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5024         if (!Res.isUsable()) {
5025           IsCorrect = false;
5026           continue;
5027         }
5028         // ((Endi - Begini) + Stepi - 1) / Stepi
5029         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5030         if (!Res.isUsable()) {
5031           IsCorrect = false;
5032           continue;
5033         }
5034         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5035         // (Begini - Endi)
5036         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5037                                              D.Range.Begin, D.Range.End);
5038         if (!Res1.isUsable()) {
5039           IsCorrect = false;
5040           continue;
5041         }
5042         // (Begini - Endi) - Stepi
5043         Res1 =
5044             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5045         if (!Res1.isUsable()) {
5046           IsCorrect = false;
5047           continue;
5048         }
5049         // (Begini - Endi) - Stepi - 1
5050         Res1 =
5051             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5052                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5053         if (!Res1.isUsable()) {
5054           IsCorrect = false;
5055           continue;
5056         }
5057         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5058         Res1 =
5059             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5060         if (!Res1.isUsable()) {
5061           IsCorrect = false;
5062           continue;
5063         }
5064         // Stepi > 0.
5065         ExprResult CmpRes =
5066             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5067                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5068         if (!CmpRes.isUsable()) {
5069           IsCorrect = false;
5070           continue;
5071         }
5072         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5073                                  Res.get(), Res1.get());
5074         if (!Res.isUsable()) {
5075           IsCorrect = false;
5076           continue;
5077         }
5078       }
5079       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5080       if (!Res.isUsable()) {
5081         IsCorrect = false;
5082         continue;
5083       }
5084 
5085       // Build counter update.
5086       // Build counter.
5087       auto *CounterVD =
5088           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5089                           D.IteratorDecl->getBeginLoc(), nullptr,
5090                           Res.get()->getType(), nullptr, SC_None);
5091       CounterVD->setImplicit();
5092       ExprResult RefRes =
5093           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5094                            D.IteratorDecl->getBeginLoc());
5095       // Build counter update.
5096       // I = Begini + counter * Stepi;
5097       ExprResult UpdateRes;
5098       if (D.Range.Step) {
5099         UpdateRes = CreateBuiltinBinOp(
5100             D.AssignmentLoc, BO_Mul,
5101             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5102       } else {
5103         UpdateRes = DefaultLvalueConversion(RefRes.get());
5104       }
5105       if (!UpdateRes.isUsable()) {
5106         IsCorrect = false;
5107         continue;
5108       }
5109       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5110                                      UpdateRes.get());
5111       if (!UpdateRes.isUsable()) {
5112         IsCorrect = false;
5113         continue;
5114       }
5115       ExprResult VDRes =
5116           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5117                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5118                            D.IteratorDecl->getBeginLoc());
5119       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5120                                      UpdateRes.get());
5121       if (!UpdateRes.isUsable()) {
5122         IsCorrect = false;
5123         continue;
5124       }
5125       UpdateRes =
5126           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5127       if (!UpdateRes.isUsable()) {
5128         IsCorrect = false;
5129         continue;
5130       }
5131       ExprResult CounterUpdateRes =
5132           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5133       if (!CounterUpdateRes.isUsable()) {
5134         IsCorrect = false;
5135         continue;
5136       }
5137       CounterUpdateRes =
5138           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5139       if (!CounterUpdateRes.isUsable()) {
5140         IsCorrect = false;
5141         continue;
5142       }
5143       OMPIteratorHelperData &HD = Helpers.emplace_back();
5144       HD.CounterVD = CounterVD;
5145       HD.Upper = Res.get();
5146       HD.Update = UpdateRes.get();
5147       HD.CounterUpdate = CounterUpdateRes.get();
5148     }
5149   } else {
5150     Helpers.assign(ID.size(), {});
5151   }
5152   if (!IsCorrect) {
5153     // Invalidate all created iterator declarations if error is found.
5154     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5155       if (Decl *ID = D.IteratorDecl)
5156         ID->setInvalidDecl();
5157     }
5158     return ExprError();
5159   }
5160   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5161                                  LLoc, RLoc, ID, Helpers);
5162 }
5163 
5164 ExprResult
5165 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5166                                       Expr *Idx, SourceLocation RLoc) {
5167   Expr *LHSExp = Base;
5168   Expr *RHSExp = Idx;
5169 
5170   ExprValueKind VK = VK_LValue;
5171   ExprObjectKind OK = OK_Ordinary;
5172 
5173   // Per C++ core issue 1213, the result is an xvalue if either operand is
5174   // a non-lvalue array, and an lvalue otherwise.
5175   if (getLangOpts().CPlusPlus11) {
5176     for (auto *Op : {LHSExp, RHSExp}) {
5177       Op = Op->IgnoreImplicit();
5178       if (Op->getType()->isArrayType() && !Op->isLValue())
5179         VK = VK_XValue;
5180     }
5181   }
5182 
5183   // Perform default conversions.
5184   if (!LHSExp->getType()->getAs<VectorType>()) {
5185     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5186     if (Result.isInvalid())
5187       return ExprError();
5188     LHSExp = Result.get();
5189   }
5190   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5191   if (Result.isInvalid())
5192     return ExprError();
5193   RHSExp = Result.get();
5194 
5195   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5196 
5197   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5198   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5199   // in the subscript position. As a result, we need to derive the array base
5200   // and index from the expression types.
5201   Expr *BaseExpr, *IndexExpr;
5202   QualType ResultType;
5203   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5204     BaseExpr = LHSExp;
5205     IndexExpr = RHSExp;
5206     ResultType = Context.DependentTy;
5207   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5208     BaseExpr = LHSExp;
5209     IndexExpr = RHSExp;
5210     ResultType = PTy->getPointeeType();
5211   } else if (const ObjCObjectPointerType *PTy =
5212                LHSTy->getAs<ObjCObjectPointerType>()) {
5213     BaseExpr = LHSExp;
5214     IndexExpr = RHSExp;
5215 
5216     // Use custom logic if this should be the pseudo-object subscript
5217     // expression.
5218     if (!LangOpts.isSubscriptPointerArithmetic())
5219       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5220                                           nullptr);
5221 
5222     ResultType = PTy->getPointeeType();
5223   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5224      // Handle the uncommon case of "123[Ptr]".
5225     BaseExpr = RHSExp;
5226     IndexExpr = LHSExp;
5227     ResultType = PTy->getPointeeType();
5228   } else if (const ObjCObjectPointerType *PTy =
5229                RHSTy->getAs<ObjCObjectPointerType>()) {
5230      // Handle the uncommon case of "123[Ptr]".
5231     BaseExpr = RHSExp;
5232     IndexExpr = LHSExp;
5233     ResultType = PTy->getPointeeType();
5234     if (!LangOpts.isSubscriptPointerArithmetic()) {
5235       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5236         << ResultType << BaseExpr->getSourceRange();
5237       return ExprError();
5238     }
5239   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5240     BaseExpr = LHSExp;    // vectors: V[123]
5241     IndexExpr = RHSExp;
5242     // We apply C++ DR1213 to vector subscripting too.
5243     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5244       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5245       if (Materialized.isInvalid())
5246         return ExprError();
5247       LHSExp = Materialized.get();
5248     }
5249     VK = LHSExp->getValueKind();
5250     if (VK != VK_RValue)
5251       OK = OK_VectorComponent;
5252 
5253     ResultType = VTy->getElementType();
5254     QualType BaseType = BaseExpr->getType();
5255     Qualifiers BaseQuals = BaseType.getQualifiers();
5256     Qualifiers MemberQuals = ResultType.getQualifiers();
5257     Qualifiers Combined = BaseQuals + MemberQuals;
5258     if (Combined != MemberQuals)
5259       ResultType = Context.getQualifiedType(ResultType, Combined);
5260   } else if (LHSTy->isArrayType()) {
5261     // If we see an array that wasn't promoted by
5262     // DefaultFunctionArrayLvalueConversion, it must be an array that
5263     // wasn't promoted because of the C90 rule that doesn't
5264     // allow promoting non-lvalue arrays.  Warn, then
5265     // force the promotion here.
5266     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5267         << LHSExp->getSourceRange();
5268     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5269                                CK_ArrayToPointerDecay).get();
5270     LHSTy = LHSExp->getType();
5271 
5272     BaseExpr = LHSExp;
5273     IndexExpr = RHSExp;
5274     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5275   } else if (RHSTy->isArrayType()) {
5276     // Same as previous, except for 123[f().a] case
5277     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5278         << RHSExp->getSourceRange();
5279     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5280                                CK_ArrayToPointerDecay).get();
5281     RHSTy = RHSExp->getType();
5282 
5283     BaseExpr = RHSExp;
5284     IndexExpr = LHSExp;
5285     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5286   } else {
5287     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5288        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5289   }
5290   // C99 6.5.2.1p1
5291   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5292     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5293                      << IndexExpr->getSourceRange());
5294 
5295   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5296        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5297          && !IndexExpr->isTypeDependent())
5298     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5299 
5300   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5301   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5302   // type. Note that Functions are not objects, and that (in C99 parlance)
5303   // incomplete types are not object types.
5304   if (ResultType->isFunctionType()) {
5305     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5306         << ResultType << BaseExpr->getSourceRange();
5307     return ExprError();
5308   }
5309 
5310   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5311     // GNU extension: subscripting on pointer to void
5312     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5313       << BaseExpr->getSourceRange();
5314 
5315     // C forbids expressions of unqualified void type from being l-values.
5316     // See IsCForbiddenLValueType.
5317     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5318   } else if (!ResultType->isDependentType() &&
5319              RequireCompleteSizedType(
5320                  LLoc, ResultType,
5321                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5322     return ExprError();
5323 
5324   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5325          !ResultType.isCForbiddenLValueType());
5326 
5327   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5328       FunctionScopes.size() > 1) {
5329     if (auto *TT =
5330             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5331       for (auto I = FunctionScopes.rbegin(),
5332                 E = std::prev(FunctionScopes.rend());
5333            I != E; ++I) {
5334         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5335         if (CSI == nullptr)
5336           break;
5337         DeclContext *DC = nullptr;
5338         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5339           DC = LSI->CallOperator;
5340         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5341           DC = CRSI->TheCapturedDecl;
5342         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5343           DC = BSI->TheDecl;
5344         if (DC) {
5345           if (DC->containsDecl(TT->getDecl()))
5346             break;
5347           captureVariablyModifiedType(
5348               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5349         }
5350       }
5351     }
5352   }
5353 
5354   return new (Context)
5355       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5356 }
5357 
5358 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5359                                   ParmVarDecl *Param) {
5360   if (Param->hasUnparsedDefaultArg()) {
5361     Diag(CallLoc,
5362          diag::err_use_of_default_argument_to_function_declared_later) <<
5363       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5364     Diag(UnparsedDefaultArgLocs[Param],
5365          diag::note_default_argument_declared_here);
5366     return true;
5367   }
5368 
5369   if (Param->hasUninstantiatedDefaultArg()) {
5370     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5371 
5372     EnterExpressionEvaluationContext EvalContext(
5373         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5374 
5375     // Instantiate the expression.
5376     //
5377     // FIXME: Pass in a correct Pattern argument, otherwise
5378     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5379     //
5380     // template<typename T>
5381     // struct A {
5382     //   static int FooImpl();
5383     //
5384     //   template<typename Tp>
5385     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5386     //   // template argument list [[T], [Tp]], should be [[Tp]].
5387     //   friend A<Tp> Foo(int a);
5388     // };
5389     //
5390     // template<typename T>
5391     // A<T> Foo(int a = A<T>::FooImpl());
5392     MultiLevelTemplateArgumentList MutiLevelArgList
5393       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5394 
5395     InstantiatingTemplate Inst(*this, CallLoc, Param,
5396                                MutiLevelArgList.getInnermost());
5397     if (Inst.isInvalid())
5398       return true;
5399     if (Inst.isAlreadyInstantiating()) {
5400       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5401       Param->setInvalidDecl();
5402       return true;
5403     }
5404 
5405     ExprResult Result;
5406     {
5407       // C++ [dcl.fct.default]p5:
5408       //   The names in the [default argument] expression are bound, and
5409       //   the semantic constraints are checked, at the point where the
5410       //   default argument expression appears.
5411       ContextRAII SavedContext(*this, FD);
5412       LocalInstantiationScope Local(*this);
5413       runWithSufficientStackSpace(CallLoc, [&] {
5414         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5415                                   /*DirectInit*/false);
5416       });
5417     }
5418     if (Result.isInvalid())
5419       return true;
5420 
5421     // Check the expression as an initializer for the parameter.
5422     InitializedEntity Entity
5423       = InitializedEntity::InitializeParameter(Context, Param);
5424     InitializationKind Kind = InitializationKind::CreateCopy(
5425         Param->getLocation(),
5426         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5427     Expr *ResultE = Result.getAs<Expr>();
5428 
5429     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5430     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5431     if (Result.isInvalid())
5432       return true;
5433 
5434     Result =
5435         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5436                             /*DiscardedValue*/ false);
5437     if (Result.isInvalid())
5438       return true;
5439 
5440     // Remember the instantiated default argument.
5441     Param->setDefaultArg(Result.getAs<Expr>());
5442     if (ASTMutationListener *L = getASTMutationListener()) {
5443       L->DefaultArgumentInstantiated(Param);
5444     }
5445   }
5446 
5447   // If the default argument expression is not set yet, we are building it now.
5448   if (!Param->hasInit()) {
5449     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5450     Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5451     Param->setInvalidDecl();
5452     return true;
5453   }
5454 
5455   // If the default expression creates temporaries, we need to
5456   // push them to the current stack of expression temporaries so they'll
5457   // be properly destroyed.
5458   // FIXME: We should really be rebuilding the default argument with new
5459   // bound temporaries; see the comment in PR5810.
5460   // We don't need to do that with block decls, though, because
5461   // blocks in default argument expression can never capture anything.
5462   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5463     // Set the "needs cleanups" bit regardless of whether there are
5464     // any explicit objects.
5465     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5466 
5467     // Append all the objects to the cleanup list.  Right now, this
5468     // should always be a no-op, because blocks in default argument
5469     // expressions should never be able to capture anything.
5470     assert(!Init->getNumObjects() &&
5471            "default argument expression has capturing blocks?");
5472   }
5473 
5474   // We already type-checked the argument, so we know it works.
5475   // Just mark all of the declarations in this potentially-evaluated expression
5476   // as being "referenced".
5477   EnterExpressionEvaluationContext EvalContext(
5478       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5479   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5480                                    /*SkipLocalVariables=*/true);
5481   return false;
5482 }
5483 
5484 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5485                                         FunctionDecl *FD, ParmVarDecl *Param) {
5486   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5487     return ExprError();
5488   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5489 }
5490 
5491 Sema::VariadicCallType
5492 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5493                           Expr *Fn) {
5494   if (Proto && Proto->isVariadic()) {
5495     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5496       return VariadicConstructor;
5497     else if (Fn && Fn->getType()->isBlockPointerType())
5498       return VariadicBlock;
5499     else if (FDecl) {
5500       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5501         if (Method->isInstance())
5502           return VariadicMethod;
5503     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5504       return VariadicMethod;
5505     return VariadicFunction;
5506   }
5507   return VariadicDoesNotApply;
5508 }
5509 
5510 namespace {
5511 class FunctionCallCCC final : public FunctionCallFilterCCC {
5512 public:
5513   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5514                   unsigned NumArgs, MemberExpr *ME)
5515       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5516         FunctionName(FuncName) {}
5517 
5518   bool ValidateCandidate(const TypoCorrection &candidate) override {
5519     if (!candidate.getCorrectionSpecifier() ||
5520         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5521       return false;
5522     }
5523 
5524     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5525   }
5526 
5527   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5528     return std::make_unique<FunctionCallCCC>(*this);
5529   }
5530 
5531 private:
5532   const IdentifierInfo *const FunctionName;
5533 };
5534 }
5535 
5536 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5537                                                FunctionDecl *FDecl,
5538                                                ArrayRef<Expr *> Args) {
5539   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5540   DeclarationName FuncName = FDecl->getDeclName();
5541   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5542 
5543   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5544   if (TypoCorrection Corrected = S.CorrectTypo(
5545           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5546           S.getScopeForContext(S.CurContext), nullptr, CCC,
5547           Sema::CTK_ErrorRecovery)) {
5548     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5549       if (Corrected.isOverloaded()) {
5550         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5551         OverloadCandidateSet::iterator Best;
5552         for (NamedDecl *CD : Corrected) {
5553           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5554             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5555                                    OCS);
5556         }
5557         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5558         case OR_Success:
5559           ND = Best->FoundDecl;
5560           Corrected.setCorrectionDecl(ND);
5561           break;
5562         default:
5563           break;
5564         }
5565       }
5566       ND = ND->getUnderlyingDecl();
5567       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5568         return Corrected;
5569     }
5570   }
5571   return TypoCorrection();
5572 }
5573 
5574 /// ConvertArgumentsForCall - Converts the arguments specified in
5575 /// Args/NumArgs to the parameter types of the function FDecl with
5576 /// function prototype Proto. Call is the call expression itself, and
5577 /// Fn is the function expression. For a C++ member function, this
5578 /// routine does not attempt to convert the object argument. Returns
5579 /// true if the call is ill-formed.
5580 bool
5581 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5582                               FunctionDecl *FDecl,
5583                               const FunctionProtoType *Proto,
5584                               ArrayRef<Expr *> Args,
5585                               SourceLocation RParenLoc,
5586                               bool IsExecConfig) {
5587   // Bail out early if calling a builtin with custom typechecking.
5588   if (FDecl)
5589     if (unsigned ID = FDecl->getBuiltinID())
5590       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5591         return false;
5592 
5593   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5594   // assignment, to the types of the corresponding parameter, ...
5595   unsigned NumParams = Proto->getNumParams();
5596   bool Invalid = false;
5597   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5598   unsigned FnKind = Fn->getType()->isBlockPointerType()
5599                        ? 1 /* block */
5600                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5601                                        : 0 /* function */);
5602 
5603   // If too few arguments are available (and we don't have default
5604   // arguments for the remaining parameters), don't make the call.
5605   if (Args.size() < NumParams) {
5606     if (Args.size() < MinArgs) {
5607       TypoCorrection TC;
5608       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5609         unsigned diag_id =
5610             MinArgs == NumParams && !Proto->isVariadic()
5611                 ? diag::err_typecheck_call_too_few_args_suggest
5612                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5613         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5614                                         << static_cast<unsigned>(Args.size())
5615                                         << TC.getCorrectionRange());
5616       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5617         Diag(RParenLoc,
5618              MinArgs == NumParams && !Proto->isVariadic()
5619                  ? diag::err_typecheck_call_too_few_args_one
5620                  : diag::err_typecheck_call_too_few_args_at_least_one)
5621             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5622       else
5623         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5624                             ? diag::err_typecheck_call_too_few_args
5625                             : diag::err_typecheck_call_too_few_args_at_least)
5626             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5627             << Fn->getSourceRange();
5628 
5629       // Emit the location of the prototype.
5630       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5631         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5632 
5633       return true;
5634     }
5635     // We reserve space for the default arguments when we create
5636     // the call expression, before calling ConvertArgumentsForCall.
5637     assert((Call->getNumArgs() == NumParams) &&
5638            "We should have reserved space for the default arguments before!");
5639   }
5640 
5641   // If too many are passed and not variadic, error on the extras and drop
5642   // them.
5643   if (Args.size() > NumParams) {
5644     if (!Proto->isVariadic()) {
5645       TypoCorrection TC;
5646       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5647         unsigned diag_id =
5648             MinArgs == NumParams && !Proto->isVariadic()
5649                 ? diag::err_typecheck_call_too_many_args_suggest
5650                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5651         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5652                                         << static_cast<unsigned>(Args.size())
5653                                         << TC.getCorrectionRange());
5654       } else if (NumParams == 1 && FDecl &&
5655                  FDecl->getParamDecl(0)->getDeclName())
5656         Diag(Args[NumParams]->getBeginLoc(),
5657              MinArgs == NumParams
5658                  ? diag::err_typecheck_call_too_many_args_one
5659                  : diag::err_typecheck_call_too_many_args_at_most_one)
5660             << FnKind << FDecl->getParamDecl(0)
5661             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5662             << SourceRange(Args[NumParams]->getBeginLoc(),
5663                            Args.back()->getEndLoc());
5664       else
5665         Diag(Args[NumParams]->getBeginLoc(),
5666              MinArgs == NumParams
5667                  ? diag::err_typecheck_call_too_many_args
5668                  : diag::err_typecheck_call_too_many_args_at_most)
5669             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5670             << Fn->getSourceRange()
5671             << SourceRange(Args[NumParams]->getBeginLoc(),
5672                            Args.back()->getEndLoc());
5673 
5674       // Emit the location of the prototype.
5675       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5676         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5677 
5678       // This deletes the extra arguments.
5679       Call->shrinkNumArgs(NumParams);
5680       return true;
5681     }
5682   }
5683   SmallVector<Expr *, 8> AllArgs;
5684   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5685 
5686   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5687                                    AllArgs, CallType);
5688   if (Invalid)
5689     return true;
5690   unsigned TotalNumArgs = AllArgs.size();
5691   for (unsigned i = 0; i < TotalNumArgs; ++i)
5692     Call->setArg(i, AllArgs[i]);
5693 
5694   return false;
5695 }
5696 
5697 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5698                                   const FunctionProtoType *Proto,
5699                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5700                                   SmallVectorImpl<Expr *> &AllArgs,
5701                                   VariadicCallType CallType, bool AllowExplicit,
5702                                   bool IsListInitialization) {
5703   unsigned NumParams = Proto->getNumParams();
5704   bool Invalid = false;
5705   size_t ArgIx = 0;
5706   // Continue to check argument types (even if we have too few/many args).
5707   for (unsigned i = FirstParam; i < NumParams; i++) {
5708     QualType ProtoArgType = Proto->getParamType(i);
5709 
5710     Expr *Arg;
5711     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5712     if (ArgIx < Args.size()) {
5713       Arg = Args[ArgIx++];
5714 
5715       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5716                               diag::err_call_incomplete_argument, Arg))
5717         return true;
5718 
5719       // Strip the unbridged-cast placeholder expression off, if applicable.
5720       bool CFAudited = false;
5721       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5722           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5723           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5724         Arg = stripARCUnbridgedCast(Arg);
5725       else if (getLangOpts().ObjCAutoRefCount &&
5726                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5727                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5728         CFAudited = true;
5729 
5730       if (Proto->getExtParameterInfo(i).isNoEscape())
5731         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5732           BE->getBlockDecl()->setDoesNotEscape();
5733 
5734       InitializedEntity Entity =
5735           Param ? InitializedEntity::InitializeParameter(Context, Param,
5736                                                          ProtoArgType)
5737                 : InitializedEntity::InitializeParameter(
5738                       Context, ProtoArgType, Proto->isParamConsumed(i));
5739 
5740       // Remember that parameter belongs to a CF audited API.
5741       if (CFAudited)
5742         Entity.setParameterCFAudited();
5743 
5744       ExprResult ArgE = PerformCopyInitialization(
5745           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5746       if (ArgE.isInvalid())
5747         return true;
5748 
5749       Arg = ArgE.getAs<Expr>();
5750     } else {
5751       assert(Param && "can't use default arguments without a known callee");
5752 
5753       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5754       if (ArgExpr.isInvalid())
5755         return true;
5756 
5757       Arg = ArgExpr.getAs<Expr>();
5758     }
5759 
5760     // Check for array bounds violations for each argument to the call. This
5761     // check only triggers warnings when the argument isn't a more complex Expr
5762     // with its own checking, such as a BinaryOperator.
5763     CheckArrayAccess(Arg);
5764 
5765     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5766     CheckStaticArrayArgument(CallLoc, Param, Arg);
5767 
5768     AllArgs.push_back(Arg);
5769   }
5770 
5771   // If this is a variadic call, handle args passed through "...".
5772   if (CallType != VariadicDoesNotApply) {
5773     // Assume that extern "C" functions with variadic arguments that
5774     // return __unknown_anytype aren't *really* variadic.
5775     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5776         FDecl->isExternC()) {
5777       for (Expr *A : Args.slice(ArgIx)) {
5778         QualType paramType; // ignored
5779         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5780         Invalid |= arg.isInvalid();
5781         AllArgs.push_back(arg.get());
5782       }
5783 
5784     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5785     } else {
5786       for (Expr *A : Args.slice(ArgIx)) {
5787         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5788         Invalid |= Arg.isInvalid();
5789         // Copy blocks to the heap.
5790         if (A->getType()->isBlockPointerType())
5791           maybeExtendBlockObject(Arg);
5792         AllArgs.push_back(Arg.get());
5793       }
5794     }
5795 
5796     // Check for array bounds violations.
5797     for (Expr *A : Args.slice(ArgIx))
5798       CheckArrayAccess(A);
5799   }
5800   return Invalid;
5801 }
5802 
5803 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5804   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5805   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5806     TL = DTL.getOriginalLoc();
5807   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5808     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5809       << ATL.getLocalSourceRange();
5810 }
5811 
5812 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5813 /// array parameter, check that it is non-null, and that if it is formed by
5814 /// array-to-pointer decay, the underlying array is sufficiently large.
5815 ///
5816 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5817 /// array type derivation, then for each call to the function, the value of the
5818 /// corresponding actual argument shall provide access to the first element of
5819 /// an array with at least as many elements as specified by the size expression.
5820 void
5821 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5822                                ParmVarDecl *Param,
5823                                const Expr *ArgExpr) {
5824   // Static array parameters are not supported in C++.
5825   if (!Param || getLangOpts().CPlusPlus)
5826     return;
5827 
5828   QualType OrigTy = Param->getOriginalType();
5829 
5830   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5831   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5832     return;
5833 
5834   if (ArgExpr->isNullPointerConstant(Context,
5835                                      Expr::NPC_NeverValueDependent)) {
5836     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5837     DiagnoseCalleeStaticArrayParam(*this, Param);
5838     return;
5839   }
5840 
5841   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5842   if (!CAT)
5843     return;
5844 
5845   const ConstantArrayType *ArgCAT =
5846     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5847   if (!ArgCAT)
5848     return;
5849 
5850   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5851                                              ArgCAT->getElementType())) {
5852     if (ArgCAT->getSize().ult(CAT->getSize())) {
5853       Diag(CallLoc, diag::warn_static_array_too_small)
5854           << ArgExpr->getSourceRange()
5855           << (unsigned)ArgCAT->getSize().getZExtValue()
5856           << (unsigned)CAT->getSize().getZExtValue() << 0;
5857       DiagnoseCalleeStaticArrayParam(*this, Param);
5858     }
5859     return;
5860   }
5861 
5862   Optional<CharUnits> ArgSize =
5863       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5864   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5865   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5866     Diag(CallLoc, diag::warn_static_array_too_small)
5867         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5868         << (unsigned)ParmSize->getQuantity() << 1;
5869     DiagnoseCalleeStaticArrayParam(*this, Param);
5870   }
5871 }
5872 
5873 /// Given a function expression of unknown-any type, try to rebuild it
5874 /// to have a function type.
5875 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5876 
5877 /// Is the given type a placeholder that we need to lower out
5878 /// immediately during argument processing?
5879 static bool isPlaceholderToRemoveAsArg(QualType type) {
5880   // Placeholders are never sugared.
5881   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5882   if (!placeholder) return false;
5883 
5884   switch (placeholder->getKind()) {
5885   // Ignore all the non-placeholder types.
5886 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5887   case BuiltinType::Id:
5888 #include "clang/Basic/OpenCLImageTypes.def"
5889 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5890   case BuiltinType::Id:
5891 #include "clang/Basic/OpenCLExtensionTypes.def"
5892   // In practice we'll never use this, since all SVE types are sugared
5893   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5894 #define SVE_TYPE(Name, Id, SingletonId) \
5895   case BuiltinType::Id:
5896 #include "clang/Basic/AArch64SVEACLETypes.def"
5897 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5898 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5899 #include "clang/AST/BuiltinTypes.def"
5900     return false;
5901 
5902   // We cannot lower out overload sets; they might validly be resolved
5903   // by the call machinery.
5904   case BuiltinType::Overload:
5905     return false;
5906 
5907   // Unbridged casts in ARC can be handled in some call positions and
5908   // should be left in place.
5909   case BuiltinType::ARCUnbridgedCast:
5910     return false;
5911 
5912   // Pseudo-objects should be converted as soon as possible.
5913   case BuiltinType::PseudoObject:
5914     return true;
5915 
5916   // The debugger mode could theoretically but currently does not try
5917   // to resolve unknown-typed arguments based on known parameter types.
5918   case BuiltinType::UnknownAny:
5919     return true;
5920 
5921   // These are always invalid as call arguments and should be reported.
5922   case BuiltinType::BoundMember:
5923   case BuiltinType::BuiltinFn:
5924   case BuiltinType::OMPArraySection:
5925   case BuiltinType::OMPArrayShaping:
5926   case BuiltinType::OMPIterator:
5927     return true;
5928 
5929   }
5930   llvm_unreachable("bad builtin type kind");
5931 }
5932 
5933 /// Check an argument list for placeholders that we won't try to
5934 /// handle later.
5935 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5936   // Apply this processing to all the arguments at once instead of
5937   // dying at the first failure.
5938   bool hasInvalid = false;
5939   for (size_t i = 0, e = args.size(); i != e; i++) {
5940     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5941       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5942       if (result.isInvalid()) hasInvalid = true;
5943       else args[i] = result.get();
5944     } else if (hasInvalid) {
5945       (void)S.CorrectDelayedTyposInExpr(args[i]);
5946     }
5947   }
5948   return hasInvalid;
5949 }
5950 
5951 /// If a builtin function has a pointer argument with no explicit address
5952 /// space, then it should be able to accept a pointer to any address
5953 /// space as input.  In order to do this, we need to replace the
5954 /// standard builtin declaration with one that uses the same address space
5955 /// as the call.
5956 ///
5957 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5958 ///                  it does not contain any pointer arguments without
5959 ///                  an address space qualifer.  Otherwise the rewritten
5960 ///                  FunctionDecl is returned.
5961 /// TODO: Handle pointer return types.
5962 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5963                                                 FunctionDecl *FDecl,
5964                                                 MultiExprArg ArgExprs) {
5965 
5966   QualType DeclType = FDecl->getType();
5967   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5968 
5969   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5970       ArgExprs.size() < FT->getNumParams())
5971     return nullptr;
5972 
5973   bool NeedsNewDecl = false;
5974   unsigned i = 0;
5975   SmallVector<QualType, 8> OverloadParams;
5976 
5977   for (QualType ParamType : FT->param_types()) {
5978 
5979     // Convert array arguments to pointer to simplify type lookup.
5980     ExprResult ArgRes =
5981         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5982     if (ArgRes.isInvalid())
5983       return nullptr;
5984     Expr *Arg = ArgRes.get();
5985     QualType ArgType = Arg->getType();
5986     if (!ParamType->isPointerType() ||
5987         ParamType.hasAddressSpace() ||
5988         !ArgType->isPointerType() ||
5989         !ArgType->getPointeeType().hasAddressSpace()) {
5990       OverloadParams.push_back(ParamType);
5991       continue;
5992     }
5993 
5994     QualType PointeeType = ParamType->getPointeeType();
5995     if (PointeeType.hasAddressSpace())
5996       continue;
5997 
5998     NeedsNewDecl = true;
5999     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6000 
6001     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6002     OverloadParams.push_back(Context.getPointerType(PointeeType));
6003   }
6004 
6005   if (!NeedsNewDecl)
6006     return nullptr;
6007 
6008   FunctionProtoType::ExtProtoInfo EPI;
6009   EPI.Variadic = FT->isVariadic();
6010   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6011                                                 OverloadParams, EPI);
6012   DeclContext *Parent = FDecl->getParent();
6013   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6014                                                     FDecl->getLocation(),
6015                                                     FDecl->getLocation(),
6016                                                     FDecl->getIdentifier(),
6017                                                     OverloadTy,
6018                                                     /*TInfo=*/nullptr,
6019                                                     SC_Extern, false,
6020                                                     /*hasPrototype=*/true);
6021   SmallVector<ParmVarDecl*, 16> Params;
6022   FT = cast<FunctionProtoType>(OverloadTy);
6023   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6024     QualType ParamType = FT->getParamType(i);
6025     ParmVarDecl *Parm =
6026         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6027                                 SourceLocation(), nullptr, ParamType,
6028                                 /*TInfo=*/nullptr, SC_None, nullptr);
6029     Parm->setScopeInfo(0, i);
6030     Params.push_back(Parm);
6031   }
6032   OverloadDecl->setParams(Params);
6033   return OverloadDecl;
6034 }
6035 
6036 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6037                                     FunctionDecl *Callee,
6038                                     MultiExprArg ArgExprs) {
6039   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6040   // similar attributes) really don't like it when functions are called with an
6041   // invalid number of args.
6042   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6043                          /*PartialOverloading=*/false) &&
6044       !Callee->isVariadic())
6045     return;
6046   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6047     return;
6048 
6049   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
6050     S.Diag(Fn->getBeginLoc(),
6051            isa<CXXMethodDecl>(Callee)
6052                ? diag::err_ovl_no_viable_member_function_in_call
6053                : diag::err_ovl_no_viable_function_in_call)
6054         << Callee << Callee->getSourceRange();
6055     S.Diag(Callee->getLocation(),
6056            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6057         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6058     return;
6059   }
6060 }
6061 
6062 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6063     const UnresolvedMemberExpr *const UME, Sema &S) {
6064 
6065   const auto GetFunctionLevelDCIfCXXClass =
6066       [](Sema &S) -> const CXXRecordDecl * {
6067     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6068     if (!DC || !DC->getParent())
6069       return nullptr;
6070 
6071     // If the call to some member function was made from within a member
6072     // function body 'M' return return 'M's parent.
6073     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6074       return MD->getParent()->getCanonicalDecl();
6075     // else the call was made from within a default member initializer of a
6076     // class, so return the class.
6077     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6078       return RD->getCanonicalDecl();
6079     return nullptr;
6080   };
6081   // If our DeclContext is neither a member function nor a class (in the
6082   // case of a lambda in a default member initializer), we can't have an
6083   // enclosing 'this'.
6084 
6085   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6086   if (!CurParentClass)
6087     return false;
6088 
6089   // The naming class for implicit member functions call is the class in which
6090   // name lookup starts.
6091   const CXXRecordDecl *const NamingClass =
6092       UME->getNamingClass()->getCanonicalDecl();
6093   assert(NamingClass && "Must have naming class even for implicit access");
6094 
6095   // If the unresolved member functions were found in a 'naming class' that is
6096   // related (either the same or derived from) to the class that contains the
6097   // member function that itself contained the implicit member access.
6098 
6099   return CurParentClass == NamingClass ||
6100          CurParentClass->isDerivedFrom(NamingClass);
6101 }
6102 
6103 static void
6104 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6105     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6106 
6107   if (!UME)
6108     return;
6109 
6110   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6111   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6112   // already been captured, or if this is an implicit member function call (if
6113   // it isn't, an attempt to capture 'this' should already have been made).
6114   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6115       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6116     return;
6117 
6118   // Check if the naming class in which the unresolved members were found is
6119   // related (same as or is a base of) to the enclosing class.
6120 
6121   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6122     return;
6123 
6124 
6125   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6126   // If the enclosing function is not dependent, then this lambda is
6127   // capture ready, so if we can capture this, do so.
6128   if (!EnclosingFunctionCtx->isDependentContext()) {
6129     // If the current lambda and all enclosing lambdas can capture 'this' -
6130     // then go ahead and capture 'this' (since our unresolved overload set
6131     // contains at least one non-static member function).
6132     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6133       S.CheckCXXThisCapture(CallLoc);
6134   } else if (S.CurContext->isDependentContext()) {
6135     // ... since this is an implicit member reference, that might potentially
6136     // involve a 'this' capture, mark 'this' for potential capture in
6137     // enclosing lambdas.
6138     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6139       CurLSI->addPotentialThisCapture(CallLoc);
6140   }
6141 }
6142 
6143 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6144                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6145                                Expr *ExecConfig) {
6146   ExprResult Call =
6147       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6148   if (Call.isInvalid())
6149     return Call;
6150 
6151   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6152   // language modes.
6153   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6154     if (ULE->hasExplicitTemplateArgs() &&
6155         ULE->decls_begin() == ULE->decls_end()) {
6156       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
6157                                  ? diag::warn_cxx17_compat_adl_only_template_id
6158                                  : diag::ext_adl_only_template_id)
6159           << ULE->getName();
6160     }
6161   }
6162 
6163   if (LangOpts.OpenMP)
6164     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6165                            ExecConfig);
6166 
6167   return Call;
6168 }
6169 
6170 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6171 /// This provides the location of the left/right parens and a list of comma
6172 /// locations.
6173 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6174                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6175                                Expr *ExecConfig, bool IsExecConfig) {
6176   // Since this might be a postfix expression, get rid of ParenListExprs.
6177   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6178   if (Result.isInvalid()) return ExprError();
6179   Fn = Result.get();
6180 
6181   if (checkArgsForPlaceholders(*this, ArgExprs))
6182     return ExprError();
6183 
6184   if (getLangOpts().CPlusPlus) {
6185     // If this is a pseudo-destructor expression, build the call immediately.
6186     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6187       if (!ArgExprs.empty()) {
6188         // Pseudo-destructor calls should not have any arguments.
6189         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6190             << FixItHint::CreateRemoval(
6191                    SourceRange(ArgExprs.front()->getBeginLoc(),
6192                                ArgExprs.back()->getEndLoc()));
6193       }
6194 
6195       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6196                               VK_RValue, RParenLoc);
6197     }
6198     if (Fn->getType() == Context.PseudoObjectTy) {
6199       ExprResult result = CheckPlaceholderExpr(Fn);
6200       if (result.isInvalid()) return ExprError();
6201       Fn = result.get();
6202     }
6203 
6204     // Determine whether this is a dependent call inside a C++ template,
6205     // in which case we won't do any semantic analysis now.
6206     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6207       if (ExecConfig) {
6208         return CUDAKernelCallExpr::Create(
6209             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6210             Context.DependentTy, VK_RValue, RParenLoc);
6211       } else {
6212 
6213         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6214             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6215             Fn->getBeginLoc());
6216 
6217         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6218                                 VK_RValue, RParenLoc);
6219       }
6220     }
6221 
6222     // Determine whether this is a call to an object (C++ [over.call.object]).
6223     if (Fn->getType()->isRecordType())
6224       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6225                                           RParenLoc);
6226 
6227     if (Fn->getType() == Context.UnknownAnyTy) {
6228       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6229       if (result.isInvalid()) return ExprError();
6230       Fn = result.get();
6231     }
6232 
6233     if (Fn->getType() == Context.BoundMemberTy) {
6234       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6235                                        RParenLoc);
6236     }
6237   }
6238 
6239   // Check for overloaded calls.  This can happen even in C due to extensions.
6240   if (Fn->getType() == Context.OverloadTy) {
6241     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6242 
6243     // We aren't supposed to apply this logic if there's an '&' involved.
6244     if (!find.HasFormOfMemberPointer) {
6245       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6246         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6247                                 VK_RValue, RParenLoc);
6248       OverloadExpr *ovl = find.Expression;
6249       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6250         return BuildOverloadedCallExpr(
6251             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6252             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6253       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6254                                        RParenLoc);
6255     }
6256   }
6257 
6258   // If we're directly calling a function, get the appropriate declaration.
6259   if (Fn->getType() == Context.UnknownAnyTy) {
6260     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6261     if (result.isInvalid()) return ExprError();
6262     Fn = result.get();
6263   }
6264 
6265   Expr *NakedFn = Fn->IgnoreParens();
6266 
6267   bool CallingNDeclIndirectly = false;
6268   NamedDecl *NDecl = nullptr;
6269   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6270     if (UnOp->getOpcode() == UO_AddrOf) {
6271       CallingNDeclIndirectly = true;
6272       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6273     }
6274   }
6275 
6276   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6277     NDecl = DRE->getDecl();
6278 
6279     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6280     if (FDecl && FDecl->getBuiltinID()) {
6281       // Rewrite the function decl for this builtin by replacing parameters
6282       // with no explicit address space with the address space of the arguments
6283       // in ArgExprs.
6284       if ((FDecl =
6285                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6286         NDecl = FDecl;
6287         Fn = DeclRefExpr::Create(
6288             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6289             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6290             nullptr, DRE->isNonOdrUse());
6291       }
6292     }
6293   } else if (isa<MemberExpr>(NakedFn))
6294     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6295 
6296   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6297     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6298                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6299       return ExprError();
6300 
6301     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6302       return ExprError();
6303 
6304     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6305   }
6306 
6307   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6308                                ExecConfig, IsExecConfig);
6309 }
6310 
6311 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6312 ///
6313 /// __builtin_astype( value, dst type )
6314 ///
6315 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6316                                  SourceLocation BuiltinLoc,
6317                                  SourceLocation RParenLoc) {
6318   ExprValueKind VK = VK_RValue;
6319   ExprObjectKind OK = OK_Ordinary;
6320   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6321   QualType SrcTy = E->getType();
6322   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6323     return ExprError(Diag(BuiltinLoc,
6324                           diag::err_invalid_astype_of_different_size)
6325                      << DstTy
6326                      << SrcTy
6327                      << E->getSourceRange());
6328   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6329 }
6330 
6331 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6332 /// provided arguments.
6333 ///
6334 /// __builtin_convertvector( value, dst type )
6335 ///
6336 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6337                                         SourceLocation BuiltinLoc,
6338                                         SourceLocation RParenLoc) {
6339   TypeSourceInfo *TInfo;
6340   GetTypeFromParser(ParsedDestTy, &TInfo);
6341   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6342 }
6343 
6344 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6345 /// i.e. an expression not of \p OverloadTy.  The expression should
6346 /// unary-convert to an expression of function-pointer or
6347 /// block-pointer type.
6348 ///
6349 /// \param NDecl the declaration being called, if available
6350 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6351                                        SourceLocation LParenLoc,
6352                                        ArrayRef<Expr *> Args,
6353                                        SourceLocation RParenLoc, Expr *Config,
6354                                        bool IsExecConfig, ADLCallKind UsesADL) {
6355   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6356   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6357 
6358   // Functions with 'interrupt' attribute cannot be called directly.
6359   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6360     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6361     return ExprError();
6362   }
6363 
6364   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6365   // so there's some risk when calling out to non-interrupt handler functions
6366   // that the callee might not preserve them. This is easy to diagnose here,
6367   // but can be very challenging to debug.
6368   if (auto *Caller = getCurFunctionDecl())
6369     if (Caller->hasAttr<ARMInterruptAttr>()) {
6370       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6371       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6372         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6373     }
6374 
6375   // Promote the function operand.
6376   // We special-case function promotion here because we only allow promoting
6377   // builtin functions to function pointers in the callee of a call.
6378   ExprResult Result;
6379   QualType ResultTy;
6380   if (BuiltinID &&
6381       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6382     // Extract the return type from the (builtin) function pointer type.
6383     // FIXME Several builtins still have setType in
6384     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6385     // Builtins.def to ensure they are correct before removing setType calls.
6386     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6387     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6388     ResultTy = FDecl->getCallResultType();
6389   } else {
6390     Result = CallExprUnaryConversions(Fn);
6391     ResultTy = Context.BoolTy;
6392   }
6393   if (Result.isInvalid())
6394     return ExprError();
6395   Fn = Result.get();
6396 
6397   // Check for a valid function type, but only if it is not a builtin which
6398   // requires custom type checking. These will be handled by
6399   // CheckBuiltinFunctionCall below just after creation of the call expression.
6400   const FunctionType *FuncT = nullptr;
6401   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6402   retry:
6403     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6404       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6405       // have type pointer to function".
6406       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6407       if (!FuncT)
6408         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6409                          << Fn->getType() << Fn->getSourceRange());
6410     } else if (const BlockPointerType *BPT =
6411                    Fn->getType()->getAs<BlockPointerType>()) {
6412       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6413     } else {
6414       // Handle calls to expressions of unknown-any type.
6415       if (Fn->getType() == Context.UnknownAnyTy) {
6416         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6417         if (rewrite.isInvalid())
6418           return ExprError();
6419         Fn = rewrite.get();
6420         goto retry;
6421       }
6422 
6423       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6424                        << Fn->getType() << Fn->getSourceRange());
6425     }
6426   }
6427 
6428   // Get the number of parameters in the function prototype, if any.
6429   // We will allocate space for max(Args.size(), NumParams) arguments
6430   // in the call expression.
6431   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6432   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6433 
6434   CallExpr *TheCall;
6435   if (Config) {
6436     assert(UsesADL == ADLCallKind::NotADL &&
6437            "CUDAKernelCallExpr should not use ADL");
6438     TheCall =
6439         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6440                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6441   } else {
6442     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6443                                RParenLoc, NumParams, UsesADL);
6444   }
6445 
6446   if (!getLangOpts().CPlusPlus) {
6447     // Forget about the nulled arguments since typo correction
6448     // do not handle them well.
6449     TheCall->shrinkNumArgs(Args.size());
6450     // C cannot always handle TypoExpr nodes in builtin calls and direct
6451     // function calls as their argument checking don't necessarily handle
6452     // dependent types properly, so make sure any TypoExprs have been
6453     // dealt with.
6454     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6455     if (!Result.isUsable()) return ExprError();
6456     CallExpr *TheOldCall = TheCall;
6457     TheCall = dyn_cast<CallExpr>(Result.get());
6458     bool CorrectedTypos = TheCall != TheOldCall;
6459     if (!TheCall) return Result;
6460     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6461 
6462     // A new call expression node was created if some typos were corrected.
6463     // However it may not have been constructed with enough storage. In this
6464     // case, rebuild the node with enough storage. The waste of space is
6465     // immaterial since this only happens when some typos were corrected.
6466     if (CorrectedTypos && Args.size() < NumParams) {
6467       if (Config)
6468         TheCall = CUDAKernelCallExpr::Create(
6469             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6470             RParenLoc, NumParams);
6471       else
6472         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6473                                    RParenLoc, NumParams, UsesADL);
6474     }
6475     // We can now handle the nulled arguments for the default arguments.
6476     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6477   }
6478 
6479   // Bail out early if calling a builtin with custom type checking.
6480   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6481     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6482 
6483   if (getLangOpts().CUDA) {
6484     if (Config) {
6485       // CUDA: Kernel calls must be to global functions
6486       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6487         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6488             << FDecl << Fn->getSourceRange());
6489 
6490       // CUDA: Kernel function must have 'void' return type
6491       if (!FuncT->getReturnType()->isVoidType() &&
6492           !FuncT->getReturnType()->getAs<AutoType>() &&
6493           !FuncT->getReturnType()->isInstantiationDependentType())
6494         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6495             << Fn->getType() << Fn->getSourceRange());
6496     } else {
6497       // CUDA: Calls to global functions must be configured
6498       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6499         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6500             << FDecl << Fn->getSourceRange());
6501     }
6502   }
6503 
6504   // Check for a valid return type
6505   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6506                           FDecl))
6507     return ExprError();
6508 
6509   // We know the result type of the call, set it.
6510   TheCall->setType(FuncT->getCallResultType(Context));
6511   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6512 
6513   if (Proto) {
6514     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6515                                 IsExecConfig))
6516       return ExprError();
6517   } else {
6518     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6519 
6520     if (FDecl) {
6521       // Check if we have too few/too many template arguments, based
6522       // on our knowledge of the function definition.
6523       const FunctionDecl *Def = nullptr;
6524       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6525         Proto = Def->getType()->getAs<FunctionProtoType>();
6526        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6527           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6528           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6529       }
6530 
6531       // If the function we're calling isn't a function prototype, but we have
6532       // a function prototype from a prior declaratiom, use that prototype.
6533       if (!FDecl->hasPrototype())
6534         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6535     }
6536 
6537     // Promote the arguments (C99 6.5.2.2p6).
6538     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6539       Expr *Arg = Args[i];
6540 
6541       if (Proto && i < Proto->getNumParams()) {
6542         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6543             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6544         ExprResult ArgE =
6545             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6546         if (ArgE.isInvalid())
6547           return true;
6548 
6549         Arg = ArgE.getAs<Expr>();
6550 
6551       } else {
6552         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6553 
6554         if (ArgE.isInvalid())
6555           return true;
6556 
6557         Arg = ArgE.getAs<Expr>();
6558       }
6559 
6560       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6561                               diag::err_call_incomplete_argument, Arg))
6562         return ExprError();
6563 
6564       TheCall->setArg(i, Arg);
6565     }
6566   }
6567 
6568   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6569     if (!Method->isStatic())
6570       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6571         << Fn->getSourceRange());
6572 
6573   // Check for sentinels
6574   if (NDecl)
6575     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6576 
6577   // Do special checking on direct calls to functions.
6578   if (FDecl) {
6579     if (CheckFunctionCall(FDecl, TheCall, Proto))
6580       return ExprError();
6581 
6582     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6583 
6584     if (BuiltinID)
6585       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6586   } else if (NDecl) {
6587     if (CheckPointerCall(NDecl, TheCall, Proto))
6588       return ExprError();
6589   } else {
6590     if (CheckOtherCall(TheCall, Proto))
6591       return ExprError();
6592   }
6593 
6594   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6595 }
6596 
6597 ExprResult
6598 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6599                            SourceLocation RParenLoc, Expr *InitExpr) {
6600   assert(Ty && "ActOnCompoundLiteral(): missing type");
6601   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6602 
6603   TypeSourceInfo *TInfo;
6604   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6605   if (!TInfo)
6606     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6607 
6608   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6609 }
6610 
6611 ExprResult
6612 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6613                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6614   QualType literalType = TInfo->getType();
6615 
6616   if (literalType->isArrayType()) {
6617     if (RequireCompleteSizedType(
6618             LParenLoc, Context.getBaseElementType(literalType),
6619             diag::err_array_incomplete_or_sizeless_type,
6620             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6621       return ExprError();
6622     if (literalType->isVariableArrayType())
6623       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6624         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6625   } else if (!literalType->isDependentType() &&
6626              RequireCompleteType(LParenLoc, literalType,
6627                diag::err_typecheck_decl_incomplete_type,
6628                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6629     return ExprError();
6630 
6631   InitializedEntity Entity
6632     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6633   InitializationKind Kind
6634     = InitializationKind::CreateCStyleCast(LParenLoc,
6635                                            SourceRange(LParenLoc, RParenLoc),
6636                                            /*InitList=*/true);
6637   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6638   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6639                                       &literalType);
6640   if (Result.isInvalid())
6641     return ExprError();
6642   LiteralExpr = Result.get();
6643 
6644   bool isFileScope = !CurContext->isFunctionOrMethod();
6645 
6646   // In C, compound literals are l-values for some reason.
6647   // For GCC compatibility, in C++, file-scope array compound literals with
6648   // constant initializers are also l-values, and compound literals are
6649   // otherwise prvalues.
6650   //
6651   // (GCC also treats C++ list-initialized file-scope array prvalues with
6652   // constant initializers as l-values, but that's non-conforming, so we don't
6653   // follow it there.)
6654   //
6655   // FIXME: It would be better to handle the lvalue cases as materializing and
6656   // lifetime-extending a temporary object, but our materialized temporaries
6657   // representation only supports lifetime extension from a variable, not "out
6658   // of thin air".
6659   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6660   // is bound to the result of applying array-to-pointer decay to the compound
6661   // literal.
6662   // FIXME: GCC supports compound literals of reference type, which should
6663   // obviously have a value kind derived from the kind of reference involved.
6664   ExprValueKind VK =
6665       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6666           ? VK_RValue
6667           : VK_LValue;
6668 
6669   if (isFileScope)
6670     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6671       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6672         Expr *Init = ILE->getInit(i);
6673         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6674       }
6675 
6676   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6677                                               VK, LiteralExpr, isFileScope);
6678   if (isFileScope) {
6679     if (!LiteralExpr->isTypeDependent() &&
6680         !LiteralExpr->isValueDependent() &&
6681         !literalType->isDependentType()) // C99 6.5.2.5p3
6682       if (CheckForConstantInitializer(LiteralExpr, literalType))
6683         return ExprError();
6684   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6685              literalType.getAddressSpace() != LangAS::Default) {
6686     // Embedded-C extensions to C99 6.5.2.5:
6687     //   "If the compound literal occurs inside the body of a function, the
6688     //   type name shall not be qualified by an address-space qualifier."
6689     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6690       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6691     return ExprError();
6692   }
6693 
6694   if (!isFileScope && !getLangOpts().CPlusPlus) {
6695     // Compound literals that have automatic storage duration are destroyed at
6696     // the end of the scope in C; in C++, they're just temporaries.
6697 
6698     // Emit diagnostics if it is or contains a C union type that is non-trivial
6699     // to destruct.
6700     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6701       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6702                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6703 
6704     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6705     if (literalType.isDestructedType()) {
6706       Cleanup.setExprNeedsCleanups(true);
6707       ExprCleanupObjects.push_back(E);
6708       getCurFunction()->setHasBranchProtectedScope();
6709     }
6710   }
6711 
6712   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6713       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6714     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6715                                        E->getInitializer()->getExprLoc());
6716 
6717   return MaybeBindToTemporary(E);
6718 }
6719 
6720 ExprResult
6721 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6722                     SourceLocation RBraceLoc) {
6723   // Only produce each kind of designated initialization diagnostic once.
6724   SourceLocation FirstDesignator;
6725   bool DiagnosedArrayDesignator = false;
6726   bool DiagnosedNestedDesignator = false;
6727   bool DiagnosedMixedDesignator = false;
6728 
6729   // Check that any designated initializers are syntactically valid in the
6730   // current language mode.
6731   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6732     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6733       if (FirstDesignator.isInvalid())
6734         FirstDesignator = DIE->getBeginLoc();
6735 
6736       if (!getLangOpts().CPlusPlus)
6737         break;
6738 
6739       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6740         DiagnosedNestedDesignator = true;
6741         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6742           << DIE->getDesignatorsSourceRange();
6743       }
6744 
6745       for (auto &Desig : DIE->designators()) {
6746         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6747           DiagnosedArrayDesignator = true;
6748           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6749             << Desig.getSourceRange();
6750         }
6751       }
6752 
6753       if (!DiagnosedMixedDesignator &&
6754           !isa<DesignatedInitExpr>(InitArgList[0])) {
6755         DiagnosedMixedDesignator = true;
6756         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6757           << DIE->getSourceRange();
6758         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6759           << InitArgList[0]->getSourceRange();
6760       }
6761     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6762                isa<DesignatedInitExpr>(InitArgList[0])) {
6763       DiagnosedMixedDesignator = true;
6764       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6765       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6766         << DIE->getSourceRange();
6767       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6768         << InitArgList[I]->getSourceRange();
6769     }
6770   }
6771 
6772   if (FirstDesignator.isValid()) {
6773     // Only diagnose designated initiaization as a C++20 extension if we didn't
6774     // already diagnose use of (non-C++20) C99 designator syntax.
6775     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6776         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6777       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6778                                 ? diag::warn_cxx17_compat_designated_init
6779                                 : diag::ext_cxx_designated_init);
6780     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6781       Diag(FirstDesignator, diag::ext_designated_init);
6782     }
6783   }
6784 
6785   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6786 }
6787 
6788 ExprResult
6789 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6790                     SourceLocation RBraceLoc) {
6791   // Semantic analysis for initializers is done by ActOnDeclarator() and
6792   // CheckInitializer() - it requires knowledge of the object being initialized.
6793 
6794   // Immediately handle non-overload placeholders.  Overloads can be
6795   // resolved contextually, but everything else here can't.
6796   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6797     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6798       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6799 
6800       // Ignore failures; dropping the entire initializer list because
6801       // of one failure would be terrible for indexing/etc.
6802       if (result.isInvalid()) continue;
6803 
6804       InitArgList[I] = result.get();
6805     }
6806   }
6807 
6808   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6809                                                RBraceLoc);
6810   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6811   return E;
6812 }
6813 
6814 /// Do an explicit extend of the given block pointer if we're in ARC.
6815 void Sema::maybeExtendBlockObject(ExprResult &E) {
6816   assert(E.get()->getType()->isBlockPointerType());
6817   assert(E.get()->isRValue());
6818 
6819   // Only do this in an r-value context.
6820   if (!getLangOpts().ObjCAutoRefCount) return;
6821 
6822   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6823                                CK_ARCExtendBlockObject, E.get(),
6824                                /*base path*/ nullptr, VK_RValue);
6825   Cleanup.setExprNeedsCleanups(true);
6826 }
6827 
6828 /// Prepare a conversion of the given expression to an ObjC object
6829 /// pointer type.
6830 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6831   QualType type = E.get()->getType();
6832   if (type->isObjCObjectPointerType()) {
6833     return CK_BitCast;
6834   } else if (type->isBlockPointerType()) {
6835     maybeExtendBlockObject(E);
6836     return CK_BlockPointerToObjCPointerCast;
6837   } else {
6838     assert(type->isPointerType());
6839     return CK_CPointerToObjCPointerCast;
6840   }
6841 }
6842 
6843 /// Prepares for a scalar cast, performing all the necessary stages
6844 /// except the final cast and returning the kind required.
6845 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6846   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6847   // Also, callers should have filtered out the invalid cases with
6848   // pointers.  Everything else should be possible.
6849 
6850   QualType SrcTy = Src.get()->getType();
6851   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6852     return CK_NoOp;
6853 
6854   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6855   case Type::STK_MemberPointer:
6856     llvm_unreachable("member pointer type in C");
6857 
6858   case Type::STK_CPointer:
6859   case Type::STK_BlockPointer:
6860   case Type::STK_ObjCObjectPointer:
6861     switch (DestTy->getScalarTypeKind()) {
6862     case Type::STK_CPointer: {
6863       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6864       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6865       if (SrcAS != DestAS)
6866         return CK_AddressSpaceConversion;
6867       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6868         return CK_NoOp;
6869       return CK_BitCast;
6870     }
6871     case Type::STK_BlockPointer:
6872       return (SrcKind == Type::STK_BlockPointer
6873                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6874     case Type::STK_ObjCObjectPointer:
6875       if (SrcKind == Type::STK_ObjCObjectPointer)
6876         return CK_BitCast;
6877       if (SrcKind == Type::STK_CPointer)
6878         return CK_CPointerToObjCPointerCast;
6879       maybeExtendBlockObject(Src);
6880       return CK_BlockPointerToObjCPointerCast;
6881     case Type::STK_Bool:
6882       return CK_PointerToBoolean;
6883     case Type::STK_Integral:
6884       return CK_PointerToIntegral;
6885     case Type::STK_Floating:
6886     case Type::STK_FloatingComplex:
6887     case Type::STK_IntegralComplex:
6888     case Type::STK_MemberPointer:
6889     case Type::STK_FixedPoint:
6890       llvm_unreachable("illegal cast from pointer");
6891     }
6892     llvm_unreachable("Should have returned before this");
6893 
6894   case Type::STK_FixedPoint:
6895     switch (DestTy->getScalarTypeKind()) {
6896     case Type::STK_FixedPoint:
6897       return CK_FixedPointCast;
6898     case Type::STK_Bool:
6899       return CK_FixedPointToBoolean;
6900     case Type::STK_Integral:
6901       return CK_FixedPointToIntegral;
6902     case Type::STK_Floating:
6903     case Type::STK_IntegralComplex:
6904     case Type::STK_FloatingComplex:
6905       Diag(Src.get()->getExprLoc(),
6906            diag::err_unimplemented_conversion_with_fixed_point_type)
6907           << DestTy;
6908       return CK_IntegralCast;
6909     case Type::STK_CPointer:
6910     case Type::STK_ObjCObjectPointer:
6911     case Type::STK_BlockPointer:
6912     case Type::STK_MemberPointer:
6913       llvm_unreachable("illegal cast to pointer type");
6914     }
6915     llvm_unreachable("Should have returned before this");
6916 
6917   case Type::STK_Bool: // casting from bool is like casting from an integer
6918   case Type::STK_Integral:
6919     switch (DestTy->getScalarTypeKind()) {
6920     case Type::STK_CPointer:
6921     case Type::STK_ObjCObjectPointer:
6922     case Type::STK_BlockPointer:
6923       if (Src.get()->isNullPointerConstant(Context,
6924                                            Expr::NPC_ValueDependentIsNull))
6925         return CK_NullToPointer;
6926       return CK_IntegralToPointer;
6927     case Type::STK_Bool:
6928       return CK_IntegralToBoolean;
6929     case Type::STK_Integral:
6930       return CK_IntegralCast;
6931     case Type::STK_Floating:
6932       return CK_IntegralToFloating;
6933     case Type::STK_IntegralComplex:
6934       Src = ImpCastExprToType(Src.get(),
6935                       DestTy->castAs<ComplexType>()->getElementType(),
6936                       CK_IntegralCast);
6937       return CK_IntegralRealToComplex;
6938     case Type::STK_FloatingComplex:
6939       Src = ImpCastExprToType(Src.get(),
6940                       DestTy->castAs<ComplexType>()->getElementType(),
6941                       CK_IntegralToFloating);
6942       return CK_FloatingRealToComplex;
6943     case Type::STK_MemberPointer:
6944       llvm_unreachable("member pointer type in C");
6945     case Type::STK_FixedPoint:
6946       return CK_IntegralToFixedPoint;
6947     }
6948     llvm_unreachable("Should have returned before this");
6949 
6950   case Type::STK_Floating:
6951     switch (DestTy->getScalarTypeKind()) {
6952     case Type::STK_Floating:
6953       return CK_FloatingCast;
6954     case Type::STK_Bool:
6955       return CK_FloatingToBoolean;
6956     case Type::STK_Integral:
6957       return CK_FloatingToIntegral;
6958     case Type::STK_FloatingComplex:
6959       Src = ImpCastExprToType(Src.get(),
6960                               DestTy->castAs<ComplexType>()->getElementType(),
6961                               CK_FloatingCast);
6962       return CK_FloatingRealToComplex;
6963     case Type::STK_IntegralComplex:
6964       Src = ImpCastExprToType(Src.get(),
6965                               DestTy->castAs<ComplexType>()->getElementType(),
6966                               CK_FloatingToIntegral);
6967       return CK_IntegralRealToComplex;
6968     case Type::STK_CPointer:
6969     case Type::STK_ObjCObjectPointer:
6970     case Type::STK_BlockPointer:
6971       llvm_unreachable("valid float->pointer cast?");
6972     case Type::STK_MemberPointer:
6973       llvm_unreachable("member pointer type in C");
6974     case Type::STK_FixedPoint:
6975       Diag(Src.get()->getExprLoc(),
6976            diag::err_unimplemented_conversion_with_fixed_point_type)
6977           << SrcTy;
6978       return CK_IntegralCast;
6979     }
6980     llvm_unreachable("Should have returned before this");
6981 
6982   case Type::STK_FloatingComplex:
6983     switch (DestTy->getScalarTypeKind()) {
6984     case Type::STK_FloatingComplex:
6985       return CK_FloatingComplexCast;
6986     case Type::STK_IntegralComplex:
6987       return CK_FloatingComplexToIntegralComplex;
6988     case Type::STK_Floating: {
6989       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6990       if (Context.hasSameType(ET, DestTy))
6991         return CK_FloatingComplexToReal;
6992       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6993       return CK_FloatingCast;
6994     }
6995     case Type::STK_Bool:
6996       return CK_FloatingComplexToBoolean;
6997     case Type::STK_Integral:
6998       Src = ImpCastExprToType(Src.get(),
6999                               SrcTy->castAs<ComplexType>()->getElementType(),
7000                               CK_FloatingComplexToReal);
7001       return CK_FloatingToIntegral;
7002     case Type::STK_CPointer:
7003     case Type::STK_ObjCObjectPointer:
7004     case Type::STK_BlockPointer:
7005       llvm_unreachable("valid complex float->pointer cast?");
7006     case Type::STK_MemberPointer:
7007       llvm_unreachable("member pointer type in C");
7008     case Type::STK_FixedPoint:
7009       Diag(Src.get()->getExprLoc(),
7010            diag::err_unimplemented_conversion_with_fixed_point_type)
7011           << SrcTy;
7012       return CK_IntegralCast;
7013     }
7014     llvm_unreachable("Should have returned before this");
7015 
7016   case Type::STK_IntegralComplex:
7017     switch (DestTy->getScalarTypeKind()) {
7018     case Type::STK_FloatingComplex:
7019       return CK_IntegralComplexToFloatingComplex;
7020     case Type::STK_IntegralComplex:
7021       return CK_IntegralComplexCast;
7022     case Type::STK_Integral: {
7023       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7024       if (Context.hasSameType(ET, DestTy))
7025         return CK_IntegralComplexToReal;
7026       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7027       return CK_IntegralCast;
7028     }
7029     case Type::STK_Bool:
7030       return CK_IntegralComplexToBoolean;
7031     case Type::STK_Floating:
7032       Src = ImpCastExprToType(Src.get(),
7033                               SrcTy->castAs<ComplexType>()->getElementType(),
7034                               CK_IntegralComplexToReal);
7035       return CK_IntegralToFloating;
7036     case Type::STK_CPointer:
7037     case Type::STK_ObjCObjectPointer:
7038     case Type::STK_BlockPointer:
7039       llvm_unreachable("valid complex int->pointer cast?");
7040     case Type::STK_MemberPointer:
7041       llvm_unreachable("member pointer type in C");
7042     case Type::STK_FixedPoint:
7043       Diag(Src.get()->getExprLoc(),
7044            diag::err_unimplemented_conversion_with_fixed_point_type)
7045           << SrcTy;
7046       return CK_IntegralCast;
7047     }
7048     llvm_unreachable("Should have returned before this");
7049   }
7050 
7051   llvm_unreachable("Unhandled scalar cast");
7052 }
7053 
7054 static bool breakDownVectorType(QualType type, uint64_t &len,
7055                                 QualType &eltType) {
7056   // Vectors are simple.
7057   if (const VectorType *vecType = type->getAs<VectorType>()) {
7058     len = vecType->getNumElements();
7059     eltType = vecType->getElementType();
7060     assert(eltType->isScalarType());
7061     return true;
7062   }
7063 
7064   // We allow lax conversion to and from non-vector types, but only if
7065   // they're real types (i.e. non-complex, non-pointer scalar types).
7066   if (!type->isRealType()) return false;
7067 
7068   len = 1;
7069   eltType = type;
7070   return true;
7071 }
7072 
7073 /// Are the two types lax-compatible vector types?  That is, given
7074 /// that one of them is a vector, do they have equal storage sizes,
7075 /// where the storage size is the number of elements times the element
7076 /// size?
7077 ///
7078 /// This will also return false if either of the types is neither a
7079 /// vector nor a real type.
7080 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7081   assert(destTy->isVectorType() || srcTy->isVectorType());
7082 
7083   // Disallow lax conversions between scalars and ExtVectors (these
7084   // conversions are allowed for other vector types because common headers
7085   // depend on them).  Most scalar OP ExtVector cases are handled by the
7086   // splat path anyway, which does what we want (convert, not bitcast).
7087   // What this rules out for ExtVectors is crazy things like char4*float.
7088   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7089   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7090 
7091   uint64_t srcLen, destLen;
7092   QualType srcEltTy, destEltTy;
7093   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7094   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7095 
7096   // ASTContext::getTypeSize will return the size rounded up to a
7097   // power of 2, so instead of using that, we need to use the raw
7098   // element size multiplied by the element count.
7099   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7100   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7101 
7102   return (srcLen * srcEltSize == destLen * destEltSize);
7103 }
7104 
7105 /// Is this a legal conversion between two types, one of which is
7106 /// known to be a vector type?
7107 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7108   assert(destTy->isVectorType() || srcTy->isVectorType());
7109 
7110   switch (Context.getLangOpts().getLaxVectorConversions()) {
7111   case LangOptions::LaxVectorConversionKind::None:
7112     return false;
7113 
7114   case LangOptions::LaxVectorConversionKind::Integer:
7115     if (!srcTy->isIntegralOrEnumerationType()) {
7116       auto *Vec = srcTy->getAs<VectorType>();
7117       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7118         return false;
7119     }
7120     if (!destTy->isIntegralOrEnumerationType()) {
7121       auto *Vec = destTy->getAs<VectorType>();
7122       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7123         return false;
7124     }
7125     // OK, integer (vector) -> integer (vector) bitcast.
7126     break;
7127 
7128     case LangOptions::LaxVectorConversionKind::All:
7129     break;
7130   }
7131 
7132   return areLaxCompatibleVectorTypes(srcTy, destTy);
7133 }
7134 
7135 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7136                            CastKind &Kind) {
7137   assert(VectorTy->isVectorType() && "Not a vector type!");
7138 
7139   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7140     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7141       return Diag(R.getBegin(),
7142                   Ty->isVectorType() ?
7143                   diag::err_invalid_conversion_between_vectors :
7144                   diag::err_invalid_conversion_between_vector_and_integer)
7145         << VectorTy << Ty << R;
7146   } else
7147     return Diag(R.getBegin(),
7148                 diag::err_invalid_conversion_between_vector_and_scalar)
7149       << VectorTy << Ty << R;
7150 
7151   Kind = CK_BitCast;
7152   return false;
7153 }
7154 
7155 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7156   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7157 
7158   if (DestElemTy == SplattedExpr->getType())
7159     return SplattedExpr;
7160 
7161   assert(DestElemTy->isFloatingType() ||
7162          DestElemTy->isIntegralOrEnumerationType());
7163 
7164   CastKind CK;
7165   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7166     // OpenCL requires that we convert `true` boolean expressions to -1, but
7167     // only when splatting vectors.
7168     if (DestElemTy->isFloatingType()) {
7169       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7170       // in two steps: boolean to signed integral, then to floating.
7171       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7172                                                  CK_BooleanToSignedIntegral);
7173       SplattedExpr = CastExprRes.get();
7174       CK = CK_IntegralToFloating;
7175     } else {
7176       CK = CK_BooleanToSignedIntegral;
7177     }
7178   } else {
7179     ExprResult CastExprRes = SplattedExpr;
7180     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7181     if (CastExprRes.isInvalid())
7182       return ExprError();
7183     SplattedExpr = CastExprRes.get();
7184   }
7185   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7186 }
7187 
7188 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7189                                     Expr *CastExpr, CastKind &Kind) {
7190   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7191 
7192   QualType SrcTy = CastExpr->getType();
7193 
7194   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7195   // an ExtVectorType.
7196   // In OpenCL, casts between vectors of different types are not allowed.
7197   // (See OpenCL 6.2).
7198   if (SrcTy->isVectorType()) {
7199     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7200         (getLangOpts().OpenCL &&
7201          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7202       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7203         << DestTy << SrcTy << R;
7204       return ExprError();
7205     }
7206     Kind = CK_BitCast;
7207     return CastExpr;
7208   }
7209 
7210   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7211   // conversion will take place first from scalar to elt type, and then
7212   // splat from elt type to vector.
7213   if (SrcTy->isPointerType())
7214     return Diag(R.getBegin(),
7215                 diag::err_invalid_conversion_between_vector_and_scalar)
7216       << DestTy << SrcTy << R;
7217 
7218   Kind = CK_VectorSplat;
7219   return prepareVectorSplat(DestTy, CastExpr);
7220 }
7221 
7222 ExprResult
7223 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7224                     Declarator &D, ParsedType &Ty,
7225                     SourceLocation RParenLoc, Expr *CastExpr) {
7226   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7227          "ActOnCastExpr(): missing type or expr");
7228 
7229   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7230   if (D.isInvalidType())
7231     return ExprError();
7232 
7233   if (getLangOpts().CPlusPlus) {
7234     // Check that there are no default arguments (C++ only).
7235     CheckExtraCXXDefaultArguments(D);
7236   } else {
7237     // Make sure any TypoExprs have been dealt with.
7238     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7239     if (!Res.isUsable())
7240       return ExprError();
7241     CastExpr = Res.get();
7242   }
7243 
7244   checkUnusedDeclAttributes(D);
7245 
7246   QualType castType = castTInfo->getType();
7247   Ty = CreateParsedType(castType, castTInfo);
7248 
7249   bool isVectorLiteral = false;
7250 
7251   // Check for an altivec or OpenCL literal,
7252   // i.e. all the elements are integer constants.
7253   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7254   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7255   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7256        && castType->isVectorType() && (PE || PLE)) {
7257     if (PLE && PLE->getNumExprs() == 0) {
7258       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7259       return ExprError();
7260     }
7261     if (PE || PLE->getNumExprs() == 1) {
7262       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7263       if (!E->getType()->isVectorType())
7264         isVectorLiteral = true;
7265     }
7266     else
7267       isVectorLiteral = true;
7268   }
7269 
7270   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7271   // then handle it as such.
7272   if (isVectorLiteral)
7273     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7274 
7275   // If the Expr being casted is a ParenListExpr, handle it specially.
7276   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7277   // sequence of BinOp comma operators.
7278   if (isa<ParenListExpr>(CastExpr)) {
7279     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7280     if (Result.isInvalid()) return ExprError();
7281     CastExpr = Result.get();
7282   }
7283 
7284   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7285       !getSourceManager().isInSystemMacro(LParenLoc))
7286     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7287 
7288   CheckTollFreeBridgeCast(castType, CastExpr);
7289 
7290   CheckObjCBridgeRelatedCast(castType, CastExpr);
7291 
7292   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7293 
7294   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7295 }
7296 
7297 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7298                                     SourceLocation RParenLoc, Expr *E,
7299                                     TypeSourceInfo *TInfo) {
7300   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7301          "Expected paren or paren list expression");
7302 
7303   Expr **exprs;
7304   unsigned numExprs;
7305   Expr *subExpr;
7306   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7307   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7308     LiteralLParenLoc = PE->getLParenLoc();
7309     LiteralRParenLoc = PE->getRParenLoc();
7310     exprs = PE->getExprs();
7311     numExprs = PE->getNumExprs();
7312   } else { // isa<ParenExpr> by assertion at function entrance
7313     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7314     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7315     subExpr = cast<ParenExpr>(E)->getSubExpr();
7316     exprs = &subExpr;
7317     numExprs = 1;
7318   }
7319 
7320   QualType Ty = TInfo->getType();
7321   assert(Ty->isVectorType() && "Expected vector type");
7322 
7323   SmallVector<Expr *, 8> initExprs;
7324   const VectorType *VTy = Ty->castAs<VectorType>();
7325   unsigned numElems = VTy->getNumElements();
7326 
7327   // '(...)' form of vector initialization in AltiVec: the number of
7328   // initializers must be one or must match the size of the vector.
7329   // If a single value is specified in the initializer then it will be
7330   // replicated to all the components of the vector
7331   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7332     // The number of initializers must be one or must match the size of the
7333     // vector. If a single value is specified in the initializer then it will
7334     // be replicated to all the components of the vector
7335     if (numExprs == 1) {
7336       QualType ElemTy = VTy->getElementType();
7337       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7338       if (Literal.isInvalid())
7339         return ExprError();
7340       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7341                                   PrepareScalarCast(Literal, ElemTy));
7342       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7343     }
7344     else if (numExprs < numElems) {
7345       Diag(E->getExprLoc(),
7346            diag::err_incorrect_number_of_vector_initializers);
7347       return ExprError();
7348     }
7349     else
7350       initExprs.append(exprs, exprs + numExprs);
7351   }
7352   else {
7353     // For OpenCL, when the number of initializers is a single value,
7354     // it will be replicated to all components of the vector.
7355     if (getLangOpts().OpenCL &&
7356         VTy->getVectorKind() == VectorType::GenericVector &&
7357         numExprs == 1) {
7358         QualType ElemTy = VTy->getElementType();
7359         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7360         if (Literal.isInvalid())
7361           return ExprError();
7362         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7363                                     PrepareScalarCast(Literal, ElemTy));
7364         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7365     }
7366 
7367     initExprs.append(exprs, exprs + numExprs);
7368   }
7369   // FIXME: This means that pretty-printing the final AST will produce curly
7370   // braces instead of the original commas.
7371   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7372                                                    initExprs, LiteralRParenLoc);
7373   initE->setType(Ty);
7374   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7375 }
7376 
7377 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7378 /// the ParenListExpr into a sequence of comma binary operators.
7379 ExprResult
7380 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7381   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7382   if (!E)
7383     return OrigExpr;
7384 
7385   ExprResult Result(E->getExpr(0));
7386 
7387   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7388     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7389                         E->getExpr(i));
7390 
7391   if (Result.isInvalid()) return ExprError();
7392 
7393   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7394 }
7395 
7396 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7397                                     SourceLocation R,
7398                                     MultiExprArg Val) {
7399   return ParenListExpr::Create(Context, L, Val, R);
7400 }
7401 
7402 /// Emit a specialized diagnostic when one expression is a null pointer
7403 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7404 /// emitted.
7405 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7406                                       SourceLocation QuestionLoc) {
7407   Expr *NullExpr = LHSExpr;
7408   Expr *NonPointerExpr = RHSExpr;
7409   Expr::NullPointerConstantKind NullKind =
7410       NullExpr->isNullPointerConstant(Context,
7411                                       Expr::NPC_ValueDependentIsNotNull);
7412 
7413   if (NullKind == Expr::NPCK_NotNull) {
7414     NullExpr = RHSExpr;
7415     NonPointerExpr = LHSExpr;
7416     NullKind =
7417         NullExpr->isNullPointerConstant(Context,
7418                                         Expr::NPC_ValueDependentIsNotNull);
7419   }
7420 
7421   if (NullKind == Expr::NPCK_NotNull)
7422     return false;
7423 
7424   if (NullKind == Expr::NPCK_ZeroExpression)
7425     return false;
7426 
7427   if (NullKind == Expr::NPCK_ZeroLiteral) {
7428     // In this case, check to make sure that we got here from a "NULL"
7429     // string in the source code.
7430     NullExpr = NullExpr->IgnoreParenImpCasts();
7431     SourceLocation loc = NullExpr->getExprLoc();
7432     if (!findMacroSpelling(loc, "NULL"))
7433       return false;
7434   }
7435 
7436   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7437   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7438       << NonPointerExpr->getType() << DiagType
7439       << NonPointerExpr->getSourceRange();
7440   return true;
7441 }
7442 
7443 /// Return false if the condition expression is valid, true otherwise.
7444 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7445   QualType CondTy = Cond->getType();
7446 
7447   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7448   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7449     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7450       << CondTy << Cond->getSourceRange();
7451     return true;
7452   }
7453 
7454   // C99 6.5.15p2
7455   if (CondTy->isScalarType()) return false;
7456 
7457   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7458     << CondTy << Cond->getSourceRange();
7459   return true;
7460 }
7461 
7462 /// Handle when one or both operands are void type.
7463 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7464                                          ExprResult &RHS) {
7465     Expr *LHSExpr = LHS.get();
7466     Expr *RHSExpr = RHS.get();
7467 
7468     if (!LHSExpr->getType()->isVoidType())
7469       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7470           << RHSExpr->getSourceRange();
7471     if (!RHSExpr->getType()->isVoidType())
7472       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7473           << LHSExpr->getSourceRange();
7474     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7475     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7476     return S.Context.VoidTy;
7477 }
7478 
7479 /// Return false if the NullExpr can be promoted to PointerTy,
7480 /// true otherwise.
7481 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7482                                         QualType PointerTy) {
7483   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7484       !NullExpr.get()->isNullPointerConstant(S.Context,
7485                                             Expr::NPC_ValueDependentIsNull))
7486     return true;
7487 
7488   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7489   return false;
7490 }
7491 
7492 /// Checks compatibility between two pointers and return the resulting
7493 /// type.
7494 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7495                                                      ExprResult &RHS,
7496                                                      SourceLocation Loc) {
7497   QualType LHSTy = LHS.get()->getType();
7498   QualType RHSTy = RHS.get()->getType();
7499 
7500   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7501     // Two identical pointers types are always compatible.
7502     return LHSTy;
7503   }
7504 
7505   QualType lhptee, rhptee;
7506 
7507   // Get the pointee types.
7508   bool IsBlockPointer = false;
7509   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7510     lhptee = LHSBTy->getPointeeType();
7511     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7512     IsBlockPointer = true;
7513   } else {
7514     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7515     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7516   }
7517 
7518   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7519   // differently qualified versions of compatible types, the result type is
7520   // a pointer to an appropriately qualified version of the composite
7521   // type.
7522 
7523   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7524   // clause doesn't make sense for our extensions. E.g. address space 2 should
7525   // be incompatible with address space 3: they may live on different devices or
7526   // anything.
7527   Qualifiers lhQual = lhptee.getQualifiers();
7528   Qualifiers rhQual = rhptee.getQualifiers();
7529 
7530   LangAS ResultAddrSpace = LangAS::Default;
7531   LangAS LAddrSpace = lhQual.getAddressSpace();
7532   LangAS RAddrSpace = rhQual.getAddressSpace();
7533 
7534   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7535   // spaces is disallowed.
7536   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7537     ResultAddrSpace = LAddrSpace;
7538   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7539     ResultAddrSpace = RAddrSpace;
7540   else {
7541     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7542         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7543         << RHS.get()->getSourceRange();
7544     return QualType();
7545   }
7546 
7547   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7548   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7549   lhQual.removeCVRQualifiers();
7550   rhQual.removeCVRQualifiers();
7551 
7552   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7553   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7554   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7555   // qual types are compatible iff
7556   //  * corresponded types are compatible
7557   //  * CVR qualifiers are equal
7558   //  * address spaces are equal
7559   // Thus for conditional operator we merge CVR and address space unqualified
7560   // pointees and if there is a composite type we return a pointer to it with
7561   // merged qualifiers.
7562   LHSCastKind =
7563       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7564   RHSCastKind =
7565       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7566   lhQual.removeAddressSpace();
7567   rhQual.removeAddressSpace();
7568 
7569   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7570   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7571 
7572   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7573 
7574   if (CompositeTy.isNull()) {
7575     // In this situation, we assume void* type. No especially good
7576     // reason, but this is what gcc does, and we do have to pick
7577     // to get a consistent AST.
7578     QualType incompatTy;
7579     incompatTy = S.Context.getPointerType(
7580         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7581     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7582     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7583 
7584     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7585     // for casts between types with incompatible address space qualifiers.
7586     // For the following code the compiler produces casts between global and
7587     // local address spaces of the corresponded innermost pointees:
7588     // local int *global *a;
7589     // global int *global *b;
7590     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7591     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7592         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7593         << RHS.get()->getSourceRange();
7594 
7595     return incompatTy;
7596   }
7597 
7598   // The pointer types are compatible.
7599   // In case of OpenCL ResultTy should have the address space qualifier
7600   // which is a superset of address spaces of both the 2nd and the 3rd
7601   // operands of the conditional operator.
7602   QualType ResultTy = [&, ResultAddrSpace]() {
7603     if (S.getLangOpts().OpenCL) {
7604       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7605       CompositeQuals.setAddressSpace(ResultAddrSpace);
7606       return S.Context
7607           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7608           .withCVRQualifiers(MergedCVRQual);
7609     }
7610     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7611   }();
7612   if (IsBlockPointer)
7613     ResultTy = S.Context.getBlockPointerType(ResultTy);
7614   else
7615     ResultTy = S.Context.getPointerType(ResultTy);
7616 
7617   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7618   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7619   return ResultTy;
7620 }
7621 
7622 /// Return the resulting type when the operands are both block pointers.
7623 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7624                                                           ExprResult &LHS,
7625                                                           ExprResult &RHS,
7626                                                           SourceLocation Loc) {
7627   QualType LHSTy = LHS.get()->getType();
7628   QualType RHSTy = RHS.get()->getType();
7629 
7630   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7631     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7632       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7633       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7634       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7635       return destType;
7636     }
7637     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7638       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7639       << RHS.get()->getSourceRange();
7640     return QualType();
7641   }
7642 
7643   // We have 2 block pointer types.
7644   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7645 }
7646 
7647 /// Return the resulting type when the operands are both pointers.
7648 static QualType
7649 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7650                                             ExprResult &RHS,
7651                                             SourceLocation Loc) {
7652   // get the pointer types
7653   QualType LHSTy = LHS.get()->getType();
7654   QualType RHSTy = RHS.get()->getType();
7655 
7656   // get the "pointed to" types
7657   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7658   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7659 
7660   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7661   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7662     // Figure out necessary qualifiers (C99 6.5.15p6)
7663     QualType destPointee
7664       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7665     QualType destType = S.Context.getPointerType(destPointee);
7666     // Add qualifiers if necessary.
7667     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7668     // Promote to void*.
7669     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7670     return destType;
7671   }
7672   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7673     QualType destPointee
7674       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7675     QualType destType = S.Context.getPointerType(destPointee);
7676     // Add qualifiers if necessary.
7677     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7678     // Promote to void*.
7679     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7680     return destType;
7681   }
7682 
7683   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7684 }
7685 
7686 /// Return false if the first expression is not an integer and the second
7687 /// expression is not a pointer, true otherwise.
7688 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7689                                         Expr* PointerExpr, SourceLocation Loc,
7690                                         bool IsIntFirstExpr) {
7691   if (!PointerExpr->getType()->isPointerType() ||
7692       !Int.get()->getType()->isIntegerType())
7693     return false;
7694 
7695   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7696   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7697 
7698   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7699     << Expr1->getType() << Expr2->getType()
7700     << Expr1->getSourceRange() << Expr2->getSourceRange();
7701   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7702                             CK_IntegralToPointer);
7703   return true;
7704 }
7705 
7706 /// Simple conversion between integer and floating point types.
7707 ///
7708 /// Used when handling the OpenCL conditional operator where the
7709 /// condition is a vector while the other operands are scalar.
7710 ///
7711 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7712 /// types are either integer or floating type. Between the two
7713 /// operands, the type with the higher rank is defined as the "result
7714 /// type". The other operand needs to be promoted to the same type. No
7715 /// other type promotion is allowed. We cannot use
7716 /// UsualArithmeticConversions() for this purpose, since it always
7717 /// promotes promotable types.
7718 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7719                                             ExprResult &RHS,
7720                                             SourceLocation QuestionLoc) {
7721   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7722   if (LHS.isInvalid())
7723     return QualType();
7724   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7725   if (RHS.isInvalid())
7726     return QualType();
7727 
7728   // For conversion purposes, we ignore any qualifiers.
7729   // For example, "const float" and "float" are equivalent.
7730   QualType LHSType =
7731     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7732   QualType RHSType =
7733     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7734 
7735   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7736     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7737       << LHSType << LHS.get()->getSourceRange();
7738     return QualType();
7739   }
7740 
7741   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7742     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7743       << RHSType << RHS.get()->getSourceRange();
7744     return QualType();
7745   }
7746 
7747   // If both types are identical, no conversion is needed.
7748   if (LHSType == RHSType)
7749     return LHSType;
7750 
7751   // Now handle "real" floating types (i.e. float, double, long double).
7752   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7753     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7754                                  /*IsCompAssign = */ false);
7755 
7756   // Finally, we have two differing integer types.
7757   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7758   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7759 }
7760 
7761 /// Convert scalar operands to a vector that matches the
7762 ///        condition in length.
7763 ///
7764 /// Used when handling the OpenCL conditional operator where the
7765 /// condition is a vector while the other operands are scalar.
7766 ///
7767 /// We first compute the "result type" for the scalar operands
7768 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7769 /// into a vector of that type where the length matches the condition
7770 /// vector type. s6.11.6 requires that the element types of the result
7771 /// and the condition must have the same number of bits.
7772 static QualType
7773 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7774                               QualType CondTy, SourceLocation QuestionLoc) {
7775   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7776   if (ResTy.isNull()) return QualType();
7777 
7778   const VectorType *CV = CondTy->getAs<VectorType>();
7779   assert(CV);
7780 
7781   // Determine the vector result type
7782   unsigned NumElements = CV->getNumElements();
7783   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7784 
7785   // Ensure that all types have the same number of bits
7786   if (S.Context.getTypeSize(CV->getElementType())
7787       != S.Context.getTypeSize(ResTy)) {
7788     // Since VectorTy is created internally, it does not pretty print
7789     // with an OpenCL name. Instead, we just print a description.
7790     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7791     SmallString<64> Str;
7792     llvm::raw_svector_ostream OS(Str);
7793     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7794     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7795       << CondTy << OS.str();
7796     return QualType();
7797   }
7798 
7799   // Convert operands to the vector result type
7800   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7801   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7802 
7803   return VectorTy;
7804 }
7805 
7806 /// Return false if this is a valid OpenCL condition vector
7807 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7808                                        SourceLocation QuestionLoc) {
7809   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7810   // integral type.
7811   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7812   assert(CondTy);
7813   QualType EleTy = CondTy->getElementType();
7814   if (EleTy->isIntegerType()) return false;
7815 
7816   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7817     << Cond->getType() << Cond->getSourceRange();
7818   return true;
7819 }
7820 
7821 /// Return false if the vector condition type and the vector
7822 ///        result type are compatible.
7823 ///
7824 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7825 /// number of elements, and their element types have the same number
7826 /// of bits.
7827 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7828                               SourceLocation QuestionLoc) {
7829   const VectorType *CV = CondTy->getAs<VectorType>();
7830   const VectorType *RV = VecResTy->getAs<VectorType>();
7831   assert(CV && RV);
7832 
7833   if (CV->getNumElements() != RV->getNumElements()) {
7834     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7835       << CondTy << VecResTy;
7836     return true;
7837   }
7838 
7839   QualType CVE = CV->getElementType();
7840   QualType RVE = RV->getElementType();
7841 
7842   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7843     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7844       << CondTy << VecResTy;
7845     return true;
7846   }
7847 
7848   return false;
7849 }
7850 
7851 /// Return the resulting type for the conditional operator in
7852 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7853 ///        s6.3.i) when the condition is a vector type.
7854 static QualType
7855 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7856                              ExprResult &LHS, ExprResult &RHS,
7857                              SourceLocation QuestionLoc) {
7858   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7859   if (Cond.isInvalid())
7860     return QualType();
7861   QualType CondTy = Cond.get()->getType();
7862 
7863   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7864     return QualType();
7865 
7866   // If either operand is a vector then find the vector type of the
7867   // result as specified in OpenCL v1.1 s6.3.i.
7868   if (LHS.get()->getType()->isVectorType() ||
7869       RHS.get()->getType()->isVectorType()) {
7870     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7871                                               /*isCompAssign*/false,
7872                                               /*AllowBothBool*/true,
7873                                               /*AllowBoolConversions*/false);
7874     if (VecResTy.isNull()) return QualType();
7875     // The result type must match the condition type as specified in
7876     // OpenCL v1.1 s6.11.6.
7877     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7878       return QualType();
7879     return VecResTy;
7880   }
7881 
7882   // Both operands are scalar.
7883   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7884 }
7885 
7886 /// Return true if the Expr is block type
7887 static bool checkBlockType(Sema &S, const Expr *E) {
7888   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7889     QualType Ty = CE->getCallee()->getType();
7890     if (Ty->isBlockPointerType()) {
7891       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7892       return true;
7893     }
7894   }
7895   return false;
7896 }
7897 
7898 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7899 /// In that case, LHS = cond.
7900 /// C99 6.5.15
7901 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7902                                         ExprResult &RHS, ExprValueKind &VK,
7903                                         ExprObjectKind &OK,
7904                                         SourceLocation QuestionLoc) {
7905 
7906   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7907   if (!LHSResult.isUsable()) return QualType();
7908   LHS = LHSResult;
7909 
7910   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7911   if (!RHSResult.isUsable()) return QualType();
7912   RHS = RHSResult;
7913 
7914   // C++ is sufficiently different to merit its own checker.
7915   if (getLangOpts().CPlusPlus)
7916     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7917 
7918   VK = VK_RValue;
7919   OK = OK_Ordinary;
7920 
7921   // The OpenCL operator with a vector condition is sufficiently
7922   // different to merit its own checker.
7923   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7924     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7925 
7926   // First, check the condition.
7927   Cond = UsualUnaryConversions(Cond.get());
7928   if (Cond.isInvalid())
7929     return QualType();
7930   if (checkCondition(*this, Cond.get(), QuestionLoc))
7931     return QualType();
7932 
7933   // Now check the two expressions.
7934   if (LHS.get()->getType()->isVectorType() ||
7935       RHS.get()->getType()->isVectorType())
7936     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7937                                /*AllowBothBool*/true,
7938                                /*AllowBoolConversions*/false);
7939 
7940   QualType ResTy =
7941       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7942   if (LHS.isInvalid() || RHS.isInvalid())
7943     return QualType();
7944 
7945   QualType LHSTy = LHS.get()->getType();
7946   QualType RHSTy = RHS.get()->getType();
7947 
7948   // Diagnose attempts to convert between __float128 and long double where
7949   // such conversions currently can't be handled.
7950   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7951     Diag(QuestionLoc,
7952          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7953       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7954     return QualType();
7955   }
7956 
7957   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7958   // selection operator (?:).
7959   if (getLangOpts().OpenCL &&
7960       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7961     return QualType();
7962   }
7963 
7964   // If both operands have arithmetic type, do the usual arithmetic conversions
7965   // to find a common type: C99 6.5.15p3,5.
7966   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7967     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7968     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7969 
7970     return ResTy;
7971   }
7972 
7973   // If both operands are the same structure or union type, the result is that
7974   // type.
7975   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7976     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7977       if (LHSRT->getDecl() == RHSRT->getDecl())
7978         // "If both the operands have structure or union type, the result has
7979         // that type."  This implies that CV qualifiers are dropped.
7980         return LHSTy.getUnqualifiedType();
7981     // FIXME: Type of conditional expression must be complete in C mode.
7982   }
7983 
7984   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7985   // The following || allows only one side to be void (a GCC-ism).
7986   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7987     return checkConditionalVoidType(*this, LHS, RHS);
7988   }
7989 
7990   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7991   // the type of the other operand."
7992   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7993   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7994 
7995   // All objective-c pointer type analysis is done here.
7996   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7997                                                         QuestionLoc);
7998   if (LHS.isInvalid() || RHS.isInvalid())
7999     return QualType();
8000   if (!compositeType.isNull())
8001     return compositeType;
8002 
8003 
8004   // Handle block pointer types.
8005   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8006     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8007                                                      QuestionLoc);
8008 
8009   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8010   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8011     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8012                                                        QuestionLoc);
8013 
8014   // GCC compatibility: soften pointer/integer mismatch.  Note that
8015   // null pointers have been filtered out by this point.
8016   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8017       /*IsIntFirstExpr=*/true))
8018     return RHSTy;
8019   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8020       /*IsIntFirstExpr=*/false))
8021     return LHSTy;
8022 
8023   // Allow ?: operations in which both operands have the same
8024   // built-in sizeless type.
8025   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8026     return LHSTy;
8027 
8028   // Emit a better diagnostic if one of the expressions is a null pointer
8029   // constant and the other is not a pointer type. In this case, the user most
8030   // likely forgot to take the address of the other expression.
8031   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8032     return QualType();
8033 
8034   // Otherwise, the operands are not compatible.
8035   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8036     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8037     << RHS.get()->getSourceRange();
8038   return QualType();
8039 }
8040 
8041 /// FindCompositeObjCPointerType - Helper method to find composite type of
8042 /// two objective-c pointer types of the two input expressions.
8043 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8044                                             SourceLocation QuestionLoc) {
8045   QualType LHSTy = LHS.get()->getType();
8046   QualType RHSTy = RHS.get()->getType();
8047 
8048   // Handle things like Class and struct objc_class*.  Here we case the result
8049   // to the pseudo-builtin, because that will be implicitly cast back to the
8050   // redefinition type if an attempt is made to access its fields.
8051   if (LHSTy->isObjCClassType() &&
8052       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8053     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8054     return LHSTy;
8055   }
8056   if (RHSTy->isObjCClassType() &&
8057       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8058     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8059     return RHSTy;
8060   }
8061   // And the same for struct objc_object* / id
8062   if (LHSTy->isObjCIdType() &&
8063       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8064     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8065     return LHSTy;
8066   }
8067   if (RHSTy->isObjCIdType() &&
8068       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8069     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8070     return RHSTy;
8071   }
8072   // And the same for struct objc_selector* / SEL
8073   if (Context.isObjCSelType(LHSTy) &&
8074       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8075     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8076     return LHSTy;
8077   }
8078   if (Context.isObjCSelType(RHSTy) &&
8079       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8080     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8081     return RHSTy;
8082   }
8083   // Check constraints for Objective-C object pointers types.
8084   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8085 
8086     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8087       // Two identical object pointer types are always compatible.
8088       return LHSTy;
8089     }
8090     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8091     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8092     QualType compositeType = LHSTy;
8093 
8094     // If both operands are interfaces and either operand can be
8095     // assigned to the other, use that type as the composite
8096     // type. This allows
8097     //   xxx ? (A*) a : (B*) b
8098     // where B is a subclass of A.
8099     //
8100     // Additionally, as for assignment, if either type is 'id'
8101     // allow silent coercion. Finally, if the types are
8102     // incompatible then make sure to use 'id' as the composite
8103     // type so the result is acceptable for sending messages to.
8104 
8105     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8106     // It could return the composite type.
8107     if (!(compositeType =
8108           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8109       // Nothing more to do.
8110     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8111       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8112     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8113       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8114     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8115                 RHSOPT->isObjCQualifiedIdType()) &&
8116                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8117                                                          true)) {
8118       // Need to handle "id<xx>" explicitly.
8119       // GCC allows qualified id and any Objective-C type to devolve to
8120       // id. Currently localizing to here until clear this should be
8121       // part of ObjCQualifiedIdTypesAreCompatible.
8122       compositeType = Context.getObjCIdType();
8123     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8124       compositeType = Context.getObjCIdType();
8125     } else {
8126       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8127       << LHSTy << RHSTy
8128       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8129       QualType incompatTy = Context.getObjCIdType();
8130       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8131       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8132       return incompatTy;
8133     }
8134     // The object pointer types are compatible.
8135     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8136     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8137     return compositeType;
8138   }
8139   // Check Objective-C object pointer types and 'void *'
8140   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8141     if (getLangOpts().ObjCAutoRefCount) {
8142       // ARC forbids the implicit conversion of object pointers to 'void *',
8143       // so these types are not compatible.
8144       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8145           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8146       LHS = RHS = true;
8147       return QualType();
8148     }
8149     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8150     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8151     QualType destPointee
8152     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8153     QualType destType = Context.getPointerType(destPointee);
8154     // Add qualifiers if necessary.
8155     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8156     // Promote to void*.
8157     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8158     return destType;
8159   }
8160   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8161     if (getLangOpts().ObjCAutoRefCount) {
8162       // ARC forbids the implicit conversion of object pointers to 'void *',
8163       // so these types are not compatible.
8164       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8165           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8166       LHS = RHS = true;
8167       return QualType();
8168     }
8169     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8170     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8171     QualType destPointee
8172     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8173     QualType destType = Context.getPointerType(destPointee);
8174     // Add qualifiers if necessary.
8175     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8176     // Promote to void*.
8177     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8178     return destType;
8179   }
8180   return QualType();
8181 }
8182 
8183 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8184 /// ParenRange in parentheses.
8185 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8186                                const PartialDiagnostic &Note,
8187                                SourceRange ParenRange) {
8188   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8189   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8190       EndLoc.isValid()) {
8191     Self.Diag(Loc, Note)
8192       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8193       << FixItHint::CreateInsertion(EndLoc, ")");
8194   } else {
8195     // We can't display the parentheses, so just show the bare note.
8196     Self.Diag(Loc, Note) << ParenRange;
8197   }
8198 }
8199 
8200 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8201   return BinaryOperator::isAdditiveOp(Opc) ||
8202          BinaryOperator::isMultiplicativeOp(Opc) ||
8203          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8204   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8205   // not any of the logical operators.  Bitwise-xor is commonly used as a
8206   // logical-xor because there is no logical-xor operator.  The logical
8207   // operators, including uses of xor, have a high false positive rate for
8208   // precedence warnings.
8209 }
8210 
8211 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8212 /// expression, either using a built-in or overloaded operator,
8213 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8214 /// expression.
8215 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8216                                    Expr **RHSExprs) {
8217   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8218   E = E->IgnoreImpCasts();
8219   E = E->IgnoreConversionOperator();
8220   E = E->IgnoreImpCasts();
8221   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8222     E = MTE->getSubExpr();
8223     E = E->IgnoreImpCasts();
8224   }
8225 
8226   // Built-in binary operator.
8227   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8228     if (IsArithmeticOp(OP->getOpcode())) {
8229       *Opcode = OP->getOpcode();
8230       *RHSExprs = OP->getRHS();
8231       return true;
8232     }
8233   }
8234 
8235   // Overloaded operator.
8236   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8237     if (Call->getNumArgs() != 2)
8238       return false;
8239 
8240     // Make sure this is really a binary operator that is safe to pass into
8241     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8242     OverloadedOperatorKind OO = Call->getOperator();
8243     if (OO < OO_Plus || OO > OO_Arrow ||
8244         OO == OO_PlusPlus || OO == OO_MinusMinus)
8245       return false;
8246 
8247     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8248     if (IsArithmeticOp(OpKind)) {
8249       *Opcode = OpKind;
8250       *RHSExprs = Call->getArg(1);
8251       return true;
8252     }
8253   }
8254 
8255   return false;
8256 }
8257 
8258 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8259 /// or is a logical expression such as (x==y) which has int type, but is
8260 /// commonly interpreted as boolean.
8261 static bool ExprLooksBoolean(Expr *E) {
8262   E = E->IgnoreParenImpCasts();
8263 
8264   if (E->getType()->isBooleanType())
8265     return true;
8266   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8267     return OP->isComparisonOp() || OP->isLogicalOp();
8268   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8269     return OP->getOpcode() == UO_LNot;
8270   if (E->getType()->isPointerType())
8271     return true;
8272   // FIXME: What about overloaded operator calls returning "unspecified boolean
8273   // type"s (commonly pointer-to-members)?
8274 
8275   return false;
8276 }
8277 
8278 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8279 /// and binary operator are mixed in a way that suggests the programmer assumed
8280 /// the conditional operator has higher precedence, for example:
8281 /// "int x = a + someBinaryCondition ? 1 : 2".
8282 static void DiagnoseConditionalPrecedence(Sema &Self,
8283                                           SourceLocation OpLoc,
8284                                           Expr *Condition,
8285                                           Expr *LHSExpr,
8286                                           Expr *RHSExpr) {
8287   BinaryOperatorKind CondOpcode;
8288   Expr *CondRHS;
8289 
8290   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8291     return;
8292   if (!ExprLooksBoolean(CondRHS))
8293     return;
8294 
8295   // The condition is an arithmetic binary expression, with a right-
8296   // hand side that looks boolean, so warn.
8297 
8298   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8299                         ? diag::warn_precedence_bitwise_conditional
8300                         : diag::warn_precedence_conditional;
8301 
8302   Self.Diag(OpLoc, DiagID)
8303       << Condition->getSourceRange()
8304       << BinaryOperator::getOpcodeStr(CondOpcode);
8305 
8306   SuggestParentheses(
8307       Self, OpLoc,
8308       Self.PDiag(diag::note_precedence_silence)
8309           << BinaryOperator::getOpcodeStr(CondOpcode),
8310       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8311 
8312   SuggestParentheses(Self, OpLoc,
8313                      Self.PDiag(diag::note_precedence_conditional_first),
8314                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8315 }
8316 
8317 /// Compute the nullability of a conditional expression.
8318 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8319                                               QualType LHSTy, QualType RHSTy,
8320                                               ASTContext &Ctx) {
8321   if (!ResTy->isAnyPointerType())
8322     return ResTy;
8323 
8324   auto GetNullability = [&Ctx](QualType Ty) {
8325     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8326     if (Kind)
8327       return *Kind;
8328     return NullabilityKind::Unspecified;
8329   };
8330 
8331   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8332   NullabilityKind MergedKind;
8333 
8334   // Compute nullability of a binary conditional expression.
8335   if (IsBin) {
8336     if (LHSKind == NullabilityKind::NonNull)
8337       MergedKind = NullabilityKind::NonNull;
8338     else
8339       MergedKind = RHSKind;
8340   // Compute nullability of a normal conditional expression.
8341   } else {
8342     if (LHSKind == NullabilityKind::Nullable ||
8343         RHSKind == NullabilityKind::Nullable)
8344       MergedKind = NullabilityKind::Nullable;
8345     else if (LHSKind == NullabilityKind::NonNull)
8346       MergedKind = RHSKind;
8347     else if (RHSKind == NullabilityKind::NonNull)
8348       MergedKind = LHSKind;
8349     else
8350       MergedKind = NullabilityKind::Unspecified;
8351   }
8352 
8353   // Return if ResTy already has the correct nullability.
8354   if (GetNullability(ResTy) == MergedKind)
8355     return ResTy;
8356 
8357   // Strip all nullability from ResTy.
8358   while (ResTy->getNullability(Ctx))
8359     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8360 
8361   // Create a new AttributedType with the new nullability kind.
8362   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8363   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8364 }
8365 
8366 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8367 /// in the case of a the GNU conditional expr extension.
8368 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8369                                     SourceLocation ColonLoc,
8370                                     Expr *CondExpr, Expr *LHSExpr,
8371                                     Expr *RHSExpr) {
8372   if (!getLangOpts().CPlusPlus) {
8373     // C cannot handle TypoExpr nodes in the condition because it
8374     // doesn't handle dependent types properly, so make sure any TypoExprs have
8375     // been dealt with before checking the operands.
8376     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8377     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8378     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8379 
8380     if (!CondResult.isUsable())
8381       return ExprError();
8382 
8383     if (LHSExpr) {
8384       if (!LHSResult.isUsable())
8385         return ExprError();
8386     }
8387 
8388     if (!RHSResult.isUsable())
8389       return ExprError();
8390 
8391     CondExpr = CondResult.get();
8392     LHSExpr = LHSResult.get();
8393     RHSExpr = RHSResult.get();
8394   }
8395 
8396   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8397   // was the condition.
8398   OpaqueValueExpr *opaqueValue = nullptr;
8399   Expr *commonExpr = nullptr;
8400   if (!LHSExpr) {
8401     commonExpr = CondExpr;
8402     // Lower out placeholder types first.  This is important so that we don't
8403     // try to capture a placeholder. This happens in few cases in C++; such
8404     // as Objective-C++'s dictionary subscripting syntax.
8405     if (commonExpr->hasPlaceholderType()) {
8406       ExprResult result = CheckPlaceholderExpr(commonExpr);
8407       if (!result.isUsable()) return ExprError();
8408       commonExpr = result.get();
8409     }
8410     // We usually want to apply unary conversions *before* saving, except
8411     // in the special case of a C++ l-value conditional.
8412     if (!(getLangOpts().CPlusPlus
8413           && !commonExpr->isTypeDependent()
8414           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8415           && commonExpr->isGLValue()
8416           && commonExpr->isOrdinaryOrBitFieldObject()
8417           && RHSExpr->isOrdinaryOrBitFieldObject()
8418           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8419       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8420       if (commonRes.isInvalid())
8421         return ExprError();
8422       commonExpr = commonRes.get();
8423     }
8424 
8425     // If the common expression is a class or array prvalue, materialize it
8426     // so that we can safely refer to it multiple times.
8427     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8428                                    commonExpr->getType()->isArrayType())) {
8429       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8430       if (MatExpr.isInvalid())
8431         return ExprError();
8432       commonExpr = MatExpr.get();
8433     }
8434 
8435     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8436                                                 commonExpr->getType(),
8437                                                 commonExpr->getValueKind(),
8438                                                 commonExpr->getObjectKind(),
8439                                                 commonExpr);
8440     LHSExpr = CondExpr = opaqueValue;
8441   }
8442 
8443   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8444   ExprValueKind VK = VK_RValue;
8445   ExprObjectKind OK = OK_Ordinary;
8446   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8447   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8448                                              VK, OK, QuestionLoc);
8449   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8450       RHS.isInvalid())
8451     return ExprError();
8452 
8453   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8454                                 RHS.get());
8455 
8456   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8457 
8458   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8459                                          Context);
8460 
8461   if (!commonExpr)
8462     return new (Context)
8463         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8464                             RHS.get(), result, VK, OK);
8465 
8466   return new (Context) BinaryConditionalOperator(
8467       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8468       ColonLoc, result, VK, OK);
8469 }
8470 
8471 // Check if we have a conversion between incompatible cmse function pointer
8472 // types, that is, a conversion between a function pointer with the
8473 // cmse_nonsecure_call attribute and one without.
8474 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8475                                           QualType ToType) {
8476   if (const auto *ToFn =
8477           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8478     if (const auto *FromFn =
8479             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8480       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8481       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8482 
8483       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8484     }
8485   }
8486   return false;
8487 }
8488 
8489 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8490 // being closely modeled after the C99 spec:-). The odd characteristic of this
8491 // routine is it effectively iqnores the qualifiers on the top level pointee.
8492 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8493 // FIXME: add a couple examples in this comment.
8494 static Sema::AssignConvertType
8495 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8496   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8497   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8498 
8499   // get the "pointed to" type (ignoring qualifiers at the top level)
8500   const Type *lhptee, *rhptee;
8501   Qualifiers lhq, rhq;
8502   std::tie(lhptee, lhq) =
8503       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8504   std::tie(rhptee, rhq) =
8505       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8506 
8507   Sema::AssignConvertType ConvTy = Sema::Compatible;
8508 
8509   // C99 6.5.16.1p1: This following citation is common to constraints
8510   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8511   // qualifiers of the type *pointed to* by the right;
8512 
8513   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8514   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8515       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8516     // Ignore lifetime for further calculation.
8517     lhq.removeObjCLifetime();
8518     rhq.removeObjCLifetime();
8519   }
8520 
8521   if (!lhq.compatiblyIncludes(rhq)) {
8522     // Treat address-space mismatches as fatal.
8523     if (!lhq.isAddressSpaceSupersetOf(rhq))
8524       return Sema::IncompatiblePointerDiscardsQualifiers;
8525 
8526     // It's okay to add or remove GC or lifetime qualifiers when converting to
8527     // and from void*.
8528     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8529                         .compatiblyIncludes(
8530                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8531              && (lhptee->isVoidType() || rhptee->isVoidType()))
8532       ; // keep old
8533 
8534     // Treat lifetime mismatches as fatal.
8535     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8536       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8537 
8538     // For GCC/MS compatibility, other qualifier mismatches are treated
8539     // as still compatible in C.
8540     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8541   }
8542 
8543   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8544   // incomplete type and the other is a pointer to a qualified or unqualified
8545   // version of void...
8546   if (lhptee->isVoidType()) {
8547     if (rhptee->isIncompleteOrObjectType())
8548       return ConvTy;
8549 
8550     // As an extension, we allow cast to/from void* to function pointer.
8551     assert(rhptee->isFunctionType());
8552     return Sema::FunctionVoidPointer;
8553   }
8554 
8555   if (rhptee->isVoidType()) {
8556     if (lhptee->isIncompleteOrObjectType())
8557       return ConvTy;
8558 
8559     // As an extension, we allow cast to/from void* to function pointer.
8560     assert(lhptee->isFunctionType());
8561     return Sema::FunctionVoidPointer;
8562   }
8563 
8564   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8565   // unqualified versions of compatible types, ...
8566   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8567   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8568     // Check if the pointee types are compatible ignoring the sign.
8569     // We explicitly check for char so that we catch "char" vs
8570     // "unsigned char" on systems where "char" is unsigned.
8571     if (lhptee->isCharType())
8572       ltrans = S.Context.UnsignedCharTy;
8573     else if (lhptee->hasSignedIntegerRepresentation())
8574       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8575 
8576     if (rhptee->isCharType())
8577       rtrans = S.Context.UnsignedCharTy;
8578     else if (rhptee->hasSignedIntegerRepresentation())
8579       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8580 
8581     if (ltrans == rtrans) {
8582       // Types are compatible ignoring the sign. Qualifier incompatibility
8583       // takes priority over sign incompatibility because the sign
8584       // warning can be disabled.
8585       if (ConvTy != Sema::Compatible)
8586         return ConvTy;
8587 
8588       return Sema::IncompatiblePointerSign;
8589     }
8590 
8591     // If we are a multi-level pointer, it's possible that our issue is simply
8592     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8593     // the eventual target type is the same and the pointers have the same
8594     // level of indirection, this must be the issue.
8595     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8596       do {
8597         std::tie(lhptee, lhq) =
8598           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8599         std::tie(rhptee, rhq) =
8600           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8601 
8602         // Inconsistent address spaces at this point is invalid, even if the
8603         // address spaces would be compatible.
8604         // FIXME: This doesn't catch address space mismatches for pointers of
8605         // different nesting levels, like:
8606         //   __local int *** a;
8607         //   int ** b = a;
8608         // It's not clear how to actually determine when such pointers are
8609         // invalidly incompatible.
8610         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8611           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8612 
8613       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8614 
8615       if (lhptee == rhptee)
8616         return Sema::IncompatibleNestedPointerQualifiers;
8617     }
8618 
8619     // General pointer incompatibility takes priority over qualifiers.
8620     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8621       return Sema::IncompatibleFunctionPointer;
8622     return Sema::IncompatiblePointer;
8623   }
8624   if (!S.getLangOpts().CPlusPlus &&
8625       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8626     return Sema::IncompatibleFunctionPointer;
8627   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8628     return Sema::IncompatibleFunctionPointer;
8629   return ConvTy;
8630 }
8631 
8632 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8633 /// block pointer types are compatible or whether a block and normal pointer
8634 /// are compatible. It is more restrict than comparing two function pointer
8635 // types.
8636 static Sema::AssignConvertType
8637 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8638                                     QualType RHSType) {
8639   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8640   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8641 
8642   QualType lhptee, rhptee;
8643 
8644   // get the "pointed to" type (ignoring qualifiers at the top level)
8645   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8646   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8647 
8648   // In C++, the types have to match exactly.
8649   if (S.getLangOpts().CPlusPlus)
8650     return Sema::IncompatibleBlockPointer;
8651 
8652   Sema::AssignConvertType ConvTy = Sema::Compatible;
8653 
8654   // For blocks we enforce that qualifiers are identical.
8655   Qualifiers LQuals = lhptee.getLocalQualifiers();
8656   Qualifiers RQuals = rhptee.getLocalQualifiers();
8657   if (S.getLangOpts().OpenCL) {
8658     LQuals.removeAddressSpace();
8659     RQuals.removeAddressSpace();
8660   }
8661   if (LQuals != RQuals)
8662     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8663 
8664   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8665   // assignment.
8666   // The current behavior is similar to C++ lambdas. A block might be
8667   // assigned to a variable iff its return type and parameters are compatible
8668   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8669   // an assignment. Presumably it should behave in way that a function pointer
8670   // assignment does in C, so for each parameter and return type:
8671   //  * CVR and address space of LHS should be a superset of CVR and address
8672   //  space of RHS.
8673   //  * unqualified types should be compatible.
8674   if (S.getLangOpts().OpenCL) {
8675     if (!S.Context.typesAreBlockPointerCompatible(
8676             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8677             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8678       return Sema::IncompatibleBlockPointer;
8679   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8680     return Sema::IncompatibleBlockPointer;
8681 
8682   return ConvTy;
8683 }
8684 
8685 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8686 /// for assignment compatibility.
8687 static Sema::AssignConvertType
8688 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8689                                    QualType RHSType) {
8690   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8691   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8692 
8693   if (LHSType->isObjCBuiltinType()) {
8694     // Class is not compatible with ObjC object pointers.
8695     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8696         !RHSType->isObjCQualifiedClassType())
8697       return Sema::IncompatiblePointer;
8698     return Sema::Compatible;
8699   }
8700   if (RHSType->isObjCBuiltinType()) {
8701     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8702         !LHSType->isObjCQualifiedClassType())
8703       return Sema::IncompatiblePointer;
8704     return Sema::Compatible;
8705   }
8706   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8707   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8708 
8709   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8710       // make an exception for id<P>
8711       !LHSType->isObjCQualifiedIdType())
8712     return Sema::CompatiblePointerDiscardsQualifiers;
8713 
8714   if (S.Context.typesAreCompatible(LHSType, RHSType))
8715     return Sema::Compatible;
8716   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8717     return Sema::IncompatibleObjCQualifiedId;
8718   return Sema::IncompatiblePointer;
8719 }
8720 
8721 Sema::AssignConvertType
8722 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8723                                  QualType LHSType, QualType RHSType) {
8724   // Fake up an opaque expression.  We don't actually care about what
8725   // cast operations are required, so if CheckAssignmentConstraints
8726   // adds casts to this they'll be wasted, but fortunately that doesn't
8727   // usually happen on valid code.
8728   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8729   ExprResult RHSPtr = &RHSExpr;
8730   CastKind K;
8731 
8732   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8733 }
8734 
8735 /// This helper function returns true if QT is a vector type that has element
8736 /// type ElementType.
8737 static bool isVector(QualType QT, QualType ElementType) {
8738   if (const VectorType *VT = QT->getAs<VectorType>())
8739     return VT->getElementType().getCanonicalType() == ElementType;
8740   return false;
8741 }
8742 
8743 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8744 /// has code to accommodate several GCC extensions when type checking
8745 /// pointers. Here are some objectionable examples that GCC considers warnings:
8746 ///
8747 ///  int a, *pint;
8748 ///  short *pshort;
8749 ///  struct foo *pfoo;
8750 ///
8751 ///  pint = pshort; // warning: assignment from incompatible pointer type
8752 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8753 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8754 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8755 ///
8756 /// As a result, the code for dealing with pointers is more complex than the
8757 /// C99 spec dictates.
8758 ///
8759 /// Sets 'Kind' for any result kind except Incompatible.
8760 Sema::AssignConvertType
8761 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8762                                  CastKind &Kind, bool ConvertRHS) {
8763   QualType RHSType = RHS.get()->getType();
8764   QualType OrigLHSType = LHSType;
8765 
8766   // Get canonical types.  We're not formatting these types, just comparing
8767   // them.
8768   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8769   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8770 
8771   // Common case: no conversion required.
8772   if (LHSType == RHSType) {
8773     Kind = CK_NoOp;
8774     return Compatible;
8775   }
8776 
8777   // If we have an atomic type, try a non-atomic assignment, then just add an
8778   // atomic qualification step.
8779   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8780     Sema::AssignConvertType result =
8781       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8782     if (result != Compatible)
8783       return result;
8784     if (Kind != CK_NoOp && ConvertRHS)
8785       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8786     Kind = CK_NonAtomicToAtomic;
8787     return Compatible;
8788   }
8789 
8790   // If the left-hand side is a reference type, then we are in a
8791   // (rare!) case where we've allowed the use of references in C,
8792   // e.g., as a parameter type in a built-in function. In this case,
8793   // just make sure that the type referenced is compatible with the
8794   // right-hand side type. The caller is responsible for adjusting
8795   // LHSType so that the resulting expression does not have reference
8796   // type.
8797   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8798     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8799       Kind = CK_LValueBitCast;
8800       return Compatible;
8801     }
8802     return Incompatible;
8803   }
8804 
8805   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8806   // to the same ExtVector type.
8807   if (LHSType->isExtVectorType()) {
8808     if (RHSType->isExtVectorType())
8809       return Incompatible;
8810     if (RHSType->isArithmeticType()) {
8811       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8812       if (ConvertRHS)
8813         RHS = prepareVectorSplat(LHSType, RHS.get());
8814       Kind = CK_VectorSplat;
8815       return Compatible;
8816     }
8817   }
8818 
8819   // Conversions to or from vector type.
8820   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8821     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8822       // Allow assignments of an AltiVec vector type to an equivalent GCC
8823       // vector type and vice versa
8824       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8825         Kind = CK_BitCast;
8826         return Compatible;
8827       }
8828 
8829       // If we are allowing lax vector conversions, and LHS and RHS are both
8830       // vectors, the total size only needs to be the same. This is a bitcast;
8831       // no bits are changed but the result type is different.
8832       if (isLaxVectorConversion(RHSType, LHSType)) {
8833         Kind = CK_BitCast;
8834         return IncompatibleVectors;
8835       }
8836     }
8837 
8838     // When the RHS comes from another lax conversion (e.g. binops between
8839     // scalars and vectors) the result is canonicalized as a vector. When the
8840     // LHS is also a vector, the lax is allowed by the condition above. Handle
8841     // the case where LHS is a scalar.
8842     if (LHSType->isScalarType()) {
8843       const VectorType *VecType = RHSType->getAs<VectorType>();
8844       if (VecType && VecType->getNumElements() == 1 &&
8845           isLaxVectorConversion(RHSType, LHSType)) {
8846         ExprResult *VecExpr = &RHS;
8847         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8848         Kind = CK_BitCast;
8849         return Compatible;
8850       }
8851     }
8852 
8853     return Incompatible;
8854   }
8855 
8856   // Diagnose attempts to convert between __float128 and long double where
8857   // such conversions currently can't be handled.
8858   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8859     return Incompatible;
8860 
8861   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8862   // discards the imaginary part.
8863   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8864       !LHSType->getAs<ComplexType>())
8865     return Incompatible;
8866 
8867   // Arithmetic conversions.
8868   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8869       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8870     if (ConvertRHS)
8871       Kind = PrepareScalarCast(RHS, LHSType);
8872     return Compatible;
8873   }
8874 
8875   // Conversions to normal pointers.
8876   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8877     // U* -> T*
8878     if (isa<PointerType>(RHSType)) {
8879       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8880       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8881       if (AddrSpaceL != AddrSpaceR)
8882         Kind = CK_AddressSpaceConversion;
8883       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8884         Kind = CK_NoOp;
8885       else
8886         Kind = CK_BitCast;
8887       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8888     }
8889 
8890     // int -> T*
8891     if (RHSType->isIntegerType()) {
8892       Kind = CK_IntegralToPointer; // FIXME: null?
8893       return IntToPointer;
8894     }
8895 
8896     // C pointers are not compatible with ObjC object pointers,
8897     // with two exceptions:
8898     if (isa<ObjCObjectPointerType>(RHSType)) {
8899       //  - conversions to void*
8900       if (LHSPointer->getPointeeType()->isVoidType()) {
8901         Kind = CK_BitCast;
8902         return Compatible;
8903       }
8904 
8905       //  - conversions from 'Class' to the redefinition type
8906       if (RHSType->isObjCClassType() &&
8907           Context.hasSameType(LHSType,
8908                               Context.getObjCClassRedefinitionType())) {
8909         Kind = CK_BitCast;
8910         return Compatible;
8911       }
8912 
8913       Kind = CK_BitCast;
8914       return IncompatiblePointer;
8915     }
8916 
8917     // U^ -> void*
8918     if (RHSType->getAs<BlockPointerType>()) {
8919       if (LHSPointer->getPointeeType()->isVoidType()) {
8920         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8921         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8922                                 ->getPointeeType()
8923                                 .getAddressSpace();
8924         Kind =
8925             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8926         return Compatible;
8927       }
8928     }
8929 
8930     return Incompatible;
8931   }
8932 
8933   // Conversions to block pointers.
8934   if (isa<BlockPointerType>(LHSType)) {
8935     // U^ -> T^
8936     if (RHSType->isBlockPointerType()) {
8937       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8938                               ->getPointeeType()
8939                               .getAddressSpace();
8940       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8941                               ->getPointeeType()
8942                               .getAddressSpace();
8943       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8944       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8945     }
8946 
8947     // int or null -> T^
8948     if (RHSType->isIntegerType()) {
8949       Kind = CK_IntegralToPointer; // FIXME: null
8950       return IntToBlockPointer;
8951     }
8952 
8953     // id -> T^
8954     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8955       Kind = CK_AnyPointerToBlockPointerCast;
8956       return Compatible;
8957     }
8958 
8959     // void* -> T^
8960     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8961       if (RHSPT->getPointeeType()->isVoidType()) {
8962         Kind = CK_AnyPointerToBlockPointerCast;
8963         return Compatible;
8964       }
8965 
8966     return Incompatible;
8967   }
8968 
8969   // Conversions to Objective-C pointers.
8970   if (isa<ObjCObjectPointerType>(LHSType)) {
8971     // A* -> B*
8972     if (RHSType->isObjCObjectPointerType()) {
8973       Kind = CK_BitCast;
8974       Sema::AssignConvertType result =
8975         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8976       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8977           result == Compatible &&
8978           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8979         result = IncompatibleObjCWeakRef;
8980       return result;
8981     }
8982 
8983     // int or null -> A*
8984     if (RHSType->isIntegerType()) {
8985       Kind = CK_IntegralToPointer; // FIXME: null
8986       return IntToPointer;
8987     }
8988 
8989     // In general, C pointers are not compatible with ObjC object pointers,
8990     // with two exceptions:
8991     if (isa<PointerType>(RHSType)) {
8992       Kind = CK_CPointerToObjCPointerCast;
8993 
8994       //  - conversions from 'void*'
8995       if (RHSType->isVoidPointerType()) {
8996         return Compatible;
8997       }
8998 
8999       //  - conversions to 'Class' from its redefinition type
9000       if (LHSType->isObjCClassType() &&
9001           Context.hasSameType(RHSType,
9002                               Context.getObjCClassRedefinitionType())) {
9003         return Compatible;
9004       }
9005 
9006       return IncompatiblePointer;
9007     }
9008 
9009     // Only under strict condition T^ is compatible with an Objective-C pointer.
9010     if (RHSType->isBlockPointerType() &&
9011         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9012       if (ConvertRHS)
9013         maybeExtendBlockObject(RHS);
9014       Kind = CK_BlockPointerToObjCPointerCast;
9015       return Compatible;
9016     }
9017 
9018     return Incompatible;
9019   }
9020 
9021   // Conversions from pointers that are not covered by the above.
9022   if (isa<PointerType>(RHSType)) {
9023     // T* -> _Bool
9024     if (LHSType == Context.BoolTy) {
9025       Kind = CK_PointerToBoolean;
9026       return Compatible;
9027     }
9028 
9029     // T* -> int
9030     if (LHSType->isIntegerType()) {
9031       Kind = CK_PointerToIntegral;
9032       return PointerToInt;
9033     }
9034 
9035     return Incompatible;
9036   }
9037 
9038   // Conversions from Objective-C pointers that are not covered by the above.
9039   if (isa<ObjCObjectPointerType>(RHSType)) {
9040     // T* -> _Bool
9041     if (LHSType == Context.BoolTy) {
9042       Kind = CK_PointerToBoolean;
9043       return Compatible;
9044     }
9045 
9046     // T* -> int
9047     if (LHSType->isIntegerType()) {
9048       Kind = CK_PointerToIntegral;
9049       return PointerToInt;
9050     }
9051 
9052     return Incompatible;
9053   }
9054 
9055   // struct A -> struct B
9056   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9057     if (Context.typesAreCompatible(LHSType, RHSType)) {
9058       Kind = CK_NoOp;
9059       return Compatible;
9060     }
9061   }
9062 
9063   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9064     Kind = CK_IntToOCLSampler;
9065     return Compatible;
9066   }
9067 
9068   return Incompatible;
9069 }
9070 
9071 /// Constructs a transparent union from an expression that is
9072 /// used to initialize the transparent union.
9073 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9074                                       ExprResult &EResult, QualType UnionType,
9075                                       FieldDecl *Field) {
9076   // Build an initializer list that designates the appropriate member
9077   // of the transparent union.
9078   Expr *E = EResult.get();
9079   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9080                                                    E, SourceLocation());
9081   Initializer->setType(UnionType);
9082   Initializer->setInitializedFieldInUnion(Field);
9083 
9084   // Build a compound literal constructing a value of the transparent
9085   // union type from this initializer list.
9086   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9087   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9088                                         VK_RValue, Initializer, false);
9089 }
9090 
9091 Sema::AssignConvertType
9092 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9093                                                ExprResult &RHS) {
9094   QualType RHSType = RHS.get()->getType();
9095 
9096   // If the ArgType is a Union type, we want to handle a potential
9097   // transparent_union GCC extension.
9098   const RecordType *UT = ArgType->getAsUnionType();
9099   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9100     return Incompatible;
9101 
9102   // The field to initialize within the transparent union.
9103   RecordDecl *UD = UT->getDecl();
9104   FieldDecl *InitField = nullptr;
9105   // It's compatible if the expression matches any of the fields.
9106   for (auto *it : UD->fields()) {
9107     if (it->getType()->isPointerType()) {
9108       // If the transparent union contains a pointer type, we allow:
9109       // 1) void pointer
9110       // 2) null pointer constant
9111       if (RHSType->isPointerType())
9112         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9113           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9114           InitField = it;
9115           break;
9116         }
9117 
9118       if (RHS.get()->isNullPointerConstant(Context,
9119                                            Expr::NPC_ValueDependentIsNull)) {
9120         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9121                                 CK_NullToPointer);
9122         InitField = it;
9123         break;
9124       }
9125     }
9126 
9127     CastKind Kind;
9128     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9129           == Compatible) {
9130       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9131       InitField = it;
9132       break;
9133     }
9134   }
9135 
9136   if (!InitField)
9137     return Incompatible;
9138 
9139   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9140   return Compatible;
9141 }
9142 
9143 Sema::AssignConvertType
9144 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9145                                        bool Diagnose,
9146                                        bool DiagnoseCFAudited,
9147                                        bool ConvertRHS) {
9148   // We need to be able to tell the caller whether we diagnosed a problem, if
9149   // they ask us to issue diagnostics.
9150   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9151 
9152   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9153   // we can't avoid *all* modifications at the moment, so we need some somewhere
9154   // to put the updated value.
9155   ExprResult LocalRHS = CallerRHS;
9156   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9157 
9158   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9159     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9160       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9161           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9162         Diag(RHS.get()->getExprLoc(),
9163              diag::warn_noderef_to_dereferenceable_pointer)
9164             << RHS.get()->getSourceRange();
9165       }
9166     }
9167   }
9168 
9169   if (getLangOpts().CPlusPlus) {
9170     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9171       // C++ 5.17p3: If the left operand is not of class type, the
9172       // expression is implicitly converted (C++ 4) to the
9173       // cv-unqualified type of the left operand.
9174       QualType RHSType = RHS.get()->getType();
9175       if (Diagnose) {
9176         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9177                                         AA_Assigning);
9178       } else {
9179         ImplicitConversionSequence ICS =
9180             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9181                                   /*SuppressUserConversions=*/false,
9182                                   AllowedExplicit::None,
9183                                   /*InOverloadResolution=*/false,
9184                                   /*CStyle=*/false,
9185                                   /*AllowObjCWritebackConversion=*/false);
9186         if (ICS.isFailure())
9187           return Incompatible;
9188         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9189                                         ICS, AA_Assigning);
9190       }
9191       if (RHS.isInvalid())
9192         return Incompatible;
9193       Sema::AssignConvertType result = Compatible;
9194       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9195           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9196         result = IncompatibleObjCWeakRef;
9197       return result;
9198     }
9199 
9200     // FIXME: Currently, we fall through and treat C++ classes like C
9201     // structures.
9202     // FIXME: We also fall through for atomics; not sure what should
9203     // happen there, though.
9204   } else if (RHS.get()->getType() == Context.OverloadTy) {
9205     // As a set of extensions to C, we support overloading on functions. These
9206     // functions need to be resolved here.
9207     DeclAccessPair DAP;
9208     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9209             RHS.get(), LHSType, /*Complain=*/false, DAP))
9210       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9211     else
9212       return Incompatible;
9213   }
9214 
9215   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9216   // a null pointer constant.
9217   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9218        LHSType->isBlockPointerType()) &&
9219       RHS.get()->isNullPointerConstant(Context,
9220                                        Expr::NPC_ValueDependentIsNull)) {
9221     if (Diagnose || ConvertRHS) {
9222       CastKind Kind;
9223       CXXCastPath Path;
9224       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9225                              /*IgnoreBaseAccess=*/false, Diagnose);
9226       if (ConvertRHS)
9227         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9228     }
9229     return Compatible;
9230   }
9231 
9232   // OpenCL queue_t type assignment.
9233   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9234                                  Context, Expr::NPC_ValueDependentIsNull)) {
9235     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9236     return Compatible;
9237   }
9238 
9239   // This check seems unnatural, however it is necessary to ensure the proper
9240   // conversion of functions/arrays. If the conversion were done for all
9241   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9242   // expressions that suppress this implicit conversion (&, sizeof).
9243   //
9244   // Suppress this for references: C++ 8.5.3p5.
9245   if (!LHSType->isReferenceType()) {
9246     // FIXME: We potentially allocate here even if ConvertRHS is false.
9247     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9248     if (RHS.isInvalid())
9249       return Incompatible;
9250   }
9251   CastKind Kind;
9252   Sema::AssignConvertType result =
9253     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9254 
9255   // C99 6.5.16.1p2: The value of the right operand is converted to the
9256   // type of the assignment expression.
9257   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9258   // so that we can use references in built-in functions even in C.
9259   // The getNonReferenceType() call makes sure that the resulting expression
9260   // does not have reference type.
9261   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9262     QualType Ty = LHSType.getNonLValueExprType(Context);
9263     Expr *E = RHS.get();
9264 
9265     // Check for various Objective-C errors. If we are not reporting
9266     // diagnostics and just checking for errors, e.g., during overload
9267     // resolution, return Incompatible to indicate the failure.
9268     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9269         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9270                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9271       if (!Diagnose)
9272         return Incompatible;
9273     }
9274     if (getLangOpts().ObjC &&
9275         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9276                                            E->getType(), E, Diagnose) ||
9277          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
9278       if (!Diagnose)
9279         return Incompatible;
9280       // Replace the expression with a corrected version and continue so we
9281       // can find further errors.
9282       RHS = E;
9283       return Compatible;
9284     }
9285 
9286     if (ConvertRHS)
9287       RHS = ImpCastExprToType(E, Ty, Kind);
9288   }
9289 
9290   return result;
9291 }
9292 
9293 namespace {
9294 /// The original operand to an operator, prior to the application of the usual
9295 /// arithmetic conversions and converting the arguments of a builtin operator
9296 /// candidate.
9297 struct OriginalOperand {
9298   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9299     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9300       Op = MTE->getSubExpr();
9301     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9302       Op = BTE->getSubExpr();
9303     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9304       Orig = ICE->getSubExprAsWritten();
9305       Conversion = ICE->getConversionFunction();
9306     }
9307   }
9308 
9309   QualType getType() const { return Orig->getType(); }
9310 
9311   Expr *Orig;
9312   NamedDecl *Conversion;
9313 };
9314 }
9315 
9316 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9317                                ExprResult &RHS) {
9318   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9319 
9320   Diag(Loc, diag::err_typecheck_invalid_operands)
9321     << OrigLHS.getType() << OrigRHS.getType()
9322     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9323 
9324   // If a user-defined conversion was applied to either of the operands prior
9325   // to applying the built-in operator rules, tell the user about it.
9326   if (OrigLHS.Conversion) {
9327     Diag(OrigLHS.Conversion->getLocation(),
9328          diag::note_typecheck_invalid_operands_converted)
9329       << 0 << LHS.get()->getType();
9330   }
9331   if (OrigRHS.Conversion) {
9332     Diag(OrigRHS.Conversion->getLocation(),
9333          diag::note_typecheck_invalid_operands_converted)
9334       << 1 << RHS.get()->getType();
9335   }
9336 
9337   return QualType();
9338 }
9339 
9340 // Diagnose cases where a scalar was implicitly converted to a vector and
9341 // diagnose the underlying types. Otherwise, diagnose the error
9342 // as invalid vector logical operands for non-C++ cases.
9343 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9344                                             ExprResult &RHS) {
9345   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9346   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9347 
9348   bool LHSNatVec = LHSType->isVectorType();
9349   bool RHSNatVec = RHSType->isVectorType();
9350 
9351   if (!(LHSNatVec && RHSNatVec)) {
9352     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9353     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9354     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9355         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9356         << Vector->getSourceRange();
9357     return QualType();
9358   }
9359 
9360   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9361       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9362       << RHS.get()->getSourceRange();
9363 
9364   return QualType();
9365 }
9366 
9367 /// Try to convert a value of non-vector type to a vector type by converting
9368 /// the type to the element type of the vector and then performing a splat.
9369 /// If the language is OpenCL, we only use conversions that promote scalar
9370 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9371 /// for float->int.
9372 ///
9373 /// OpenCL V2.0 6.2.6.p2:
9374 /// An error shall occur if any scalar operand type has greater rank
9375 /// than the type of the vector element.
9376 ///
9377 /// \param scalar - if non-null, actually perform the conversions
9378 /// \return true if the operation fails (but without diagnosing the failure)
9379 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9380                                      QualType scalarTy,
9381                                      QualType vectorEltTy,
9382                                      QualType vectorTy,
9383                                      unsigned &DiagID) {
9384   // The conversion to apply to the scalar before splatting it,
9385   // if necessary.
9386   CastKind scalarCast = CK_NoOp;
9387 
9388   if (vectorEltTy->isIntegralType(S.Context)) {
9389     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9390         (scalarTy->isIntegerType() &&
9391          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9392       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9393       return true;
9394     }
9395     if (!scalarTy->isIntegralType(S.Context))
9396       return true;
9397     scalarCast = CK_IntegralCast;
9398   } else if (vectorEltTy->isRealFloatingType()) {
9399     if (scalarTy->isRealFloatingType()) {
9400       if (S.getLangOpts().OpenCL &&
9401           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9402         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9403         return true;
9404       }
9405       scalarCast = CK_FloatingCast;
9406     }
9407     else if (scalarTy->isIntegralType(S.Context))
9408       scalarCast = CK_IntegralToFloating;
9409     else
9410       return true;
9411   } else {
9412     return true;
9413   }
9414 
9415   // Adjust scalar if desired.
9416   if (scalar) {
9417     if (scalarCast != CK_NoOp)
9418       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9419     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9420   }
9421   return false;
9422 }
9423 
9424 /// Convert vector E to a vector with the same number of elements but different
9425 /// element type.
9426 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9427   const auto *VecTy = E->getType()->getAs<VectorType>();
9428   assert(VecTy && "Expression E must be a vector");
9429   QualType NewVecTy = S.Context.getVectorType(ElementType,
9430                                               VecTy->getNumElements(),
9431                                               VecTy->getVectorKind());
9432 
9433   // Look through the implicit cast. Return the subexpression if its type is
9434   // NewVecTy.
9435   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9436     if (ICE->getSubExpr()->getType() == NewVecTy)
9437       return ICE->getSubExpr();
9438 
9439   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9440   return S.ImpCastExprToType(E, NewVecTy, Cast);
9441 }
9442 
9443 /// Test if a (constant) integer Int can be casted to another integer type
9444 /// IntTy without losing precision.
9445 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9446                                       QualType OtherIntTy) {
9447   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9448 
9449   // Reject cases where the value of the Int is unknown as that would
9450   // possibly cause truncation, but accept cases where the scalar can be
9451   // demoted without loss of precision.
9452   Expr::EvalResult EVResult;
9453   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9454   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9455   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9456   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9457 
9458   if (CstInt) {
9459     // If the scalar is constant and is of a higher order and has more active
9460     // bits that the vector element type, reject it.
9461     llvm::APSInt Result = EVResult.Val.getInt();
9462     unsigned NumBits = IntSigned
9463                            ? (Result.isNegative() ? Result.getMinSignedBits()
9464                                                   : Result.getActiveBits())
9465                            : Result.getActiveBits();
9466     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9467       return true;
9468 
9469     // If the signedness of the scalar type and the vector element type
9470     // differs and the number of bits is greater than that of the vector
9471     // element reject it.
9472     return (IntSigned != OtherIntSigned &&
9473             NumBits > S.Context.getIntWidth(OtherIntTy));
9474   }
9475 
9476   // Reject cases where the value of the scalar is not constant and it's
9477   // order is greater than that of the vector element type.
9478   return (Order < 0);
9479 }
9480 
9481 /// Test if a (constant) integer Int can be casted to floating point type
9482 /// FloatTy without losing precision.
9483 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9484                                      QualType FloatTy) {
9485   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9486 
9487   // Determine if the integer constant can be expressed as a floating point
9488   // number of the appropriate type.
9489   Expr::EvalResult EVResult;
9490   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9491 
9492   uint64_t Bits = 0;
9493   if (CstInt) {
9494     // Reject constants that would be truncated if they were converted to
9495     // the floating point type. Test by simple to/from conversion.
9496     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9497     //        could be avoided if there was a convertFromAPInt method
9498     //        which could signal back if implicit truncation occurred.
9499     llvm::APSInt Result = EVResult.Val.getInt();
9500     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9501     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9502                            llvm::APFloat::rmTowardZero);
9503     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9504                              !IntTy->hasSignedIntegerRepresentation());
9505     bool Ignored = false;
9506     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9507                            &Ignored);
9508     if (Result != ConvertBack)
9509       return true;
9510   } else {
9511     // Reject types that cannot be fully encoded into the mantissa of
9512     // the float.
9513     Bits = S.Context.getTypeSize(IntTy);
9514     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9515         S.Context.getFloatTypeSemantics(FloatTy));
9516     if (Bits > FloatPrec)
9517       return true;
9518   }
9519 
9520   return false;
9521 }
9522 
9523 /// Attempt to convert and splat Scalar into a vector whose types matches
9524 /// Vector following GCC conversion rules. The rule is that implicit
9525 /// conversion can occur when Scalar can be casted to match Vector's element
9526 /// type without causing truncation of Scalar.
9527 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9528                                         ExprResult *Vector) {
9529   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9530   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9531   const VectorType *VT = VectorTy->getAs<VectorType>();
9532 
9533   assert(!isa<ExtVectorType>(VT) &&
9534          "ExtVectorTypes should not be handled here!");
9535 
9536   QualType VectorEltTy = VT->getElementType();
9537 
9538   // Reject cases where the vector element type or the scalar element type are
9539   // not integral or floating point types.
9540   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9541     return true;
9542 
9543   // The conversion to apply to the scalar before splatting it,
9544   // if necessary.
9545   CastKind ScalarCast = CK_NoOp;
9546 
9547   // Accept cases where the vector elements are integers and the scalar is
9548   // an integer.
9549   // FIXME: Notionally if the scalar was a floating point value with a precise
9550   //        integral representation, we could cast it to an appropriate integer
9551   //        type and then perform the rest of the checks here. GCC will perform
9552   //        this conversion in some cases as determined by the input language.
9553   //        We should accept it on a language independent basis.
9554   if (VectorEltTy->isIntegralType(S.Context) &&
9555       ScalarTy->isIntegralType(S.Context) &&
9556       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9557 
9558     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9559       return true;
9560 
9561     ScalarCast = CK_IntegralCast;
9562   } else if (VectorEltTy->isIntegralType(S.Context) &&
9563              ScalarTy->isRealFloatingType()) {
9564     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9565       ScalarCast = CK_FloatingToIntegral;
9566     else
9567       return true;
9568   } else if (VectorEltTy->isRealFloatingType()) {
9569     if (ScalarTy->isRealFloatingType()) {
9570 
9571       // Reject cases where the scalar type is not a constant and has a higher
9572       // Order than the vector element type.
9573       llvm::APFloat Result(0.0);
9574 
9575       // Determine whether this is a constant scalar. In the event that the
9576       // value is dependent (and thus cannot be evaluated by the constant
9577       // evaluator), skip the evaluation. This will then diagnose once the
9578       // expression is instantiated.
9579       bool CstScalar = Scalar->get()->isValueDependent() ||
9580                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9581       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9582       if (!CstScalar && Order < 0)
9583         return true;
9584 
9585       // If the scalar cannot be safely casted to the vector element type,
9586       // reject it.
9587       if (CstScalar) {
9588         bool Truncated = false;
9589         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9590                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9591         if (Truncated)
9592           return true;
9593       }
9594 
9595       ScalarCast = CK_FloatingCast;
9596     } else if (ScalarTy->isIntegralType(S.Context)) {
9597       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9598         return true;
9599 
9600       ScalarCast = CK_IntegralToFloating;
9601     } else
9602       return true;
9603   }
9604 
9605   // Adjust scalar if desired.
9606   if (Scalar) {
9607     if (ScalarCast != CK_NoOp)
9608       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9609     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9610   }
9611   return false;
9612 }
9613 
9614 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9615                                    SourceLocation Loc, bool IsCompAssign,
9616                                    bool AllowBothBool,
9617                                    bool AllowBoolConversions) {
9618   if (!IsCompAssign) {
9619     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9620     if (LHS.isInvalid())
9621       return QualType();
9622   }
9623   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9624   if (RHS.isInvalid())
9625     return QualType();
9626 
9627   // For conversion purposes, we ignore any qualifiers.
9628   // For example, "const float" and "float" are equivalent.
9629   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9630   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9631 
9632   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9633   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9634   assert(LHSVecType || RHSVecType);
9635 
9636   // AltiVec-style "vector bool op vector bool" combinations are allowed
9637   // for some operators but not others.
9638   if (!AllowBothBool &&
9639       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9640       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9641     return InvalidOperands(Loc, LHS, RHS);
9642 
9643   // If the vector types are identical, return.
9644   if (Context.hasSameType(LHSType, RHSType))
9645     return LHSType;
9646 
9647   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9648   if (LHSVecType && RHSVecType &&
9649       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9650     if (isa<ExtVectorType>(LHSVecType)) {
9651       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9652       return LHSType;
9653     }
9654 
9655     if (!IsCompAssign)
9656       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9657     return RHSType;
9658   }
9659 
9660   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9661   // can be mixed, with the result being the non-bool type.  The non-bool
9662   // operand must have integer element type.
9663   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9664       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9665       (Context.getTypeSize(LHSVecType->getElementType()) ==
9666        Context.getTypeSize(RHSVecType->getElementType()))) {
9667     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9668         LHSVecType->getElementType()->isIntegerType() &&
9669         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9670       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9671       return LHSType;
9672     }
9673     if (!IsCompAssign &&
9674         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9675         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9676         RHSVecType->getElementType()->isIntegerType()) {
9677       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9678       return RHSType;
9679     }
9680   }
9681 
9682   // If there's a vector type and a scalar, try to convert the scalar to
9683   // the vector element type and splat.
9684   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9685   if (!RHSVecType) {
9686     if (isa<ExtVectorType>(LHSVecType)) {
9687       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9688                                     LHSVecType->getElementType(), LHSType,
9689                                     DiagID))
9690         return LHSType;
9691     } else {
9692       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9693         return LHSType;
9694     }
9695   }
9696   if (!LHSVecType) {
9697     if (isa<ExtVectorType>(RHSVecType)) {
9698       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9699                                     LHSType, RHSVecType->getElementType(),
9700                                     RHSType, DiagID))
9701         return RHSType;
9702     } else {
9703       if (LHS.get()->getValueKind() == VK_LValue ||
9704           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9705         return RHSType;
9706     }
9707   }
9708 
9709   // FIXME: The code below also handles conversion between vectors and
9710   // non-scalars, we should break this down into fine grained specific checks
9711   // and emit proper diagnostics.
9712   QualType VecType = LHSVecType ? LHSType : RHSType;
9713   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9714   QualType OtherType = LHSVecType ? RHSType : LHSType;
9715   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9716   if (isLaxVectorConversion(OtherType, VecType)) {
9717     // If we're allowing lax vector conversions, only the total (data) size
9718     // needs to be the same. For non compound assignment, if one of the types is
9719     // scalar, the result is always the vector type.
9720     if (!IsCompAssign) {
9721       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9722       return VecType;
9723     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9724     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9725     // type. Note that this is already done by non-compound assignments in
9726     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9727     // <1 x T> -> T. The result is also a vector type.
9728     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9729                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9730       ExprResult *RHSExpr = &RHS;
9731       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9732       return VecType;
9733     }
9734   }
9735 
9736   // Okay, the expression is invalid.
9737 
9738   // If there's a non-vector, non-real operand, diagnose that.
9739   if ((!RHSVecType && !RHSType->isRealType()) ||
9740       (!LHSVecType && !LHSType->isRealType())) {
9741     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9742       << LHSType << RHSType
9743       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9744     return QualType();
9745   }
9746 
9747   // OpenCL V1.1 6.2.6.p1:
9748   // If the operands are of more than one vector type, then an error shall
9749   // occur. Implicit conversions between vector types are not permitted, per
9750   // section 6.2.1.
9751   if (getLangOpts().OpenCL &&
9752       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9753       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9754     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9755                                                            << RHSType;
9756     return QualType();
9757   }
9758 
9759 
9760   // If there is a vector type that is not a ExtVector and a scalar, we reach
9761   // this point if scalar could not be converted to the vector's element type
9762   // without truncation.
9763   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9764       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9765     QualType Scalar = LHSVecType ? RHSType : LHSType;
9766     QualType Vector = LHSVecType ? LHSType : RHSType;
9767     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9768     Diag(Loc,
9769          diag::err_typecheck_vector_not_convertable_implict_truncation)
9770         << ScalarOrVector << Scalar << Vector;
9771 
9772     return QualType();
9773   }
9774 
9775   // Otherwise, use the generic diagnostic.
9776   Diag(Loc, DiagID)
9777     << LHSType << RHSType
9778     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9779   return QualType();
9780 }
9781 
9782 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9783 // expression.  These are mainly cases where the null pointer is used as an
9784 // integer instead of a pointer.
9785 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9786                                 SourceLocation Loc, bool IsCompare) {
9787   // The canonical way to check for a GNU null is with isNullPointerConstant,
9788   // but we use a bit of a hack here for speed; this is a relatively
9789   // hot path, and isNullPointerConstant is slow.
9790   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9791   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9792 
9793   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9794 
9795   // Avoid analyzing cases where the result will either be invalid (and
9796   // diagnosed as such) or entirely valid and not something to warn about.
9797   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9798       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9799     return;
9800 
9801   // Comparison operations would not make sense with a null pointer no matter
9802   // what the other expression is.
9803   if (!IsCompare) {
9804     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9805         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9806         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9807     return;
9808   }
9809 
9810   // The rest of the operations only make sense with a null pointer
9811   // if the other expression is a pointer.
9812   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9813       NonNullType->canDecayToPointerType())
9814     return;
9815 
9816   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9817       << LHSNull /* LHS is NULL */ << NonNullType
9818       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9819 }
9820 
9821 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9822                                           SourceLocation Loc) {
9823   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9824   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9825   if (!LUE || !RUE)
9826     return;
9827   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9828       RUE->getKind() != UETT_SizeOf)
9829     return;
9830 
9831   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9832   QualType LHSTy = LHSArg->getType();
9833   QualType RHSTy;
9834 
9835   if (RUE->isArgumentType())
9836     RHSTy = RUE->getArgumentType();
9837   else
9838     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9839 
9840   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9841     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9842       return;
9843 
9844     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9845     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9846       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9847         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9848             << LHSArgDecl;
9849     }
9850   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9851     QualType ArrayElemTy = ArrayTy->getElementType();
9852     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9853         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9854         ArrayElemTy->isCharType() ||
9855         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9856       return;
9857     S.Diag(Loc, diag::warn_division_sizeof_array)
9858         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9859     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9860       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9861         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9862             << LHSArgDecl;
9863     }
9864 
9865     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9866   }
9867 }
9868 
9869 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9870                                                ExprResult &RHS,
9871                                                SourceLocation Loc, bool IsDiv) {
9872   // Check for division/remainder by zero.
9873   Expr::EvalResult RHSValue;
9874   if (!RHS.get()->isValueDependent() &&
9875       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9876       RHSValue.Val.getInt() == 0)
9877     S.DiagRuntimeBehavior(Loc, RHS.get(),
9878                           S.PDiag(diag::warn_remainder_division_by_zero)
9879                             << IsDiv << RHS.get()->getSourceRange());
9880 }
9881 
9882 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9883                                            SourceLocation Loc,
9884                                            bool IsCompAssign, bool IsDiv) {
9885   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9886 
9887   if (LHS.get()->getType()->isVectorType() ||
9888       RHS.get()->getType()->isVectorType())
9889     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9890                                /*AllowBothBool*/getLangOpts().AltiVec,
9891                                /*AllowBoolConversions*/false);
9892 
9893   QualType compType = UsualArithmeticConversions(
9894       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9895   if (LHS.isInvalid() || RHS.isInvalid())
9896     return QualType();
9897 
9898 
9899   if (compType.isNull() || !compType->isArithmeticType())
9900     return InvalidOperands(Loc, LHS, RHS);
9901   if (IsDiv) {
9902     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9903     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9904   }
9905   return compType;
9906 }
9907 
9908 QualType Sema::CheckRemainderOperands(
9909   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9910   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9911 
9912   if (LHS.get()->getType()->isVectorType() ||
9913       RHS.get()->getType()->isVectorType()) {
9914     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9915         RHS.get()->getType()->hasIntegerRepresentation())
9916       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9917                                  /*AllowBothBool*/getLangOpts().AltiVec,
9918                                  /*AllowBoolConversions*/false);
9919     return InvalidOperands(Loc, LHS, RHS);
9920   }
9921 
9922   QualType compType = UsualArithmeticConversions(
9923       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9924   if (LHS.isInvalid() || RHS.isInvalid())
9925     return QualType();
9926 
9927   if (compType.isNull() || !compType->isIntegerType())
9928     return InvalidOperands(Loc, LHS, RHS);
9929   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9930   return compType;
9931 }
9932 
9933 /// Diagnose invalid arithmetic on two void pointers.
9934 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9935                                                 Expr *LHSExpr, Expr *RHSExpr) {
9936   S.Diag(Loc, S.getLangOpts().CPlusPlus
9937                 ? diag::err_typecheck_pointer_arith_void_type
9938                 : diag::ext_gnu_void_ptr)
9939     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9940                             << RHSExpr->getSourceRange();
9941 }
9942 
9943 /// Diagnose invalid arithmetic on a void pointer.
9944 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9945                                             Expr *Pointer) {
9946   S.Diag(Loc, S.getLangOpts().CPlusPlus
9947                 ? diag::err_typecheck_pointer_arith_void_type
9948                 : diag::ext_gnu_void_ptr)
9949     << 0 /* one pointer */ << Pointer->getSourceRange();
9950 }
9951 
9952 /// Diagnose invalid arithmetic on a null pointer.
9953 ///
9954 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9955 /// idiom, which we recognize as a GNU extension.
9956 ///
9957 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9958                                             Expr *Pointer, bool IsGNUIdiom) {
9959   if (IsGNUIdiom)
9960     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9961       << Pointer->getSourceRange();
9962   else
9963     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9964       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9965 }
9966 
9967 /// Diagnose invalid arithmetic on two function pointers.
9968 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9969                                                     Expr *LHS, Expr *RHS) {
9970   assert(LHS->getType()->isAnyPointerType());
9971   assert(RHS->getType()->isAnyPointerType());
9972   S.Diag(Loc, S.getLangOpts().CPlusPlus
9973                 ? diag::err_typecheck_pointer_arith_function_type
9974                 : diag::ext_gnu_ptr_func_arith)
9975     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9976     // We only show the second type if it differs from the first.
9977     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9978                                                    RHS->getType())
9979     << RHS->getType()->getPointeeType()
9980     << LHS->getSourceRange() << RHS->getSourceRange();
9981 }
9982 
9983 /// Diagnose invalid arithmetic on a function pointer.
9984 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9985                                                 Expr *Pointer) {
9986   assert(Pointer->getType()->isAnyPointerType());
9987   S.Diag(Loc, S.getLangOpts().CPlusPlus
9988                 ? diag::err_typecheck_pointer_arith_function_type
9989                 : diag::ext_gnu_ptr_func_arith)
9990     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9991     << 0 /* one pointer, so only one type */
9992     << Pointer->getSourceRange();
9993 }
9994 
9995 /// Emit error if Operand is incomplete pointer type
9996 ///
9997 /// \returns True if pointer has incomplete type
9998 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9999                                                  Expr *Operand) {
10000   QualType ResType = Operand->getType();
10001   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10002     ResType = ResAtomicType->getValueType();
10003 
10004   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10005   QualType PointeeTy = ResType->getPointeeType();
10006   return S.RequireCompleteSizedType(
10007       Loc, PointeeTy,
10008       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10009       Operand->getSourceRange());
10010 }
10011 
10012 /// Check the validity of an arithmetic pointer operand.
10013 ///
10014 /// If the operand has pointer type, this code will check for pointer types
10015 /// which are invalid in arithmetic operations. These will be diagnosed
10016 /// appropriately, including whether or not the use is supported as an
10017 /// extension.
10018 ///
10019 /// \returns True when the operand is valid to use (even if as an extension).
10020 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10021                                             Expr *Operand) {
10022   QualType ResType = Operand->getType();
10023   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10024     ResType = ResAtomicType->getValueType();
10025 
10026   if (!ResType->isAnyPointerType()) return true;
10027 
10028   QualType PointeeTy = ResType->getPointeeType();
10029   if (PointeeTy->isVoidType()) {
10030     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10031     return !S.getLangOpts().CPlusPlus;
10032   }
10033   if (PointeeTy->isFunctionType()) {
10034     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10035     return !S.getLangOpts().CPlusPlus;
10036   }
10037 
10038   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10039 
10040   return true;
10041 }
10042 
10043 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10044 /// operands.
10045 ///
10046 /// This routine will diagnose any invalid arithmetic on pointer operands much
10047 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10048 /// for emitting a single diagnostic even for operations where both LHS and RHS
10049 /// are (potentially problematic) pointers.
10050 ///
10051 /// \returns True when the operand is valid to use (even if as an extension).
10052 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10053                                                 Expr *LHSExpr, Expr *RHSExpr) {
10054   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10055   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10056   if (!isLHSPointer && !isRHSPointer) return true;
10057 
10058   QualType LHSPointeeTy, RHSPointeeTy;
10059   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10060   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10061 
10062   // if both are pointers check if operation is valid wrt address spaces
10063   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
10064     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
10065     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
10066     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
10067       S.Diag(Loc,
10068              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10069           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10070           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10071       return false;
10072     }
10073   }
10074 
10075   // Check for arithmetic on pointers to incomplete types.
10076   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10077   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10078   if (isLHSVoidPtr || isRHSVoidPtr) {
10079     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10080     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10081     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10082 
10083     return !S.getLangOpts().CPlusPlus;
10084   }
10085 
10086   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10087   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10088   if (isLHSFuncPtr || isRHSFuncPtr) {
10089     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10090     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10091                                                                 RHSExpr);
10092     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10093 
10094     return !S.getLangOpts().CPlusPlus;
10095   }
10096 
10097   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10098     return false;
10099   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10100     return false;
10101 
10102   return true;
10103 }
10104 
10105 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10106 /// literal.
10107 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10108                                   Expr *LHSExpr, Expr *RHSExpr) {
10109   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10110   Expr* IndexExpr = RHSExpr;
10111   if (!StrExpr) {
10112     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10113     IndexExpr = LHSExpr;
10114   }
10115 
10116   bool IsStringPlusInt = StrExpr &&
10117       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10118   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10119     return;
10120 
10121   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10122   Self.Diag(OpLoc, diag::warn_string_plus_int)
10123       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10124 
10125   // Only print a fixit for "str" + int, not for int + "str".
10126   if (IndexExpr == RHSExpr) {
10127     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10128     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10129         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10130         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10131         << FixItHint::CreateInsertion(EndLoc, "]");
10132   } else
10133     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10134 }
10135 
10136 /// Emit a warning when adding a char literal to a string.
10137 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10138                                    Expr *LHSExpr, Expr *RHSExpr) {
10139   const Expr *StringRefExpr = LHSExpr;
10140   const CharacterLiteral *CharExpr =
10141       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10142 
10143   if (!CharExpr) {
10144     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10145     StringRefExpr = RHSExpr;
10146   }
10147 
10148   if (!CharExpr || !StringRefExpr)
10149     return;
10150 
10151   const QualType StringType = StringRefExpr->getType();
10152 
10153   // Return if not a PointerType.
10154   if (!StringType->isAnyPointerType())
10155     return;
10156 
10157   // Return if not a CharacterType.
10158   if (!StringType->getPointeeType()->isAnyCharacterType())
10159     return;
10160 
10161   ASTContext &Ctx = Self.getASTContext();
10162   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10163 
10164   const QualType CharType = CharExpr->getType();
10165   if (!CharType->isAnyCharacterType() &&
10166       CharType->isIntegerType() &&
10167       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10168     Self.Diag(OpLoc, diag::warn_string_plus_char)
10169         << DiagRange << Ctx.CharTy;
10170   } else {
10171     Self.Diag(OpLoc, diag::warn_string_plus_char)
10172         << DiagRange << CharExpr->getType();
10173   }
10174 
10175   // Only print a fixit for str + char, not for char + str.
10176   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10177     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10178     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10179         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10180         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10181         << FixItHint::CreateInsertion(EndLoc, "]");
10182   } else {
10183     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10184   }
10185 }
10186 
10187 /// Emit error when two pointers are incompatible.
10188 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10189                                            Expr *LHSExpr, Expr *RHSExpr) {
10190   assert(LHSExpr->getType()->isAnyPointerType());
10191   assert(RHSExpr->getType()->isAnyPointerType());
10192   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10193     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10194     << RHSExpr->getSourceRange();
10195 }
10196 
10197 // C99 6.5.6
10198 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10199                                      SourceLocation Loc, BinaryOperatorKind Opc,
10200                                      QualType* CompLHSTy) {
10201   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10202 
10203   if (LHS.get()->getType()->isVectorType() ||
10204       RHS.get()->getType()->isVectorType()) {
10205     QualType compType = CheckVectorOperands(
10206         LHS, RHS, Loc, CompLHSTy,
10207         /*AllowBothBool*/getLangOpts().AltiVec,
10208         /*AllowBoolConversions*/getLangOpts().ZVector);
10209     if (CompLHSTy) *CompLHSTy = compType;
10210     return compType;
10211   }
10212 
10213   QualType compType = UsualArithmeticConversions(
10214       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10215   if (LHS.isInvalid() || RHS.isInvalid())
10216     return QualType();
10217 
10218   // Diagnose "string literal" '+' int and string '+' "char literal".
10219   if (Opc == BO_Add) {
10220     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10221     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10222   }
10223 
10224   // handle the common case first (both operands are arithmetic).
10225   if (!compType.isNull() && compType->isArithmeticType()) {
10226     if (CompLHSTy) *CompLHSTy = compType;
10227     return compType;
10228   }
10229 
10230   // Type-checking.  Ultimately the pointer's going to be in PExp;
10231   // note that we bias towards the LHS being the pointer.
10232   Expr *PExp = LHS.get(), *IExp = RHS.get();
10233 
10234   bool isObjCPointer;
10235   if (PExp->getType()->isPointerType()) {
10236     isObjCPointer = false;
10237   } else if (PExp->getType()->isObjCObjectPointerType()) {
10238     isObjCPointer = true;
10239   } else {
10240     std::swap(PExp, IExp);
10241     if (PExp->getType()->isPointerType()) {
10242       isObjCPointer = false;
10243     } else if (PExp->getType()->isObjCObjectPointerType()) {
10244       isObjCPointer = true;
10245     } else {
10246       return InvalidOperands(Loc, LHS, RHS);
10247     }
10248   }
10249   assert(PExp->getType()->isAnyPointerType());
10250 
10251   if (!IExp->getType()->isIntegerType())
10252     return InvalidOperands(Loc, LHS, RHS);
10253 
10254   // Adding to a null pointer results in undefined behavior.
10255   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10256           Context, Expr::NPC_ValueDependentIsNotNull)) {
10257     // In C++ adding zero to a null pointer is defined.
10258     Expr::EvalResult KnownVal;
10259     if (!getLangOpts().CPlusPlus ||
10260         (!IExp->isValueDependent() &&
10261          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10262           KnownVal.Val.getInt() != 0))) {
10263       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10264       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10265           Context, BO_Add, PExp, IExp);
10266       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10267     }
10268   }
10269 
10270   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10271     return QualType();
10272 
10273   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10274     return QualType();
10275 
10276   // Check array bounds for pointer arithemtic
10277   CheckArrayAccess(PExp, IExp);
10278 
10279   if (CompLHSTy) {
10280     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10281     if (LHSTy.isNull()) {
10282       LHSTy = LHS.get()->getType();
10283       if (LHSTy->isPromotableIntegerType())
10284         LHSTy = Context.getPromotedIntegerType(LHSTy);
10285     }
10286     *CompLHSTy = LHSTy;
10287   }
10288 
10289   return PExp->getType();
10290 }
10291 
10292 // C99 6.5.6
10293 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10294                                         SourceLocation Loc,
10295                                         QualType* CompLHSTy) {
10296   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10297 
10298   if (LHS.get()->getType()->isVectorType() ||
10299       RHS.get()->getType()->isVectorType()) {
10300     QualType compType = CheckVectorOperands(
10301         LHS, RHS, Loc, CompLHSTy,
10302         /*AllowBothBool*/getLangOpts().AltiVec,
10303         /*AllowBoolConversions*/getLangOpts().ZVector);
10304     if (CompLHSTy) *CompLHSTy = compType;
10305     return compType;
10306   }
10307 
10308   QualType compType = UsualArithmeticConversions(
10309       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10310   if (LHS.isInvalid() || RHS.isInvalid())
10311     return QualType();
10312 
10313   // Enforce type constraints: C99 6.5.6p3.
10314 
10315   // Handle the common case first (both operands are arithmetic).
10316   if (!compType.isNull() && compType->isArithmeticType()) {
10317     if (CompLHSTy) *CompLHSTy = compType;
10318     return compType;
10319   }
10320 
10321   // Either ptr - int   or   ptr - ptr.
10322   if (LHS.get()->getType()->isAnyPointerType()) {
10323     QualType lpointee = LHS.get()->getType()->getPointeeType();
10324 
10325     // Diagnose bad cases where we step over interface counts.
10326     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10327         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10328       return QualType();
10329 
10330     // The result type of a pointer-int computation is the pointer type.
10331     if (RHS.get()->getType()->isIntegerType()) {
10332       // Subtracting from a null pointer should produce a warning.
10333       // The last argument to the diagnose call says this doesn't match the
10334       // GNU int-to-pointer idiom.
10335       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10336                                            Expr::NPC_ValueDependentIsNotNull)) {
10337         // In C++ adding zero to a null pointer is defined.
10338         Expr::EvalResult KnownVal;
10339         if (!getLangOpts().CPlusPlus ||
10340             (!RHS.get()->isValueDependent() &&
10341              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10342               KnownVal.Val.getInt() != 0))) {
10343           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10344         }
10345       }
10346 
10347       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10348         return QualType();
10349 
10350       // Check array bounds for pointer arithemtic
10351       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10352                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10353 
10354       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10355       return LHS.get()->getType();
10356     }
10357 
10358     // Handle pointer-pointer subtractions.
10359     if (const PointerType *RHSPTy
10360           = RHS.get()->getType()->getAs<PointerType>()) {
10361       QualType rpointee = RHSPTy->getPointeeType();
10362 
10363       if (getLangOpts().CPlusPlus) {
10364         // Pointee types must be the same: C++ [expr.add]
10365         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10366           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10367         }
10368       } else {
10369         // Pointee types must be compatible C99 6.5.6p3
10370         if (!Context.typesAreCompatible(
10371                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10372                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10373           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10374           return QualType();
10375         }
10376       }
10377 
10378       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10379                                                LHS.get(), RHS.get()))
10380         return QualType();
10381 
10382       // FIXME: Add warnings for nullptr - ptr.
10383 
10384       // The pointee type may have zero size.  As an extension, a structure or
10385       // union may have zero size or an array may have zero length.  In this
10386       // case subtraction does not make sense.
10387       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10388         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10389         if (ElementSize.isZero()) {
10390           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10391             << rpointee.getUnqualifiedType()
10392             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10393         }
10394       }
10395 
10396       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10397       return Context.getPointerDiffType();
10398     }
10399   }
10400 
10401   return InvalidOperands(Loc, LHS, RHS);
10402 }
10403 
10404 static bool isScopedEnumerationType(QualType T) {
10405   if (const EnumType *ET = T->getAs<EnumType>())
10406     return ET->getDecl()->isScoped();
10407   return false;
10408 }
10409 
10410 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10411                                    SourceLocation Loc, BinaryOperatorKind Opc,
10412                                    QualType LHSType) {
10413   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10414   // so skip remaining warnings as we don't want to modify values within Sema.
10415   if (S.getLangOpts().OpenCL)
10416     return;
10417 
10418   // Check right/shifter operand
10419   Expr::EvalResult RHSResult;
10420   if (RHS.get()->isValueDependent() ||
10421       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10422     return;
10423   llvm::APSInt Right = RHSResult.Val.getInt();
10424 
10425   if (Right.isNegative()) {
10426     S.DiagRuntimeBehavior(Loc, RHS.get(),
10427                           S.PDiag(diag::warn_shift_negative)
10428                             << RHS.get()->getSourceRange());
10429     return;
10430   }
10431   llvm::APInt LeftBits(Right.getBitWidth(),
10432                        S.Context.getTypeSize(LHS.get()->getType()));
10433   if (Right.uge(LeftBits)) {
10434     S.DiagRuntimeBehavior(Loc, RHS.get(),
10435                           S.PDiag(diag::warn_shift_gt_typewidth)
10436                             << RHS.get()->getSourceRange());
10437     return;
10438   }
10439   if (Opc != BO_Shl)
10440     return;
10441 
10442   // When left shifting an ICE which is signed, we can check for overflow which
10443   // according to C++ standards prior to C++2a has undefined behavior
10444   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10445   // more than the maximum value representable in the result type, so never
10446   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10447   // expression is still probably a bug.)
10448   Expr::EvalResult LHSResult;
10449   if (LHS.get()->isValueDependent() ||
10450       LHSType->hasUnsignedIntegerRepresentation() ||
10451       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10452     return;
10453   llvm::APSInt Left = LHSResult.Val.getInt();
10454 
10455   // If LHS does not have a signed type and non-negative value
10456   // then, the behavior is undefined before C++2a. Warn about it.
10457   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10458       !S.getLangOpts().CPlusPlus2a) {
10459     S.DiagRuntimeBehavior(Loc, LHS.get(),
10460                           S.PDiag(diag::warn_shift_lhs_negative)
10461                             << LHS.get()->getSourceRange());
10462     return;
10463   }
10464 
10465   llvm::APInt ResultBits =
10466       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10467   if (LeftBits.uge(ResultBits))
10468     return;
10469   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10470   Result = Result.shl(Right);
10471 
10472   // Print the bit representation of the signed integer as an unsigned
10473   // hexadecimal number.
10474   SmallString<40> HexResult;
10475   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10476 
10477   // If we are only missing a sign bit, this is less likely to result in actual
10478   // bugs -- if the result is cast back to an unsigned type, it will have the
10479   // expected value. Thus we place this behind a different warning that can be
10480   // turned off separately if needed.
10481   if (LeftBits == ResultBits - 1) {
10482     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10483         << HexResult << LHSType
10484         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10485     return;
10486   }
10487 
10488   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10489     << HexResult.str() << Result.getMinSignedBits() << LHSType
10490     << Left.getBitWidth() << LHS.get()->getSourceRange()
10491     << RHS.get()->getSourceRange();
10492 }
10493 
10494 /// Return the resulting type when a vector is shifted
10495 ///        by a scalar or vector shift amount.
10496 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10497                                  SourceLocation Loc, bool IsCompAssign) {
10498   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10499   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10500       !LHS.get()->getType()->isVectorType()) {
10501     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10502       << RHS.get()->getType() << LHS.get()->getType()
10503       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10504     return QualType();
10505   }
10506 
10507   if (!IsCompAssign) {
10508     LHS = S.UsualUnaryConversions(LHS.get());
10509     if (LHS.isInvalid()) return QualType();
10510   }
10511 
10512   RHS = S.UsualUnaryConversions(RHS.get());
10513   if (RHS.isInvalid()) return QualType();
10514 
10515   QualType LHSType = LHS.get()->getType();
10516   // Note that LHS might be a scalar because the routine calls not only in
10517   // OpenCL case.
10518   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10519   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10520 
10521   // Note that RHS might not be a vector.
10522   QualType RHSType = RHS.get()->getType();
10523   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10524   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10525 
10526   // The operands need to be integers.
10527   if (!LHSEleType->isIntegerType()) {
10528     S.Diag(Loc, diag::err_typecheck_expect_int)
10529       << LHS.get()->getType() << LHS.get()->getSourceRange();
10530     return QualType();
10531   }
10532 
10533   if (!RHSEleType->isIntegerType()) {
10534     S.Diag(Loc, diag::err_typecheck_expect_int)
10535       << RHS.get()->getType() << RHS.get()->getSourceRange();
10536     return QualType();
10537   }
10538 
10539   if (!LHSVecTy) {
10540     assert(RHSVecTy);
10541     if (IsCompAssign)
10542       return RHSType;
10543     if (LHSEleType != RHSEleType) {
10544       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10545       LHSEleType = RHSEleType;
10546     }
10547     QualType VecTy =
10548         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10549     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10550     LHSType = VecTy;
10551   } else if (RHSVecTy) {
10552     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10553     // are applied component-wise. So if RHS is a vector, then ensure
10554     // that the number of elements is the same as LHS...
10555     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10556       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10557         << LHS.get()->getType() << RHS.get()->getType()
10558         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10559       return QualType();
10560     }
10561     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10562       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10563       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10564       if (LHSBT != RHSBT &&
10565           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10566         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10567             << LHS.get()->getType() << RHS.get()->getType()
10568             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10569       }
10570     }
10571   } else {
10572     // ...else expand RHS to match the number of elements in LHS.
10573     QualType VecTy =
10574       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10575     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10576   }
10577 
10578   return LHSType;
10579 }
10580 
10581 // C99 6.5.7
10582 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10583                                   SourceLocation Loc, BinaryOperatorKind Opc,
10584                                   bool IsCompAssign) {
10585   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10586 
10587   // Vector shifts promote their scalar inputs to vector type.
10588   if (LHS.get()->getType()->isVectorType() ||
10589       RHS.get()->getType()->isVectorType()) {
10590     if (LangOpts.ZVector) {
10591       // The shift operators for the z vector extensions work basically
10592       // like general shifts, except that neither the LHS nor the RHS is
10593       // allowed to be a "vector bool".
10594       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10595         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10596           return InvalidOperands(Loc, LHS, RHS);
10597       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10598         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10599           return InvalidOperands(Loc, LHS, RHS);
10600     }
10601     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10602   }
10603 
10604   // Shifts don't perform usual arithmetic conversions, they just do integer
10605   // promotions on each operand. C99 6.5.7p3
10606 
10607   // For the LHS, do usual unary conversions, but then reset them away
10608   // if this is a compound assignment.
10609   ExprResult OldLHS = LHS;
10610   LHS = UsualUnaryConversions(LHS.get());
10611   if (LHS.isInvalid())
10612     return QualType();
10613   QualType LHSType = LHS.get()->getType();
10614   if (IsCompAssign) LHS = OldLHS;
10615 
10616   // The RHS is simpler.
10617   RHS = UsualUnaryConversions(RHS.get());
10618   if (RHS.isInvalid())
10619     return QualType();
10620   QualType RHSType = RHS.get()->getType();
10621 
10622   // C99 6.5.7p2: Each of the operands shall have integer type.
10623   if (!LHSType->hasIntegerRepresentation() ||
10624       !RHSType->hasIntegerRepresentation())
10625     return InvalidOperands(Loc, LHS, RHS);
10626 
10627   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10628   // hasIntegerRepresentation() above instead of this.
10629   if (isScopedEnumerationType(LHSType) ||
10630       isScopedEnumerationType(RHSType)) {
10631     return InvalidOperands(Loc, LHS, RHS);
10632   }
10633   // Sanity-check shift operands
10634   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10635 
10636   // "The type of the result is that of the promoted left operand."
10637   return LHSType;
10638 }
10639 
10640 /// Diagnose bad pointer comparisons.
10641 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10642                                               ExprResult &LHS, ExprResult &RHS,
10643                                               bool IsError) {
10644   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10645                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10646     << LHS.get()->getType() << RHS.get()->getType()
10647     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10648 }
10649 
10650 /// Returns false if the pointers are converted to a composite type,
10651 /// true otherwise.
10652 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10653                                            ExprResult &LHS, ExprResult &RHS) {
10654   // C++ [expr.rel]p2:
10655   //   [...] Pointer conversions (4.10) and qualification
10656   //   conversions (4.4) are performed on pointer operands (or on
10657   //   a pointer operand and a null pointer constant) to bring
10658   //   them to their composite pointer type. [...]
10659   //
10660   // C++ [expr.eq]p1 uses the same notion for (in)equality
10661   // comparisons of pointers.
10662 
10663   QualType LHSType = LHS.get()->getType();
10664   QualType RHSType = RHS.get()->getType();
10665   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10666          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10667 
10668   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10669   if (T.isNull()) {
10670     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10671         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10672       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10673     else
10674       S.InvalidOperands(Loc, LHS, RHS);
10675     return true;
10676   }
10677 
10678   return false;
10679 }
10680 
10681 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10682                                                     ExprResult &LHS,
10683                                                     ExprResult &RHS,
10684                                                     bool IsError) {
10685   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10686                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10687     << LHS.get()->getType() << RHS.get()->getType()
10688     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10689 }
10690 
10691 static bool isObjCObjectLiteral(ExprResult &E) {
10692   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10693   case Stmt::ObjCArrayLiteralClass:
10694   case Stmt::ObjCDictionaryLiteralClass:
10695   case Stmt::ObjCStringLiteralClass:
10696   case Stmt::ObjCBoxedExprClass:
10697     return true;
10698   default:
10699     // Note that ObjCBoolLiteral is NOT an object literal!
10700     return false;
10701   }
10702 }
10703 
10704 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10705   const ObjCObjectPointerType *Type =
10706     LHS->getType()->getAs<ObjCObjectPointerType>();
10707 
10708   // If this is not actually an Objective-C object, bail out.
10709   if (!Type)
10710     return false;
10711 
10712   // Get the LHS object's interface type.
10713   QualType InterfaceType = Type->getPointeeType();
10714 
10715   // If the RHS isn't an Objective-C object, bail out.
10716   if (!RHS->getType()->isObjCObjectPointerType())
10717     return false;
10718 
10719   // Try to find the -isEqual: method.
10720   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10721   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10722                                                       InterfaceType,
10723                                                       /*IsInstance=*/true);
10724   if (!Method) {
10725     if (Type->isObjCIdType()) {
10726       // For 'id', just check the global pool.
10727       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10728                                                   /*receiverId=*/true);
10729     } else {
10730       // Check protocols.
10731       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10732                                              /*IsInstance=*/true);
10733     }
10734   }
10735 
10736   if (!Method)
10737     return false;
10738 
10739   QualType T = Method->parameters()[0]->getType();
10740   if (!T->isObjCObjectPointerType())
10741     return false;
10742 
10743   QualType R = Method->getReturnType();
10744   if (!R->isScalarType())
10745     return false;
10746 
10747   return true;
10748 }
10749 
10750 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10751   FromE = FromE->IgnoreParenImpCasts();
10752   switch (FromE->getStmtClass()) {
10753     default:
10754       break;
10755     case Stmt::ObjCStringLiteralClass:
10756       // "string literal"
10757       return LK_String;
10758     case Stmt::ObjCArrayLiteralClass:
10759       // "array literal"
10760       return LK_Array;
10761     case Stmt::ObjCDictionaryLiteralClass:
10762       // "dictionary literal"
10763       return LK_Dictionary;
10764     case Stmt::BlockExprClass:
10765       return LK_Block;
10766     case Stmt::ObjCBoxedExprClass: {
10767       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10768       switch (Inner->getStmtClass()) {
10769         case Stmt::IntegerLiteralClass:
10770         case Stmt::FloatingLiteralClass:
10771         case Stmt::CharacterLiteralClass:
10772         case Stmt::ObjCBoolLiteralExprClass:
10773         case Stmt::CXXBoolLiteralExprClass:
10774           // "numeric literal"
10775           return LK_Numeric;
10776         case Stmt::ImplicitCastExprClass: {
10777           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10778           // Boolean literals can be represented by implicit casts.
10779           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10780             return LK_Numeric;
10781           break;
10782         }
10783         default:
10784           break;
10785       }
10786       return LK_Boxed;
10787     }
10788   }
10789   return LK_None;
10790 }
10791 
10792 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10793                                           ExprResult &LHS, ExprResult &RHS,
10794                                           BinaryOperator::Opcode Opc){
10795   Expr *Literal;
10796   Expr *Other;
10797   if (isObjCObjectLiteral(LHS)) {
10798     Literal = LHS.get();
10799     Other = RHS.get();
10800   } else {
10801     Literal = RHS.get();
10802     Other = LHS.get();
10803   }
10804 
10805   // Don't warn on comparisons against nil.
10806   Other = Other->IgnoreParenCasts();
10807   if (Other->isNullPointerConstant(S.getASTContext(),
10808                                    Expr::NPC_ValueDependentIsNotNull))
10809     return;
10810 
10811   // This should be kept in sync with warn_objc_literal_comparison.
10812   // LK_String should always be after the other literals, since it has its own
10813   // warning flag.
10814   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10815   assert(LiteralKind != Sema::LK_Block);
10816   if (LiteralKind == Sema::LK_None) {
10817     llvm_unreachable("Unknown Objective-C object literal kind");
10818   }
10819 
10820   if (LiteralKind == Sema::LK_String)
10821     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10822       << Literal->getSourceRange();
10823   else
10824     S.Diag(Loc, diag::warn_objc_literal_comparison)
10825       << LiteralKind << Literal->getSourceRange();
10826 
10827   if (BinaryOperator::isEqualityOp(Opc) &&
10828       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10829     SourceLocation Start = LHS.get()->getBeginLoc();
10830     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10831     CharSourceRange OpRange =
10832       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10833 
10834     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10835       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10836       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10837       << FixItHint::CreateInsertion(End, "]");
10838   }
10839 }
10840 
10841 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10842 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10843                                            ExprResult &RHS, SourceLocation Loc,
10844                                            BinaryOperatorKind Opc) {
10845   // Check that left hand side is !something.
10846   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10847   if (!UO || UO->getOpcode() != UO_LNot) return;
10848 
10849   // Only check if the right hand side is non-bool arithmetic type.
10850   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10851 
10852   // Make sure that the something in !something is not bool.
10853   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10854   if (SubExpr->isKnownToHaveBooleanValue()) return;
10855 
10856   // Emit warning.
10857   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10858   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10859       << Loc << IsBitwiseOp;
10860 
10861   // First note suggest !(x < y)
10862   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10863   SourceLocation FirstClose = RHS.get()->getEndLoc();
10864   FirstClose = S.getLocForEndOfToken(FirstClose);
10865   if (FirstClose.isInvalid())
10866     FirstOpen = SourceLocation();
10867   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10868       << IsBitwiseOp
10869       << FixItHint::CreateInsertion(FirstOpen, "(")
10870       << FixItHint::CreateInsertion(FirstClose, ")");
10871 
10872   // Second note suggests (!x) < y
10873   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10874   SourceLocation SecondClose = LHS.get()->getEndLoc();
10875   SecondClose = S.getLocForEndOfToken(SecondClose);
10876   if (SecondClose.isInvalid())
10877     SecondOpen = SourceLocation();
10878   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10879       << FixItHint::CreateInsertion(SecondOpen, "(")
10880       << FixItHint::CreateInsertion(SecondClose, ")");
10881 }
10882 
10883 // Returns true if E refers to a non-weak array.
10884 static bool checkForArray(const Expr *E) {
10885   const ValueDecl *D = nullptr;
10886   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10887     D = DR->getDecl();
10888   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10889     if (Mem->isImplicitAccess())
10890       D = Mem->getMemberDecl();
10891   }
10892   if (!D)
10893     return false;
10894   return D->getType()->isArrayType() && !D->isWeak();
10895 }
10896 
10897 /// Diagnose some forms of syntactically-obvious tautological comparison.
10898 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10899                                            Expr *LHS, Expr *RHS,
10900                                            BinaryOperatorKind Opc) {
10901   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10902   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10903 
10904   QualType LHSType = LHS->getType();
10905   QualType RHSType = RHS->getType();
10906   if (LHSType->hasFloatingRepresentation() ||
10907       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10908       S.inTemplateInstantiation())
10909     return;
10910 
10911   // Comparisons between two array types are ill-formed for operator<=>, so
10912   // we shouldn't emit any additional warnings about it.
10913   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10914     return;
10915 
10916   // For non-floating point types, check for self-comparisons of the form
10917   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10918   // often indicate logic errors in the program.
10919   //
10920   // NOTE: Don't warn about comparison expressions resulting from macro
10921   // expansion. Also don't warn about comparisons which are only self
10922   // comparisons within a template instantiation. The warnings should catch
10923   // obvious cases in the definition of the template anyways. The idea is to
10924   // warn when the typed comparison operator will always evaluate to the same
10925   // result.
10926 
10927   // Used for indexing into %select in warn_comparison_always
10928   enum {
10929     AlwaysConstant,
10930     AlwaysTrue,
10931     AlwaysFalse,
10932     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10933   };
10934 
10935   // C++2a [depr.array.comp]:
10936   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10937   //   operands of array type are deprecated.
10938   if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10939       RHSStripped->getType()->isArrayType()) {
10940     S.Diag(Loc, diag::warn_depr_array_comparison)
10941         << LHS->getSourceRange() << RHS->getSourceRange()
10942         << LHSStripped->getType() << RHSStripped->getType();
10943     // Carry on to produce the tautological comparison warning, if this
10944     // expression is potentially-evaluated, we can resolve the array to a
10945     // non-weak declaration, and so on.
10946   }
10947 
10948   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10949     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10950       unsigned Result;
10951       switch (Opc) {
10952       case BO_EQ:
10953       case BO_LE:
10954       case BO_GE:
10955         Result = AlwaysTrue;
10956         break;
10957       case BO_NE:
10958       case BO_LT:
10959       case BO_GT:
10960         Result = AlwaysFalse;
10961         break;
10962       case BO_Cmp:
10963         Result = AlwaysEqual;
10964         break;
10965       default:
10966         Result = AlwaysConstant;
10967         break;
10968       }
10969       S.DiagRuntimeBehavior(Loc, nullptr,
10970                             S.PDiag(diag::warn_comparison_always)
10971                                 << 0 /*self-comparison*/
10972                                 << Result);
10973     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10974       // What is it always going to evaluate to?
10975       unsigned Result;
10976       switch (Opc) {
10977       case BO_EQ: // e.g. array1 == array2
10978         Result = AlwaysFalse;
10979         break;
10980       case BO_NE: // e.g. array1 != array2
10981         Result = AlwaysTrue;
10982         break;
10983       default: // e.g. array1 <= array2
10984         // The best we can say is 'a constant'
10985         Result = AlwaysConstant;
10986         break;
10987       }
10988       S.DiagRuntimeBehavior(Loc, nullptr,
10989                             S.PDiag(diag::warn_comparison_always)
10990                                 << 1 /*array comparison*/
10991                                 << Result);
10992     }
10993   }
10994 
10995   if (isa<CastExpr>(LHSStripped))
10996     LHSStripped = LHSStripped->IgnoreParenCasts();
10997   if (isa<CastExpr>(RHSStripped))
10998     RHSStripped = RHSStripped->IgnoreParenCasts();
10999 
11000   // Warn about comparisons against a string constant (unless the other
11001   // operand is null); the user probably wants string comparison function.
11002   Expr *LiteralString = nullptr;
11003   Expr *LiteralStringStripped = nullptr;
11004   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11005       !RHSStripped->isNullPointerConstant(S.Context,
11006                                           Expr::NPC_ValueDependentIsNull)) {
11007     LiteralString = LHS;
11008     LiteralStringStripped = LHSStripped;
11009   } else if ((isa<StringLiteral>(RHSStripped) ||
11010               isa<ObjCEncodeExpr>(RHSStripped)) &&
11011              !LHSStripped->isNullPointerConstant(S.Context,
11012                                           Expr::NPC_ValueDependentIsNull)) {
11013     LiteralString = RHS;
11014     LiteralStringStripped = RHSStripped;
11015   }
11016 
11017   if (LiteralString) {
11018     S.DiagRuntimeBehavior(Loc, nullptr,
11019                           S.PDiag(diag::warn_stringcompare)
11020                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11021                               << LiteralString->getSourceRange());
11022   }
11023 }
11024 
11025 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11026   switch (CK) {
11027   default: {
11028 #ifndef NDEBUG
11029     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11030                  << "\n";
11031 #endif
11032     llvm_unreachable("unhandled cast kind");
11033   }
11034   case CK_UserDefinedConversion:
11035     return ICK_Identity;
11036   case CK_LValueToRValue:
11037     return ICK_Lvalue_To_Rvalue;
11038   case CK_ArrayToPointerDecay:
11039     return ICK_Array_To_Pointer;
11040   case CK_FunctionToPointerDecay:
11041     return ICK_Function_To_Pointer;
11042   case CK_IntegralCast:
11043     return ICK_Integral_Conversion;
11044   case CK_FloatingCast:
11045     return ICK_Floating_Conversion;
11046   case CK_IntegralToFloating:
11047   case CK_FloatingToIntegral:
11048     return ICK_Floating_Integral;
11049   case CK_IntegralComplexCast:
11050   case CK_FloatingComplexCast:
11051   case CK_FloatingComplexToIntegralComplex:
11052   case CK_IntegralComplexToFloatingComplex:
11053     return ICK_Complex_Conversion;
11054   case CK_FloatingComplexToReal:
11055   case CK_FloatingRealToComplex:
11056   case CK_IntegralComplexToReal:
11057   case CK_IntegralRealToComplex:
11058     return ICK_Complex_Real;
11059   }
11060 }
11061 
11062 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11063                                              QualType FromType,
11064                                              SourceLocation Loc) {
11065   // Check for a narrowing implicit conversion.
11066   StandardConversionSequence SCS;
11067   SCS.setAsIdentityConversion();
11068   SCS.setToType(0, FromType);
11069   SCS.setToType(1, ToType);
11070   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11071     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11072 
11073   APValue PreNarrowingValue;
11074   QualType PreNarrowingType;
11075   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11076                                PreNarrowingType,
11077                                /*IgnoreFloatToIntegralConversion*/ true)) {
11078   case NK_Dependent_Narrowing:
11079     // Implicit conversion to a narrower type, but the expression is
11080     // value-dependent so we can't tell whether it's actually narrowing.
11081   case NK_Not_Narrowing:
11082     return false;
11083 
11084   case NK_Constant_Narrowing:
11085     // Implicit conversion to a narrower type, and the value is not a constant
11086     // expression.
11087     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11088         << /*Constant*/ 1
11089         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11090     return true;
11091 
11092   case NK_Variable_Narrowing:
11093     // Implicit conversion to a narrower type, and the value is not a constant
11094     // expression.
11095   case NK_Type_Narrowing:
11096     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11097         << /*Constant*/ 0 << FromType << ToType;
11098     // TODO: It's not a constant expression, but what if the user intended it
11099     // to be? Can we produce notes to help them figure out why it isn't?
11100     return true;
11101   }
11102   llvm_unreachable("unhandled case in switch");
11103 }
11104 
11105 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11106                                                          ExprResult &LHS,
11107                                                          ExprResult &RHS,
11108                                                          SourceLocation Loc) {
11109   QualType LHSType = LHS.get()->getType();
11110   QualType RHSType = RHS.get()->getType();
11111   // Dig out the original argument type and expression before implicit casts
11112   // were applied. These are the types/expressions we need to check the
11113   // [expr.spaceship] requirements against.
11114   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11115   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11116   QualType LHSStrippedType = LHSStripped.get()->getType();
11117   QualType RHSStrippedType = RHSStripped.get()->getType();
11118 
11119   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11120   // other is not, the program is ill-formed.
11121   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11122     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11123     return QualType();
11124   }
11125 
11126   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11127   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11128                     RHSStrippedType->isEnumeralType();
11129   if (NumEnumArgs == 1) {
11130     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11131     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11132     if (OtherTy->hasFloatingRepresentation()) {
11133       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11134       return QualType();
11135     }
11136   }
11137   if (NumEnumArgs == 2) {
11138     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11139     // type E, the operator yields the result of converting the operands
11140     // to the underlying type of E and applying <=> to the converted operands.
11141     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11142       S.InvalidOperands(Loc, LHS, RHS);
11143       return QualType();
11144     }
11145     QualType IntType =
11146         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11147     assert(IntType->isArithmeticType());
11148 
11149     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11150     // promote the boolean type, and all other promotable integer types, to
11151     // avoid this.
11152     if (IntType->isPromotableIntegerType())
11153       IntType = S.Context.getPromotedIntegerType(IntType);
11154 
11155     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11156     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11157     LHSType = RHSType = IntType;
11158   }
11159 
11160   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11161   // usual arithmetic conversions are applied to the operands.
11162   QualType Type =
11163       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11164   if (LHS.isInvalid() || RHS.isInvalid())
11165     return QualType();
11166   if (Type.isNull())
11167     return S.InvalidOperands(Loc, LHS, RHS);
11168 
11169   Optional<ComparisonCategoryType> CCT =
11170       getComparisonCategoryForBuiltinCmp(Type);
11171   if (!CCT)
11172     return S.InvalidOperands(Loc, LHS, RHS);
11173 
11174   bool HasNarrowing = checkThreeWayNarrowingConversion(
11175       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11176   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11177                                                    RHS.get()->getBeginLoc());
11178   if (HasNarrowing)
11179     return QualType();
11180 
11181   assert(!Type.isNull() && "composite type for <=> has not been set");
11182 
11183   return S.CheckComparisonCategoryType(
11184       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11185 }
11186 
11187 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11188                                                  ExprResult &RHS,
11189                                                  SourceLocation Loc,
11190                                                  BinaryOperatorKind Opc) {
11191   if (Opc == BO_Cmp)
11192     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11193 
11194   // C99 6.5.8p3 / C99 6.5.9p4
11195   QualType Type =
11196       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11197   if (LHS.isInvalid() || RHS.isInvalid())
11198     return QualType();
11199   if (Type.isNull())
11200     return S.InvalidOperands(Loc, LHS, RHS);
11201   assert(Type->isArithmeticType() || Type->isEnumeralType());
11202 
11203   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11204     return S.InvalidOperands(Loc, LHS, RHS);
11205 
11206   // Check for comparisons of floating point operands using != and ==.
11207   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11208     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11209 
11210   // The result of comparisons is 'bool' in C++, 'int' in C.
11211   return S.Context.getLogicalOperationType();
11212 }
11213 
11214 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11215   if (!NullE.get()->getType()->isAnyPointerType())
11216     return;
11217   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11218   if (!E.get()->getType()->isAnyPointerType() &&
11219       E.get()->isNullPointerConstant(Context,
11220                                      Expr::NPC_ValueDependentIsNotNull) ==
11221         Expr::NPCK_ZeroExpression) {
11222     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11223       if (CL->getValue() == 0)
11224         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11225             << NullValue
11226             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11227                                             NullValue ? "NULL" : "(void *)0");
11228     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11229         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11230         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11231         if (T == Context.CharTy)
11232           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11233               << NullValue
11234               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11235                                               NullValue ? "NULL" : "(void *)0");
11236       }
11237   }
11238 }
11239 
11240 // C99 6.5.8, C++ [expr.rel]
11241 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11242                                     SourceLocation Loc,
11243                                     BinaryOperatorKind Opc) {
11244   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11245   bool IsThreeWay = Opc == BO_Cmp;
11246   bool IsOrdered = IsRelational || IsThreeWay;
11247   auto IsAnyPointerType = [](ExprResult E) {
11248     QualType Ty = E.get()->getType();
11249     return Ty->isPointerType() || Ty->isMemberPointerType();
11250   };
11251 
11252   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11253   // type, array-to-pointer, ..., conversions are performed on both operands to
11254   // bring them to their composite type.
11255   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11256   // any type-related checks.
11257   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11258     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11259     if (LHS.isInvalid())
11260       return QualType();
11261     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11262     if (RHS.isInvalid())
11263       return QualType();
11264   } else {
11265     LHS = DefaultLvalueConversion(LHS.get());
11266     if (LHS.isInvalid())
11267       return QualType();
11268     RHS = DefaultLvalueConversion(RHS.get());
11269     if (RHS.isInvalid())
11270       return QualType();
11271   }
11272 
11273   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11274   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11275     CheckPtrComparisonWithNullChar(LHS, RHS);
11276     CheckPtrComparisonWithNullChar(RHS, LHS);
11277   }
11278 
11279   // Handle vector comparisons separately.
11280   if (LHS.get()->getType()->isVectorType() ||
11281       RHS.get()->getType()->isVectorType())
11282     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11283 
11284   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11285   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11286 
11287   QualType LHSType = LHS.get()->getType();
11288   QualType RHSType = RHS.get()->getType();
11289   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11290       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11291     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11292 
11293   const Expr::NullPointerConstantKind LHSNullKind =
11294       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11295   const Expr::NullPointerConstantKind RHSNullKind =
11296       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11297   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11298   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11299 
11300   auto computeResultTy = [&]() {
11301     if (Opc != BO_Cmp)
11302       return Context.getLogicalOperationType();
11303     assert(getLangOpts().CPlusPlus);
11304     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11305 
11306     QualType CompositeTy = LHS.get()->getType();
11307     assert(!CompositeTy->isReferenceType());
11308 
11309     Optional<ComparisonCategoryType> CCT =
11310         getComparisonCategoryForBuiltinCmp(CompositeTy);
11311     if (!CCT)
11312       return InvalidOperands(Loc, LHS, RHS);
11313 
11314     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11315       // P0946R0: Comparisons between a null pointer constant and an object
11316       // pointer result in std::strong_equality, which is ill-formed under
11317       // P1959R0.
11318       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11319           << (LHSIsNull ? LHS.get()->getSourceRange()
11320                         : RHS.get()->getSourceRange());
11321       return QualType();
11322     }
11323 
11324     return CheckComparisonCategoryType(
11325         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11326   };
11327 
11328   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11329     bool IsEquality = Opc == BO_EQ;
11330     if (RHSIsNull)
11331       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11332                                    RHS.get()->getSourceRange());
11333     else
11334       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11335                                    LHS.get()->getSourceRange());
11336   }
11337 
11338   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11339       (RHSType->isIntegerType() && !RHSIsNull)) {
11340     // Skip normal pointer conversion checks in this case; we have better
11341     // diagnostics for this below.
11342   } else if (getLangOpts().CPlusPlus) {
11343     // Equality comparison of a function pointer to a void pointer is invalid,
11344     // but we allow it as an extension.
11345     // FIXME: If we really want to allow this, should it be part of composite
11346     // pointer type computation so it works in conditionals too?
11347     if (!IsOrdered &&
11348         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11349          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11350       // This is a gcc extension compatibility comparison.
11351       // In a SFINAE context, we treat this as a hard error to maintain
11352       // conformance with the C++ standard.
11353       diagnoseFunctionPointerToVoidComparison(
11354           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11355 
11356       if (isSFINAEContext())
11357         return QualType();
11358 
11359       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11360       return computeResultTy();
11361     }
11362 
11363     // C++ [expr.eq]p2:
11364     //   If at least one operand is a pointer [...] bring them to their
11365     //   composite pointer type.
11366     // C++ [expr.spaceship]p6
11367     //  If at least one of the operands is of pointer type, [...] bring them
11368     //  to their composite pointer type.
11369     // C++ [expr.rel]p2:
11370     //   If both operands are pointers, [...] bring them to their composite
11371     //   pointer type.
11372     // For <=>, the only valid non-pointer types are arrays and functions, and
11373     // we already decayed those, so this is really the same as the relational
11374     // comparison rule.
11375     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11376             (IsOrdered ? 2 : 1) &&
11377         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11378                                          RHSType->isObjCObjectPointerType()))) {
11379       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11380         return QualType();
11381       return computeResultTy();
11382     }
11383   } else if (LHSType->isPointerType() &&
11384              RHSType->isPointerType()) { // C99 6.5.8p2
11385     // All of the following pointer-related warnings are GCC extensions, except
11386     // when handling null pointer constants.
11387     QualType LCanPointeeTy =
11388       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11389     QualType RCanPointeeTy =
11390       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11391 
11392     // C99 6.5.9p2 and C99 6.5.8p2
11393     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11394                                    RCanPointeeTy.getUnqualifiedType())) {
11395       // Valid unless a relational comparison of function pointers
11396       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11397         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11398           << LHSType << RHSType << LHS.get()->getSourceRange()
11399           << RHS.get()->getSourceRange();
11400       }
11401     } else if (!IsRelational &&
11402                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11403       // Valid unless comparison between non-null pointer and function pointer
11404       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11405           && !LHSIsNull && !RHSIsNull)
11406         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11407                                                 /*isError*/false);
11408     } else {
11409       // Invalid
11410       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11411     }
11412     if (LCanPointeeTy != RCanPointeeTy) {
11413       // Treat NULL constant as a special case in OpenCL.
11414       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11415         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
11416         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
11417           Diag(Loc,
11418                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11419               << LHSType << RHSType << 0 /* comparison */
11420               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11421         }
11422       }
11423       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11424       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11425       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11426                                                : CK_BitCast;
11427       if (LHSIsNull && !RHSIsNull)
11428         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11429       else
11430         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11431     }
11432     return computeResultTy();
11433   }
11434 
11435   if (getLangOpts().CPlusPlus) {
11436     // C++ [expr.eq]p4:
11437     //   Two operands of type std::nullptr_t or one operand of type
11438     //   std::nullptr_t and the other a null pointer constant compare equal.
11439     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11440       if (LHSType->isNullPtrType()) {
11441         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11442         return computeResultTy();
11443       }
11444       if (RHSType->isNullPtrType()) {
11445         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11446         return computeResultTy();
11447       }
11448     }
11449 
11450     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11451     // These aren't covered by the composite pointer type rules.
11452     if (!IsOrdered && RHSType->isNullPtrType() &&
11453         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11454       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11455       return computeResultTy();
11456     }
11457     if (!IsOrdered && LHSType->isNullPtrType() &&
11458         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11459       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11460       return computeResultTy();
11461     }
11462 
11463     if (IsRelational &&
11464         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11465          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11466       // HACK: Relational comparison of nullptr_t against a pointer type is
11467       // invalid per DR583, but we allow it within std::less<> and friends,
11468       // since otherwise common uses of it break.
11469       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11470       // friends to have std::nullptr_t overload candidates.
11471       DeclContext *DC = CurContext;
11472       if (isa<FunctionDecl>(DC))
11473         DC = DC->getParent();
11474       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11475         if (CTSD->isInStdNamespace() &&
11476             llvm::StringSwitch<bool>(CTSD->getName())
11477                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11478                 .Default(false)) {
11479           if (RHSType->isNullPtrType())
11480             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11481           else
11482             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11483           return computeResultTy();
11484         }
11485       }
11486     }
11487 
11488     // C++ [expr.eq]p2:
11489     //   If at least one operand is a pointer to member, [...] bring them to
11490     //   their composite pointer type.
11491     if (!IsOrdered &&
11492         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11493       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11494         return QualType();
11495       else
11496         return computeResultTy();
11497     }
11498   }
11499 
11500   // Handle block pointer types.
11501   if (!IsOrdered && LHSType->isBlockPointerType() &&
11502       RHSType->isBlockPointerType()) {
11503     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11504     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11505 
11506     if (!LHSIsNull && !RHSIsNull &&
11507         !Context.typesAreCompatible(lpointee, rpointee)) {
11508       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11509         << LHSType << RHSType << LHS.get()->getSourceRange()
11510         << RHS.get()->getSourceRange();
11511     }
11512     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11513     return computeResultTy();
11514   }
11515 
11516   // Allow block pointers to be compared with null pointer constants.
11517   if (!IsOrdered
11518       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11519           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11520     if (!LHSIsNull && !RHSIsNull) {
11521       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11522              ->getPointeeType()->isVoidType())
11523             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11524                 ->getPointeeType()->isVoidType())))
11525         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11526           << LHSType << RHSType << LHS.get()->getSourceRange()
11527           << RHS.get()->getSourceRange();
11528     }
11529     if (LHSIsNull && !RHSIsNull)
11530       LHS = ImpCastExprToType(LHS.get(), RHSType,
11531                               RHSType->isPointerType() ? CK_BitCast
11532                                 : CK_AnyPointerToBlockPointerCast);
11533     else
11534       RHS = ImpCastExprToType(RHS.get(), LHSType,
11535                               LHSType->isPointerType() ? CK_BitCast
11536                                 : CK_AnyPointerToBlockPointerCast);
11537     return computeResultTy();
11538   }
11539 
11540   if (LHSType->isObjCObjectPointerType() ||
11541       RHSType->isObjCObjectPointerType()) {
11542     const PointerType *LPT = LHSType->getAs<PointerType>();
11543     const PointerType *RPT = RHSType->getAs<PointerType>();
11544     if (LPT || RPT) {
11545       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11546       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11547 
11548       if (!LPtrToVoid && !RPtrToVoid &&
11549           !Context.typesAreCompatible(LHSType, RHSType)) {
11550         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11551                                           /*isError*/false);
11552       }
11553       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11554       // the RHS, but we have test coverage for this behavior.
11555       // FIXME: Consider using convertPointersToCompositeType in C++.
11556       if (LHSIsNull && !RHSIsNull) {
11557         Expr *E = LHS.get();
11558         if (getLangOpts().ObjCAutoRefCount)
11559           CheckObjCConversion(SourceRange(), RHSType, E,
11560                               CCK_ImplicitConversion);
11561         LHS = ImpCastExprToType(E, RHSType,
11562                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11563       }
11564       else {
11565         Expr *E = RHS.get();
11566         if (getLangOpts().ObjCAutoRefCount)
11567           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11568                               /*Diagnose=*/true,
11569                               /*DiagnoseCFAudited=*/false, Opc);
11570         RHS = ImpCastExprToType(E, LHSType,
11571                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11572       }
11573       return computeResultTy();
11574     }
11575     if (LHSType->isObjCObjectPointerType() &&
11576         RHSType->isObjCObjectPointerType()) {
11577       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11578         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11579                                           /*isError*/false);
11580       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11581         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11582 
11583       if (LHSIsNull && !RHSIsNull)
11584         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11585       else
11586         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11587       return computeResultTy();
11588     }
11589 
11590     if (!IsOrdered && LHSType->isBlockPointerType() &&
11591         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11592       LHS = ImpCastExprToType(LHS.get(), RHSType,
11593                               CK_BlockPointerToObjCPointerCast);
11594       return computeResultTy();
11595     } else if (!IsOrdered &&
11596                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11597                RHSType->isBlockPointerType()) {
11598       RHS = ImpCastExprToType(RHS.get(), LHSType,
11599                               CK_BlockPointerToObjCPointerCast);
11600       return computeResultTy();
11601     }
11602   }
11603   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11604       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11605     unsigned DiagID = 0;
11606     bool isError = false;
11607     if (LangOpts.DebuggerSupport) {
11608       // Under a debugger, allow the comparison of pointers to integers,
11609       // since users tend to want to compare addresses.
11610     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11611                (RHSIsNull && RHSType->isIntegerType())) {
11612       if (IsOrdered) {
11613         isError = getLangOpts().CPlusPlus;
11614         DiagID =
11615           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11616                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11617       }
11618     } else if (getLangOpts().CPlusPlus) {
11619       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11620       isError = true;
11621     } else if (IsOrdered)
11622       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11623     else
11624       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11625 
11626     if (DiagID) {
11627       Diag(Loc, DiagID)
11628         << LHSType << RHSType << LHS.get()->getSourceRange()
11629         << RHS.get()->getSourceRange();
11630       if (isError)
11631         return QualType();
11632     }
11633 
11634     if (LHSType->isIntegerType())
11635       LHS = ImpCastExprToType(LHS.get(), RHSType,
11636                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11637     else
11638       RHS = ImpCastExprToType(RHS.get(), LHSType,
11639                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11640     return computeResultTy();
11641   }
11642 
11643   // Handle block pointers.
11644   if (!IsOrdered && RHSIsNull
11645       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11646     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11647     return computeResultTy();
11648   }
11649   if (!IsOrdered && LHSIsNull
11650       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11651     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11652     return computeResultTy();
11653   }
11654 
11655   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11656     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11657       return computeResultTy();
11658     }
11659 
11660     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11661       return computeResultTy();
11662     }
11663 
11664     if (LHSIsNull && RHSType->isQueueT()) {
11665       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11666       return computeResultTy();
11667     }
11668 
11669     if (LHSType->isQueueT() && RHSIsNull) {
11670       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11671       return computeResultTy();
11672     }
11673   }
11674 
11675   return InvalidOperands(Loc, LHS, RHS);
11676 }
11677 
11678 // Return a signed ext_vector_type that is of identical size and number of
11679 // elements. For floating point vectors, return an integer type of identical
11680 // size and number of elements. In the non ext_vector_type case, search from
11681 // the largest type to the smallest type to avoid cases where long long == long,
11682 // where long gets picked over long long.
11683 QualType Sema::GetSignedVectorType(QualType V) {
11684   const VectorType *VTy = V->castAs<VectorType>();
11685   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11686 
11687   if (isa<ExtVectorType>(VTy)) {
11688     if (TypeSize == Context.getTypeSize(Context.CharTy))
11689       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11690     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11691       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11692     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11693       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11694     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11695       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11696     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11697            "Unhandled vector element size in vector compare");
11698     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11699   }
11700 
11701   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11702     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11703                                  VectorType::GenericVector);
11704   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11705     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11706                                  VectorType::GenericVector);
11707   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11708     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11709                                  VectorType::GenericVector);
11710   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11711     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11712                                  VectorType::GenericVector);
11713   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11714          "Unhandled vector element size in vector compare");
11715   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11716                                VectorType::GenericVector);
11717 }
11718 
11719 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11720 /// operates on extended vector types.  Instead of producing an IntTy result,
11721 /// like a scalar comparison, a vector comparison produces a vector of integer
11722 /// types.
11723 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11724                                           SourceLocation Loc,
11725                                           BinaryOperatorKind Opc) {
11726   if (Opc == BO_Cmp) {
11727     Diag(Loc, diag::err_three_way_vector_comparison);
11728     return QualType();
11729   }
11730 
11731   // Check to make sure we're operating on vectors of the same type and width,
11732   // Allowing one side to be a scalar of element type.
11733   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11734                               /*AllowBothBool*/true,
11735                               /*AllowBoolConversions*/getLangOpts().ZVector);
11736   if (vType.isNull())
11737     return vType;
11738 
11739   QualType LHSType = LHS.get()->getType();
11740 
11741   // If AltiVec, the comparison results in a numeric type, i.e.
11742   // bool for C++, int for C
11743   if (getLangOpts().AltiVec &&
11744       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11745     return Context.getLogicalOperationType();
11746 
11747   // For non-floating point types, check for self-comparisons of the form
11748   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11749   // often indicate logic errors in the program.
11750   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11751 
11752   // Check for comparisons of floating point operands using != and ==.
11753   if (BinaryOperator::isEqualityOp(Opc) &&
11754       LHSType->hasFloatingRepresentation()) {
11755     assert(RHS.get()->getType()->hasFloatingRepresentation());
11756     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11757   }
11758 
11759   // Return a signed type for the vector.
11760   return GetSignedVectorType(vType);
11761 }
11762 
11763 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11764                                     const ExprResult &XorRHS,
11765                                     const SourceLocation Loc) {
11766   // Do not diagnose macros.
11767   if (Loc.isMacroID())
11768     return;
11769 
11770   bool Negative = false;
11771   bool ExplicitPlus = false;
11772   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11773   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11774 
11775   if (!LHSInt)
11776     return;
11777   if (!RHSInt) {
11778     // Check negative literals.
11779     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11780       UnaryOperatorKind Opc = UO->getOpcode();
11781       if (Opc != UO_Minus && Opc != UO_Plus)
11782         return;
11783       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11784       if (!RHSInt)
11785         return;
11786       Negative = (Opc == UO_Minus);
11787       ExplicitPlus = !Negative;
11788     } else {
11789       return;
11790     }
11791   }
11792 
11793   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11794   llvm::APInt RightSideValue = RHSInt->getValue();
11795   if (LeftSideValue != 2 && LeftSideValue != 10)
11796     return;
11797 
11798   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11799     return;
11800 
11801   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11802       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11803   llvm::StringRef ExprStr =
11804       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11805 
11806   CharSourceRange XorRange =
11807       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11808   llvm::StringRef XorStr =
11809       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11810   // Do not diagnose if xor keyword/macro is used.
11811   if (XorStr == "xor")
11812     return;
11813 
11814   std::string LHSStr = std::string(Lexer::getSourceText(
11815       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11816       S.getSourceManager(), S.getLangOpts()));
11817   std::string RHSStr = std::string(Lexer::getSourceText(
11818       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11819       S.getSourceManager(), S.getLangOpts()));
11820 
11821   if (Negative) {
11822     RightSideValue = -RightSideValue;
11823     RHSStr = "-" + RHSStr;
11824   } else if (ExplicitPlus) {
11825     RHSStr = "+" + RHSStr;
11826   }
11827 
11828   StringRef LHSStrRef = LHSStr;
11829   StringRef RHSStrRef = RHSStr;
11830   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11831   // literals.
11832   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11833       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11834       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11835       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11836       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11837       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11838       LHSStrRef.find('\'') != StringRef::npos ||
11839       RHSStrRef.find('\'') != StringRef::npos)
11840     return;
11841 
11842   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11843   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11844   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11845   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11846     std::string SuggestedExpr = "1 << " + RHSStr;
11847     bool Overflow = false;
11848     llvm::APInt One = (LeftSideValue - 1);
11849     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11850     if (Overflow) {
11851       if (RightSideIntValue < 64)
11852         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11853             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11854             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11855       else if (RightSideIntValue == 64)
11856         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11857       else
11858         return;
11859     } else {
11860       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11861           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11862           << PowValue.toString(10, true)
11863           << FixItHint::CreateReplacement(
11864                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11865     }
11866 
11867     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11868   } else if (LeftSideValue == 10) {
11869     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11870     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11871         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11872         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11873     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11874   }
11875 }
11876 
11877 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11878                                           SourceLocation Loc) {
11879   // Ensure that either both operands are of the same vector type, or
11880   // one operand is of a vector type and the other is of its element type.
11881   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11882                                        /*AllowBothBool*/true,
11883                                        /*AllowBoolConversions*/false);
11884   if (vType.isNull())
11885     return InvalidOperands(Loc, LHS, RHS);
11886   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11887       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11888     return InvalidOperands(Loc, LHS, RHS);
11889   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11890   //        usage of the logical operators && and || with vectors in C. This
11891   //        check could be notionally dropped.
11892   if (!getLangOpts().CPlusPlus &&
11893       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11894     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11895 
11896   return GetSignedVectorType(LHS.get()->getType());
11897 }
11898 
11899 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11900                                            SourceLocation Loc,
11901                                            BinaryOperatorKind Opc) {
11902   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11903 
11904   bool IsCompAssign =
11905       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11906 
11907   if (LHS.get()->getType()->isVectorType() ||
11908       RHS.get()->getType()->isVectorType()) {
11909     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11910         RHS.get()->getType()->hasIntegerRepresentation())
11911       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11912                         /*AllowBothBool*/true,
11913                         /*AllowBoolConversions*/getLangOpts().ZVector);
11914     return InvalidOperands(Loc, LHS, RHS);
11915   }
11916 
11917   if (Opc == BO_And)
11918     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11919 
11920   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11921       RHS.get()->getType()->hasFloatingRepresentation())
11922     return InvalidOperands(Loc, LHS, RHS);
11923 
11924   ExprResult LHSResult = LHS, RHSResult = RHS;
11925   QualType compType = UsualArithmeticConversions(
11926       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11927   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11928     return QualType();
11929   LHS = LHSResult.get();
11930   RHS = RHSResult.get();
11931 
11932   if (Opc == BO_Xor)
11933     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11934 
11935   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11936     return compType;
11937   return InvalidOperands(Loc, LHS, RHS);
11938 }
11939 
11940 // C99 6.5.[13,14]
11941 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11942                                            SourceLocation Loc,
11943                                            BinaryOperatorKind Opc) {
11944   // Check vector operands differently.
11945   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11946     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11947 
11948   bool EnumConstantInBoolContext = false;
11949   for (const ExprResult &HS : {LHS, RHS}) {
11950     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11951       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11952       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11953         EnumConstantInBoolContext = true;
11954     }
11955   }
11956 
11957   if (EnumConstantInBoolContext)
11958     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11959 
11960   // Diagnose cases where the user write a logical and/or but probably meant a
11961   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11962   // is a constant.
11963   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11964       !LHS.get()->getType()->isBooleanType() &&
11965       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11966       // Don't warn in macros or template instantiations.
11967       !Loc.isMacroID() && !inTemplateInstantiation()) {
11968     // If the RHS can be constant folded, and if it constant folds to something
11969     // that isn't 0 or 1 (which indicate a potential logical operation that
11970     // happened to fold to true/false) then warn.
11971     // Parens on the RHS are ignored.
11972     Expr::EvalResult EVResult;
11973     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11974       llvm::APSInt Result = EVResult.Val.getInt();
11975       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11976            !RHS.get()->getExprLoc().isMacroID()) ||
11977           (Result != 0 && Result != 1)) {
11978         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11979           << RHS.get()->getSourceRange()
11980           << (Opc == BO_LAnd ? "&&" : "||");
11981         // Suggest replacing the logical operator with the bitwise version
11982         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11983             << (Opc == BO_LAnd ? "&" : "|")
11984             << FixItHint::CreateReplacement(SourceRange(
11985                                                  Loc, getLocForEndOfToken(Loc)),
11986                                             Opc == BO_LAnd ? "&" : "|");
11987         if (Opc == BO_LAnd)
11988           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11989           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11990               << FixItHint::CreateRemoval(
11991                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11992                                  RHS.get()->getEndLoc()));
11993       }
11994     }
11995   }
11996 
11997   if (!Context.getLangOpts().CPlusPlus) {
11998     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11999     // not operate on the built-in scalar and vector float types.
12000     if (Context.getLangOpts().OpenCL &&
12001         Context.getLangOpts().OpenCLVersion < 120) {
12002       if (LHS.get()->getType()->isFloatingType() ||
12003           RHS.get()->getType()->isFloatingType())
12004         return InvalidOperands(Loc, LHS, RHS);
12005     }
12006 
12007     LHS = UsualUnaryConversions(LHS.get());
12008     if (LHS.isInvalid())
12009       return QualType();
12010 
12011     RHS = UsualUnaryConversions(RHS.get());
12012     if (RHS.isInvalid())
12013       return QualType();
12014 
12015     if (!LHS.get()->getType()->isScalarType() ||
12016         !RHS.get()->getType()->isScalarType())
12017       return InvalidOperands(Loc, LHS, RHS);
12018 
12019     return Context.IntTy;
12020   }
12021 
12022   // The following is safe because we only use this method for
12023   // non-overloadable operands.
12024 
12025   // C++ [expr.log.and]p1
12026   // C++ [expr.log.or]p1
12027   // The operands are both contextually converted to type bool.
12028   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12029   if (LHSRes.isInvalid())
12030     return InvalidOperands(Loc, LHS, RHS);
12031   LHS = LHSRes;
12032 
12033   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12034   if (RHSRes.isInvalid())
12035     return InvalidOperands(Loc, LHS, RHS);
12036   RHS = RHSRes;
12037 
12038   // C++ [expr.log.and]p2
12039   // C++ [expr.log.or]p2
12040   // The result is a bool.
12041   return Context.BoolTy;
12042 }
12043 
12044 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12045   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12046   if (!ME) return false;
12047   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12048   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12049       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12050   if (!Base) return false;
12051   return Base->getMethodDecl() != nullptr;
12052 }
12053 
12054 /// Is the given expression (which must be 'const') a reference to a
12055 /// variable which was originally non-const, but which has become
12056 /// 'const' due to being captured within a block?
12057 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12058 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12059   assert(E->isLValue() && E->getType().isConstQualified());
12060   E = E->IgnoreParens();
12061 
12062   // Must be a reference to a declaration from an enclosing scope.
12063   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12064   if (!DRE) return NCCK_None;
12065   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12066 
12067   // The declaration must be a variable which is not declared 'const'.
12068   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12069   if (!var) return NCCK_None;
12070   if (var->getType().isConstQualified()) return NCCK_None;
12071   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12072 
12073   // Decide whether the first capture was for a block or a lambda.
12074   DeclContext *DC = S.CurContext, *Prev = nullptr;
12075   // Decide whether the first capture was for a block or a lambda.
12076   while (DC) {
12077     // For init-capture, it is possible that the variable belongs to the
12078     // template pattern of the current context.
12079     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12080       if (var->isInitCapture() &&
12081           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12082         break;
12083     if (DC == var->getDeclContext())
12084       break;
12085     Prev = DC;
12086     DC = DC->getParent();
12087   }
12088   // Unless we have an init-capture, we've gone one step too far.
12089   if (!var->isInitCapture())
12090     DC = Prev;
12091   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12092 }
12093 
12094 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12095   Ty = Ty.getNonReferenceType();
12096   if (IsDereference && Ty->isPointerType())
12097     Ty = Ty->getPointeeType();
12098   return !Ty.isConstQualified();
12099 }
12100 
12101 // Update err_typecheck_assign_const and note_typecheck_assign_const
12102 // when this enum is changed.
12103 enum {
12104   ConstFunction,
12105   ConstVariable,
12106   ConstMember,
12107   ConstMethod,
12108   NestedConstMember,
12109   ConstUnknown,  // Keep as last element
12110 };
12111 
12112 /// Emit the "read-only variable not assignable" error and print notes to give
12113 /// more information about why the variable is not assignable, such as pointing
12114 /// to the declaration of a const variable, showing that a method is const, or
12115 /// that the function is returning a const reference.
12116 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12117                                     SourceLocation Loc) {
12118   SourceRange ExprRange = E->getSourceRange();
12119 
12120   // Only emit one error on the first const found.  All other consts will emit
12121   // a note to the error.
12122   bool DiagnosticEmitted = false;
12123 
12124   // Track if the current expression is the result of a dereference, and if the
12125   // next checked expression is the result of a dereference.
12126   bool IsDereference = false;
12127   bool NextIsDereference = false;
12128 
12129   // Loop to process MemberExpr chains.
12130   while (true) {
12131     IsDereference = NextIsDereference;
12132 
12133     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12134     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12135       NextIsDereference = ME->isArrow();
12136       const ValueDecl *VD = ME->getMemberDecl();
12137       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12138         // Mutable fields can be modified even if the class is const.
12139         if (Field->isMutable()) {
12140           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12141           break;
12142         }
12143 
12144         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12145           if (!DiagnosticEmitted) {
12146             S.Diag(Loc, diag::err_typecheck_assign_const)
12147                 << ExprRange << ConstMember << false /*static*/ << Field
12148                 << Field->getType();
12149             DiagnosticEmitted = true;
12150           }
12151           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12152               << ConstMember << false /*static*/ << Field << Field->getType()
12153               << Field->getSourceRange();
12154         }
12155         E = ME->getBase();
12156         continue;
12157       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12158         if (VDecl->getType().isConstQualified()) {
12159           if (!DiagnosticEmitted) {
12160             S.Diag(Loc, diag::err_typecheck_assign_const)
12161                 << ExprRange << ConstMember << true /*static*/ << VDecl
12162                 << VDecl->getType();
12163             DiagnosticEmitted = true;
12164           }
12165           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12166               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12167               << VDecl->getSourceRange();
12168         }
12169         // Static fields do not inherit constness from parents.
12170         break;
12171       }
12172       break; // End MemberExpr
12173     } else if (const ArraySubscriptExpr *ASE =
12174                    dyn_cast<ArraySubscriptExpr>(E)) {
12175       E = ASE->getBase()->IgnoreParenImpCasts();
12176       continue;
12177     } else if (const ExtVectorElementExpr *EVE =
12178                    dyn_cast<ExtVectorElementExpr>(E)) {
12179       E = EVE->getBase()->IgnoreParenImpCasts();
12180       continue;
12181     }
12182     break;
12183   }
12184 
12185   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12186     // Function calls
12187     const FunctionDecl *FD = CE->getDirectCallee();
12188     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12189       if (!DiagnosticEmitted) {
12190         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12191                                                       << ConstFunction << FD;
12192         DiagnosticEmitted = true;
12193       }
12194       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12195              diag::note_typecheck_assign_const)
12196           << ConstFunction << FD << FD->getReturnType()
12197           << FD->getReturnTypeSourceRange();
12198     }
12199   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12200     // Point to variable declaration.
12201     if (const ValueDecl *VD = DRE->getDecl()) {
12202       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12203         if (!DiagnosticEmitted) {
12204           S.Diag(Loc, diag::err_typecheck_assign_const)
12205               << ExprRange << ConstVariable << VD << VD->getType();
12206           DiagnosticEmitted = true;
12207         }
12208         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12209             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12210       }
12211     }
12212   } else if (isa<CXXThisExpr>(E)) {
12213     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12214       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12215         if (MD->isConst()) {
12216           if (!DiagnosticEmitted) {
12217             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12218                                                           << ConstMethod << MD;
12219             DiagnosticEmitted = true;
12220           }
12221           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12222               << ConstMethod << MD << MD->getSourceRange();
12223         }
12224       }
12225     }
12226   }
12227 
12228   if (DiagnosticEmitted)
12229     return;
12230 
12231   // Can't determine a more specific message, so display the generic error.
12232   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12233 }
12234 
12235 enum OriginalExprKind {
12236   OEK_Variable,
12237   OEK_Member,
12238   OEK_LValue
12239 };
12240 
12241 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12242                                          const RecordType *Ty,
12243                                          SourceLocation Loc, SourceRange Range,
12244                                          OriginalExprKind OEK,
12245                                          bool &DiagnosticEmitted) {
12246   std::vector<const RecordType *> RecordTypeList;
12247   RecordTypeList.push_back(Ty);
12248   unsigned NextToCheckIndex = 0;
12249   // We walk the record hierarchy breadth-first to ensure that we print
12250   // diagnostics in field nesting order.
12251   while (RecordTypeList.size() > NextToCheckIndex) {
12252     bool IsNested = NextToCheckIndex > 0;
12253     for (const FieldDecl *Field :
12254          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12255       // First, check every field for constness.
12256       QualType FieldTy = Field->getType();
12257       if (FieldTy.isConstQualified()) {
12258         if (!DiagnosticEmitted) {
12259           S.Diag(Loc, diag::err_typecheck_assign_const)
12260               << Range << NestedConstMember << OEK << VD
12261               << IsNested << Field;
12262           DiagnosticEmitted = true;
12263         }
12264         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12265             << NestedConstMember << IsNested << Field
12266             << FieldTy << Field->getSourceRange();
12267       }
12268 
12269       // Then we append it to the list to check next in order.
12270       FieldTy = FieldTy.getCanonicalType();
12271       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12272         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12273           RecordTypeList.push_back(FieldRecTy);
12274       }
12275     }
12276     ++NextToCheckIndex;
12277   }
12278 }
12279 
12280 /// Emit an error for the case where a record we are trying to assign to has a
12281 /// const-qualified field somewhere in its hierarchy.
12282 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12283                                          SourceLocation Loc) {
12284   QualType Ty = E->getType();
12285   assert(Ty->isRecordType() && "lvalue was not record?");
12286   SourceRange Range = E->getSourceRange();
12287   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12288   bool DiagEmitted = false;
12289 
12290   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12291     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12292             Range, OEK_Member, DiagEmitted);
12293   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12294     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12295             Range, OEK_Variable, DiagEmitted);
12296   else
12297     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12298             Range, OEK_LValue, DiagEmitted);
12299   if (!DiagEmitted)
12300     DiagnoseConstAssignment(S, E, Loc);
12301 }
12302 
12303 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12304 /// emit an error and return true.  If so, return false.
12305 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12306   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12307 
12308   S.CheckShadowingDeclModification(E, Loc);
12309 
12310   SourceLocation OrigLoc = Loc;
12311   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12312                                                               &Loc);
12313   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12314     IsLV = Expr::MLV_InvalidMessageExpression;
12315   if (IsLV == Expr::MLV_Valid)
12316     return false;
12317 
12318   unsigned DiagID = 0;
12319   bool NeedType = false;
12320   switch (IsLV) { // C99 6.5.16p2
12321   case Expr::MLV_ConstQualified:
12322     // Use a specialized diagnostic when we're assigning to an object
12323     // from an enclosing function or block.
12324     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12325       if (NCCK == NCCK_Block)
12326         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12327       else
12328         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12329       break;
12330     }
12331 
12332     // In ARC, use some specialized diagnostics for occasions where we
12333     // infer 'const'.  These are always pseudo-strong variables.
12334     if (S.getLangOpts().ObjCAutoRefCount) {
12335       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12336       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12337         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12338 
12339         // Use the normal diagnostic if it's pseudo-__strong but the
12340         // user actually wrote 'const'.
12341         if (var->isARCPseudoStrong() &&
12342             (!var->getTypeSourceInfo() ||
12343              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12344           // There are three pseudo-strong cases:
12345           //  - self
12346           ObjCMethodDecl *method = S.getCurMethodDecl();
12347           if (method && var == method->getSelfDecl()) {
12348             DiagID = method->isClassMethod()
12349               ? diag::err_typecheck_arc_assign_self_class_method
12350               : diag::err_typecheck_arc_assign_self;
12351 
12352           //  - Objective-C externally_retained attribute.
12353           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12354                      isa<ParmVarDecl>(var)) {
12355             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12356 
12357           //  - fast enumeration variables
12358           } else {
12359             DiagID = diag::err_typecheck_arr_assign_enumeration;
12360           }
12361 
12362           SourceRange Assign;
12363           if (Loc != OrigLoc)
12364             Assign = SourceRange(OrigLoc, OrigLoc);
12365           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12366           // We need to preserve the AST regardless, so migration tool
12367           // can do its job.
12368           return false;
12369         }
12370       }
12371     }
12372 
12373     // If none of the special cases above are triggered, then this is a
12374     // simple const assignment.
12375     if (DiagID == 0) {
12376       DiagnoseConstAssignment(S, E, Loc);
12377       return true;
12378     }
12379 
12380     break;
12381   case Expr::MLV_ConstAddrSpace:
12382     DiagnoseConstAssignment(S, E, Loc);
12383     return true;
12384   case Expr::MLV_ConstQualifiedField:
12385     DiagnoseRecursiveConstFields(S, E, Loc);
12386     return true;
12387   case Expr::MLV_ArrayType:
12388   case Expr::MLV_ArrayTemporary:
12389     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12390     NeedType = true;
12391     break;
12392   case Expr::MLV_NotObjectType:
12393     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12394     NeedType = true;
12395     break;
12396   case Expr::MLV_LValueCast:
12397     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12398     break;
12399   case Expr::MLV_Valid:
12400     llvm_unreachable("did not take early return for MLV_Valid");
12401   case Expr::MLV_InvalidExpression:
12402   case Expr::MLV_MemberFunction:
12403   case Expr::MLV_ClassTemporary:
12404     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12405     break;
12406   case Expr::MLV_IncompleteType:
12407   case Expr::MLV_IncompleteVoidType:
12408     return S.RequireCompleteType(Loc, E->getType(),
12409              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12410   case Expr::MLV_DuplicateVectorComponents:
12411     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12412     break;
12413   case Expr::MLV_NoSetterProperty:
12414     llvm_unreachable("readonly properties should be processed differently");
12415   case Expr::MLV_InvalidMessageExpression:
12416     DiagID = diag::err_readonly_message_assignment;
12417     break;
12418   case Expr::MLV_SubObjCPropertySetting:
12419     DiagID = diag::err_no_subobject_property_setting;
12420     break;
12421   }
12422 
12423   SourceRange Assign;
12424   if (Loc != OrigLoc)
12425     Assign = SourceRange(OrigLoc, OrigLoc);
12426   if (NeedType)
12427     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12428   else
12429     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12430   return true;
12431 }
12432 
12433 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12434                                          SourceLocation Loc,
12435                                          Sema &Sema) {
12436   if (Sema.inTemplateInstantiation())
12437     return;
12438   if (Sema.isUnevaluatedContext())
12439     return;
12440   if (Loc.isInvalid() || Loc.isMacroID())
12441     return;
12442   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12443     return;
12444 
12445   // C / C++ fields
12446   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12447   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12448   if (ML && MR) {
12449     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12450       return;
12451     const ValueDecl *LHSDecl =
12452         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12453     const ValueDecl *RHSDecl =
12454         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12455     if (LHSDecl != RHSDecl)
12456       return;
12457     if (LHSDecl->getType().isVolatileQualified())
12458       return;
12459     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12460       if (RefTy->getPointeeType().isVolatileQualified())
12461         return;
12462 
12463     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12464   }
12465 
12466   // Objective-C instance variables
12467   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12468   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12469   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12470     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12471     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12472     if (RL && RR && RL->getDecl() == RR->getDecl())
12473       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12474   }
12475 }
12476 
12477 // C99 6.5.16.1
12478 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12479                                        SourceLocation Loc,
12480                                        QualType CompoundType) {
12481   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12482 
12483   // Verify that LHS is a modifiable lvalue, and emit error if not.
12484   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12485     return QualType();
12486 
12487   QualType LHSType = LHSExpr->getType();
12488   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12489                                              CompoundType;
12490   // OpenCL v1.2 s6.1.1.1 p2:
12491   // The half data type can only be used to declare a pointer to a buffer that
12492   // contains half values
12493   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12494     LHSType->isHalfType()) {
12495     Diag(Loc, diag::err_opencl_half_load_store) << 1
12496         << LHSType.getUnqualifiedType();
12497     return QualType();
12498   }
12499 
12500   AssignConvertType ConvTy;
12501   if (CompoundType.isNull()) {
12502     Expr *RHSCheck = RHS.get();
12503 
12504     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12505 
12506     QualType LHSTy(LHSType);
12507     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12508     if (RHS.isInvalid())
12509       return QualType();
12510     // Special case of NSObject attributes on c-style pointer types.
12511     if (ConvTy == IncompatiblePointer &&
12512         ((Context.isObjCNSObjectType(LHSType) &&
12513           RHSType->isObjCObjectPointerType()) ||
12514          (Context.isObjCNSObjectType(RHSType) &&
12515           LHSType->isObjCObjectPointerType())))
12516       ConvTy = Compatible;
12517 
12518     if (ConvTy == Compatible &&
12519         LHSType->isObjCObjectType())
12520         Diag(Loc, diag::err_objc_object_assignment)
12521           << LHSType;
12522 
12523     // If the RHS is a unary plus or minus, check to see if they = and + are
12524     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12525     // instead of "x += 4".
12526     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12527       RHSCheck = ICE->getSubExpr();
12528     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12529       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12530           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12531           // Only if the two operators are exactly adjacent.
12532           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12533           // And there is a space or other character before the subexpr of the
12534           // unary +/-.  We don't want to warn on "x=-1".
12535           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12536           UO->getSubExpr()->getBeginLoc().isFileID()) {
12537         Diag(Loc, diag::warn_not_compound_assign)
12538           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12539           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12540       }
12541     }
12542 
12543     if (ConvTy == Compatible) {
12544       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12545         // Warn about retain cycles where a block captures the LHS, but
12546         // not if the LHS is a simple variable into which the block is
12547         // being stored...unless that variable can be captured by reference!
12548         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12549         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12550         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12551           checkRetainCycles(LHSExpr, RHS.get());
12552       }
12553 
12554       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12555           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12556         // It is safe to assign a weak reference into a strong variable.
12557         // Although this code can still have problems:
12558         //   id x = self.weakProp;
12559         //   id y = self.weakProp;
12560         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12561         // paths through the function. This should be revisited if
12562         // -Wrepeated-use-of-weak is made flow-sensitive.
12563         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12564         // variable, which will be valid for the current autorelease scope.
12565         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12566                              RHS.get()->getBeginLoc()))
12567           getCurFunction()->markSafeWeakUse(RHS.get());
12568 
12569       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12570         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12571       }
12572     }
12573   } else {
12574     // Compound assignment "x += y"
12575     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12576   }
12577 
12578   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12579                                RHS.get(), AA_Assigning))
12580     return QualType();
12581 
12582   CheckForNullPointerDereference(*this, LHSExpr);
12583 
12584   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12585     if (CompoundType.isNull()) {
12586       // C++2a [expr.ass]p5:
12587       //   A simple-assignment whose left operand is of a volatile-qualified
12588       //   type is deprecated unless the assignment is either a discarded-value
12589       //   expression or an unevaluated operand
12590       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12591     } else {
12592       // C++2a [expr.ass]p6:
12593       //   [Compound-assignment] expressions are deprecated if E1 has
12594       //   volatile-qualified type
12595       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12596     }
12597   }
12598 
12599   // C99 6.5.16p3: The type of an assignment expression is the type of the
12600   // left operand unless the left operand has qualified type, in which case
12601   // it is the unqualified version of the type of the left operand.
12602   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12603   // is converted to the type of the assignment expression (above).
12604   // C++ 5.17p1: the type of the assignment expression is that of its left
12605   // operand.
12606   return (getLangOpts().CPlusPlus
12607           ? LHSType : LHSType.getUnqualifiedType());
12608 }
12609 
12610 // Only ignore explicit casts to void.
12611 static bool IgnoreCommaOperand(const Expr *E) {
12612   E = E->IgnoreParens();
12613 
12614   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12615     if (CE->getCastKind() == CK_ToVoid) {
12616       return true;
12617     }
12618 
12619     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12620     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12621         CE->getSubExpr()->getType()->isDependentType()) {
12622       return true;
12623     }
12624   }
12625 
12626   return false;
12627 }
12628 
12629 // Look for instances where it is likely the comma operator is confused with
12630 // another operator.  There is a whitelist of acceptable expressions for the
12631 // left hand side of the comma operator, otherwise emit a warning.
12632 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12633   // No warnings in macros
12634   if (Loc.isMacroID())
12635     return;
12636 
12637   // Don't warn in template instantiations.
12638   if (inTemplateInstantiation())
12639     return;
12640 
12641   // Scope isn't fine-grained enough to whitelist the specific cases, so
12642   // instead, skip more than needed, then call back into here with the
12643   // CommaVisitor in SemaStmt.cpp.
12644   // The whitelisted locations are the initialization and increment portions
12645   // of a for loop.  The additional checks are on the condition of
12646   // if statements, do/while loops, and for loops.
12647   // Differences in scope flags for C89 mode requires the extra logic.
12648   const unsigned ForIncrementFlags =
12649       getLangOpts().C99 || getLangOpts().CPlusPlus
12650           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12651           : Scope::ContinueScope | Scope::BreakScope;
12652   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12653   const unsigned ScopeFlags = getCurScope()->getFlags();
12654   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12655       (ScopeFlags & ForInitFlags) == ForInitFlags)
12656     return;
12657 
12658   // If there are multiple comma operators used together, get the RHS of the
12659   // of the comma operator as the LHS.
12660   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12661     if (BO->getOpcode() != BO_Comma)
12662       break;
12663     LHS = BO->getRHS();
12664   }
12665 
12666   // Only allow some expressions on LHS to not warn.
12667   if (IgnoreCommaOperand(LHS))
12668     return;
12669 
12670   Diag(Loc, diag::warn_comma_operator);
12671   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12672       << LHS->getSourceRange()
12673       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12674                                     LangOpts.CPlusPlus ? "static_cast<void>("
12675                                                        : "(void)(")
12676       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12677                                     ")");
12678 }
12679 
12680 // C99 6.5.17
12681 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12682                                    SourceLocation Loc) {
12683   LHS = S.CheckPlaceholderExpr(LHS.get());
12684   RHS = S.CheckPlaceholderExpr(RHS.get());
12685   if (LHS.isInvalid() || RHS.isInvalid())
12686     return QualType();
12687 
12688   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12689   // operands, but not unary promotions.
12690   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12691 
12692   // So we treat the LHS as a ignored value, and in C++ we allow the
12693   // containing site to determine what should be done with the RHS.
12694   LHS = S.IgnoredValueConversions(LHS.get());
12695   if (LHS.isInvalid())
12696     return QualType();
12697 
12698   S.DiagnoseUnusedExprResult(LHS.get());
12699 
12700   if (!S.getLangOpts().CPlusPlus) {
12701     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12702     if (RHS.isInvalid())
12703       return QualType();
12704     if (!RHS.get()->getType()->isVoidType())
12705       S.RequireCompleteType(Loc, RHS.get()->getType(),
12706                             diag::err_incomplete_type);
12707   }
12708 
12709   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12710     S.DiagnoseCommaOperator(LHS.get(), Loc);
12711 
12712   return RHS.get()->getType();
12713 }
12714 
12715 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12716 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12717 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12718                                                ExprValueKind &VK,
12719                                                ExprObjectKind &OK,
12720                                                SourceLocation OpLoc,
12721                                                bool IsInc, bool IsPrefix) {
12722   if (Op->isTypeDependent())
12723     return S.Context.DependentTy;
12724 
12725   QualType ResType = Op->getType();
12726   // Atomic types can be used for increment / decrement where the non-atomic
12727   // versions can, so ignore the _Atomic() specifier for the purpose of
12728   // checking.
12729   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12730     ResType = ResAtomicType->getValueType();
12731 
12732   assert(!ResType.isNull() && "no type for increment/decrement expression");
12733 
12734   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12735     // Decrement of bool is not allowed.
12736     if (!IsInc) {
12737       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12738       return QualType();
12739     }
12740     // Increment of bool sets it to true, but is deprecated.
12741     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12742                                               : diag::warn_increment_bool)
12743       << Op->getSourceRange();
12744   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12745     // Error on enum increments and decrements in C++ mode
12746     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12747     return QualType();
12748   } else if (ResType->isRealType()) {
12749     // OK!
12750   } else if (ResType->isPointerType()) {
12751     // C99 6.5.2.4p2, 6.5.6p2
12752     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12753       return QualType();
12754   } else if (ResType->isObjCObjectPointerType()) {
12755     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12756     // Otherwise, we just need a complete type.
12757     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12758         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12759       return QualType();
12760   } else if (ResType->isAnyComplexType()) {
12761     // C99 does not support ++/-- on complex types, we allow as an extension.
12762     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12763       << ResType << Op->getSourceRange();
12764   } else if (ResType->isPlaceholderType()) {
12765     ExprResult PR = S.CheckPlaceholderExpr(Op);
12766     if (PR.isInvalid()) return QualType();
12767     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12768                                           IsInc, IsPrefix);
12769   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12770     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12771   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12772              (ResType->castAs<VectorType>()->getVectorKind() !=
12773               VectorType::AltiVecBool)) {
12774     // The z vector extensions allow ++ and -- for non-bool vectors.
12775   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12776             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12777     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12778   } else {
12779     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12780       << ResType << int(IsInc) << Op->getSourceRange();
12781     return QualType();
12782   }
12783   // At this point, we know we have a real, complex or pointer type.
12784   // Now make sure the operand is a modifiable lvalue.
12785   if (CheckForModifiableLvalue(Op, OpLoc, S))
12786     return QualType();
12787   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12788     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12789     //   An operand with volatile-qualified type is deprecated
12790     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12791         << IsInc << ResType;
12792   }
12793   // In C++, a prefix increment is the same type as the operand. Otherwise
12794   // (in C or with postfix), the increment is the unqualified type of the
12795   // operand.
12796   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12797     VK = VK_LValue;
12798     OK = Op->getObjectKind();
12799     return ResType;
12800   } else {
12801     VK = VK_RValue;
12802     return ResType.getUnqualifiedType();
12803   }
12804 }
12805 
12806 
12807 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12808 /// This routine allows us to typecheck complex/recursive expressions
12809 /// where the declaration is needed for type checking. We only need to
12810 /// handle cases when the expression references a function designator
12811 /// or is an lvalue. Here are some examples:
12812 ///  - &(x) => x
12813 ///  - &*****f => f for f a function designator.
12814 ///  - &s.xx => s
12815 ///  - &s.zz[1].yy -> s, if zz is an array
12816 ///  - *(x + 1) -> x, if x is an array
12817 ///  - &"123"[2] -> 0
12818 ///  - & __real__ x -> x
12819 static ValueDecl *getPrimaryDecl(Expr *E) {
12820   switch (E->getStmtClass()) {
12821   case Stmt::DeclRefExprClass:
12822     return cast<DeclRefExpr>(E)->getDecl();
12823   case Stmt::MemberExprClass:
12824     // If this is an arrow operator, the address is an offset from
12825     // the base's value, so the object the base refers to is
12826     // irrelevant.
12827     if (cast<MemberExpr>(E)->isArrow())
12828       return nullptr;
12829     // Otherwise, the expression refers to a part of the base
12830     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12831   case Stmt::ArraySubscriptExprClass: {
12832     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12833     // promotion of register arrays earlier.
12834     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12835     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12836       if (ICE->getSubExpr()->getType()->isArrayType())
12837         return getPrimaryDecl(ICE->getSubExpr());
12838     }
12839     return nullptr;
12840   }
12841   case Stmt::UnaryOperatorClass: {
12842     UnaryOperator *UO = cast<UnaryOperator>(E);
12843 
12844     switch(UO->getOpcode()) {
12845     case UO_Real:
12846     case UO_Imag:
12847     case UO_Extension:
12848       return getPrimaryDecl(UO->getSubExpr());
12849     default:
12850       return nullptr;
12851     }
12852   }
12853   case Stmt::ParenExprClass:
12854     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12855   case Stmt::ImplicitCastExprClass:
12856     // If the result of an implicit cast is an l-value, we care about
12857     // the sub-expression; otherwise, the result here doesn't matter.
12858     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12859   default:
12860     return nullptr;
12861   }
12862 }
12863 
12864 namespace {
12865   enum {
12866     AO_Bit_Field = 0,
12867     AO_Vector_Element = 1,
12868     AO_Property_Expansion = 2,
12869     AO_Register_Variable = 3,
12870     AO_No_Error = 4
12871   };
12872 }
12873 /// Diagnose invalid operand for address of operations.
12874 ///
12875 /// \param Type The type of operand which cannot have its address taken.
12876 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12877                                          Expr *E, unsigned Type) {
12878   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12879 }
12880 
12881 /// CheckAddressOfOperand - The operand of & must be either a function
12882 /// designator or an lvalue designating an object. If it is an lvalue, the
12883 /// object cannot be declared with storage class register or be a bit field.
12884 /// Note: The usual conversions are *not* applied to the operand of the &
12885 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12886 /// In C++, the operand might be an overloaded function name, in which case
12887 /// we allow the '&' but retain the overloaded-function type.
12888 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12889   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12890     if (PTy->getKind() == BuiltinType::Overload) {
12891       Expr *E = OrigOp.get()->IgnoreParens();
12892       if (!isa<OverloadExpr>(E)) {
12893         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12894         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12895           << OrigOp.get()->getSourceRange();
12896         return QualType();
12897       }
12898 
12899       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12900       if (isa<UnresolvedMemberExpr>(Ovl))
12901         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12902           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12903             << OrigOp.get()->getSourceRange();
12904           return QualType();
12905         }
12906 
12907       return Context.OverloadTy;
12908     }
12909 
12910     if (PTy->getKind() == BuiltinType::UnknownAny)
12911       return Context.UnknownAnyTy;
12912 
12913     if (PTy->getKind() == BuiltinType::BoundMember) {
12914       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12915         << OrigOp.get()->getSourceRange();
12916       return QualType();
12917     }
12918 
12919     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12920     if (OrigOp.isInvalid()) return QualType();
12921   }
12922 
12923   if (OrigOp.get()->isTypeDependent())
12924     return Context.DependentTy;
12925 
12926   assert(!OrigOp.get()->getType()->isPlaceholderType());
12927 
12928   // Make sure to ignore parentheses in subsequent checks
12929   Expr *op = OrigOp.get()->IgnoreParens();
12930 
12931   // In OpenCL captures for blocks called as lambda functions
12932   // are located in the private address space. Blocks used in
12933   // enqueue_kernel can be located in a different address space
12934   // depending on a vendor implementation. Thus preventing
12935   // taking an address of the capture to avoid invalid AS casts.
12936   if (LangOpts.OpenCL) {
12937     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12938     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12939       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12940       return QualType();
12941     }
12942   }
12943 
12944   if (getLangOpts().C99) {
12945     // Implement C99-only parts of addressof rules.
12946     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12947       if (uOp->getOpcode() == UO_Deref)
12948         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12949         // (assuming the deref expression is valid).
12950         return uOp->getSubExpr()->getType();
12951     }
12952     // Technically, there should be a check for array subscript
12953     // expressions here, but the result of one is always an lvalue anyway.
12954   }
12955   ValueDecl *dcl = getPrimaryDecl(op);
12956 
12957   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12958     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12959                                            op->getBeginLoc()))
12960       return QualType();
12961 
12962   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12963   unsigned AddressOfError = AO_No_Error;
12964 
12965   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12966     bool sfinae = (bool)isSFINAEContext();
12967     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12968                                   : diag::ext_typecheck_addrof_temporary)
12969       << op->getType() << op->getSourceRange();
12970     if (sfinae)
12971       return QualType();
12972     // Materialize the temporary as an lvalue so that we can take its address.
12973     OrigOp = op =
12974         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12975   } else if (isa<ObjCSelectorExpr>(op)) {
12976     return Context.getPointerType(op->getType());
12977   } else if (lval == Expr::LV_MemberFunction) {
12978     // If it's an instance method, make a member pointer.
12979     // The expression must have exactly the form &A::foo.
12980 
12981     // If the underlying expression isn't a decl ref, give up.
12982     if (!isa<DeclRefExpr>(op)) {
12983       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12984         << OrigOp.get()->getSourceRange();
12985       return QualType();
12986     }
12987     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12988     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12989 
12990     // The id-expression was parenthesized.
12991     if (OrigOp.get() != DRE) {
12992       Diag(OpLoc, diag::err_parens_pointer_member_function)
12993         << OrigOp.get()->getSourceRange();
12994 
12995     // The method was named without a qualifier.
12996     } else if (!DRE->getQualifier()) {
12997       if (MD->getParent()->getName().empty())
12998         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12999           << op->getSourceRange();
13000       else {
13001         SmallString<32> Str;
13002         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13003         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13004           << op->getSourceRange()
13005           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13006       }
13007     }
13008 
13009     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13010     if (isa<CXXDestructorDecl>(MD))
13011       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13012 
13013     QualType MPTy = Context.getMemberPointerType(
13014         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13015     // Under the MS ABI, lock down the inheritance model now.
13016     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13017       (void)isCompleteType(OpLoc, MPTy);
13018     return MPTy;
13019   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13020     // C99 6.5.3.2p1
13021     // The operand must be either an l-value or a function designator
13022     if (!op->getType()->isFunctionType()) {
13023       // Use a special diagnostic for loads from property references.
13024       if (isa<PseudoObjectExpr>(op)) {
13025         AddressOfError = AO_Property_Expansion;
13026       } else {
13027         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13028           << op->getType() << op->getSourceRange();
13029         return QualType();
13030       }
13031     }
13032   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13033     // The operand cannot be a bit-field
13034     AddressOfError = AO_Bit_Field;
13035   } else if (op->getObjectKind() == OK_VectorComponent) {
13036     // The operand cannot be an element of a vector
13037     AddressOfError = AO_Vector_Element;
13038   } else if (dcl) { // C99 6.5.3.2p1
13039     // We have an lvalue with a decl. Make sure the decl is not declared
13040     // with the register storage-class specifier.
13041     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13042       // in C++ it is not error to take address of a register
13043       // variable (c++03 7.1.1P3)
13044       if (vd->getStorageClass() == SC_Register &&
13045           !getLangOpts().CPlusPlus) {
13046         AddressOfError = AO_Register_Variable;
13047       }
13048     } else if (isa<MSPropertyDecl>(dcl)) {
13049       AddressOfError = AO_Property_Expansion;
13050     } else if (isa<FunctionTemplateDecl>(dcl)) {
13051       return Context.OverloadTy;
13052     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13053       // Okay: we can take the address of a field.
13054       // Could be a pointer to member, though, if there is an explicit
13055       // scope qualifier for the class.
13056       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13057         DeclContext *Ctx = dcl->getDeclContext();
13058         if (Ctx && Ctx->isRecord()) {
13059           if (dcl->getType()->isReferenceType()) {
13060             Diag(OpLoc,
13061                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13062               << dcl->getDeclName() << dcl->getType();
13063             return QualType();
13064           }
13065 
13066           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13067             Ctx = Ctx->getParent();
13068 
13069           QualType MPTy = Context.getMemberPointerType(
13070               op->getType(),
13071               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13072           // Under the MS ABI, lock down the inheritance model now.
13073           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13074             (void)isCompleteType(OpLoc, MPTy);
13075           return MPTy;
13076         }
13077       }
13078     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13079                !isa<BindingDecl>(dcl))
13080       llvm_unreachable("Unknown/unexpected decl type");
13081   }
13082 
13083   if (AddressOfError != AO_No_Error) {
13084     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13085     return QualType();
13086   }
13087 
13088   if (lval == Expr::LV_IncompleteVoidType) {
13089     // Taking the address of a void variable is technically illegal, but we
13090     // allow it in cases which are otherwise valid.
13091     // Example: "extern void x; void* y = &x;".
13092     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13093   }
13094 
13095   // If the operand has type "type", the result has type "pointer to type".
13096   if (op->getType()->isObjCObjectType())
13097     return Context.getObjCObjectPointerType(op->getType());
13098 
13099   CheckAddressOfPackedMember(op);
13100 
13101   return Context.getPointerType(op->getType());
13102 }
13103 
13104 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13105   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13106   if (!DRE)
13107     return;
13108   const Decl *D = DRE->getDecl();
13109   if (!D)
13110     return;
13111   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13112   if (!Param)
13113     return;
13114   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13115     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13116       return;
13117   if (FunctionScopeInfo *FD = S.getCurFunction())
13118     if (!FD->ModifiedNonNullParams.count(Param))
13119       FD->ModifiedNonNullParams.insert(Param);
13120 }
13121 
13122 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13123 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13124                                         SourceLocation OpLoc) {
13125   if (Op->isTypeDependent())
13126     return S.Context.DependentTy;
13127 
13128   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13129   if (ConvResult.isInvalid())
13130     return QualType();
13131   Op = ConvResult.get();
13132   QualType OpTy = Op->getType();
13133   QualType Result;
13134 
13135   if (isa<CXXReinterpretCastExpr>(Op)) {
13136     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13137     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13138                                      Op->getSourceRange());
13139   }
13140 
13141   if (const PointerType *PT = OpTy->getAs<PointerType>())
13142   {
13143     Result = PT->getPointeeType();
13144   }
13145   else if (const ObjCObjectPointerType *OPT =
13146              OpTy->getAs<ObjCObjectPointerType>())
13147     Result = OPT->getPointeeType();
13148   else {
13149     ExprResult PR = S.CheckPlaceholderExpr(Op);
13150     if (PR.isInvalid()) return QualType();
13151     if (PR.get() != Op)
13152       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13153   }
13154 
13155   if (Result.isNull()) {
13156     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13157       << OpTy << Op->getSourceRange();
13158     return QualType();
13159   }
13160 
13161   // Note that per both C89 and C99, indirection is always legal, even if Result
13162   // is an incomplete type or void.  It would be possible to warn about
13163   // dereferencing a void pointer, but it's completely well-defined, and such a
13164   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13165   // for pointers to 'void' but is fine for any other pointer type:
13166   //
13167   // C++ [expr.unary.op]p1:
13168   //   [...] the expression to which [the unary * operator] is applied shall
13169   //   be a pointer to an object type, or a pointer to a function type
13170   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13171     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13172       << OpTy << Op->getSourceRange();
13173 
13174   // Dereferences are usually l-values...
13175   VK = VK_LValue;
13176 
13177   // ...except that certain expressions are never l-values in C.
13178   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13179     VK = VK_RValue;
13180 
13181   return Result;
13182 }
13183 
13184 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13185   BinaryOperatorKind Opc;
13186   switch (Kind) {
13187   default: llvm_unreachable("Unknown binop!");
13188   case tok::periodstar:           Opc = BO_PtrMemD; break;
13189   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13190   case tok::star:                 Opc = BO_Mul; break;
13191   case tok::slash:                Opc = BO_Div; break;
13192   case tok::percent:              Opc = BO_Rem; break;
13193   case tok::plus:                 Opc = BO_Add; break;
13194   case tok::minus:                Opc = BO_Sub; break;
13195   case tok::lessless:             Opc = BO_Shl; break;
13196   case tok::greatergreater:       Opc = BO_Shr; break;
13197   case tok::lessequal:            Opc = BO_LE; break;
13198   case tok::less:                 Opc = BO_LT; break;
13199   case tok::greaterequal:         Opc = BO_GE; break;
13200   case tok::greater:              Opc = BO_GT; break;
13201   case tok::exclaimequal:         Opc = BO_NE; break;
13202   case tok::equalequal:           Opc = BO_EQ; break;
13203   case tok::spaceship:            Opc = BO_Cmp; break;
13204   case tok::amp:                  Opc = BO_And; break;
13205   case tok::caret:                Opc = BO_Xor; break;
13206   case tok::pipe:                 Opc = BO_Or; break;
13207   case tok::ampamp:               Opc = BO_LAnd; break;
13208   case tok::pipepipe:             Opc = BO_LOr; break;
13209   case tok::equal:                Opc = BO_Assign; break;
13210   case tok::starequal:            Opc = BO_MulAssign; break;
13211   case tok::slashequal:           Opc = BO_DivAssign; break;
13212   case tok::percentequal:         Opc = BO_RemAssign; break;
13213   case tok::plusequal:            Opc = BO_AddAssign; break;
13214   case tok::minusequal:           Opc = BO_SubAssign; break;
13215   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13216   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13217   case tok::ampequal:             Opc = BO_AndAssign; break;
13218   case tok::caretequal:           Opc = BO_XorAssign; break;
13219   case tok::pipeequal:            Opc = BO_OrAssign; break;
13220   case tok::comma:                Opc = BO_Comma; break;
13221   }
13222   return Opc;
13223 }
13224 
13225 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13226   tok::TokenKind Kind) {
13227   UnaryOperatorKind Opc;
13228   switch (Kind) {
13229   default: llvm_unreachable("Unknown unary op!");
13230   case tok::plusplus:     Opc = UO_PreInc; break;
13231   case tok::minusminus:   Opc = UO_PreDec; break;
13232   case tok::amp:          Opc = UO_AddrOf; break;
13233   case tok::star:         Opc = UO_Deref; break;
13234   case tok::plus:         Opc = UO_Plus; break;
13235   case tok::minus:        Opc = UO_Minus; break;
13236   case tok::tilde:        Opc = UO_Not; break;
13237   case tok::exclaim:      Opc = UO_LNot; break;
13238   case tok::kw___real:    Opc = UO_Real; break;
13239   case tok::kw___imag:    Opc = UO_Imag; break;
13240   case tok::kw___extension__: Opc = UO_Extension; break;
13241   }
13242   return Opc;
13243 }
13244 
13245 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13246 /// This warning suppressed in the event of macro expansions.
13247 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13248                                    SourceLocation OpLoc, bool IsBuiltin) {
13249   if (S.inTemplateInstantiation())
13250     return;
13251   if (S.isUnevaluatedContext())
13252     return;
13253   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13254     return;
13255   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13256   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13257   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13258   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13259   if (!LHSDeclRef || !RHSDeclRef ||
13260       LHSDeclRef->getLocation().isMacroID() ||
13261       RHSDeclRef->getLocation().isMacroID())
13262     return;
13263   const ValueDecl *LHSDecl =
13264     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13265   const ValueDecl *RHSDecl =
13266     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13267   if (LHSDecl != RHSDecl)
13268     return;
13269   if (LHSDecl->getType().isVolatileQualified())
13270     return;
13271   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13272     if (RefTy->getPointeeType().isVolatileQualified())
13273       return;
13274 
13275   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13276                           : diag::warn_self_assignment_overloaded)
13277       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13278       << RHSExpr->getSourceRange();
13279 }
13280 
13281 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13282 /// is usually indicative of introspection within the Objective-C pointer.
13283 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13284                                           SourceLocation OpLoc) {
13285   if (!S.getLangOpts().ObjC)
13286     return;
13287 
13288   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13289   const Expr *LHS = L.get();
13290   const Expr *RHS = R.get();
13291 
13292   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13293     ObjCPointerExpr = LHS;
13294     OtherExpr = RHS;
13295   }
13296   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13297     ObjCPointerExpr = RHS;
13298     OtherExpr = LHS;
13299   }
13300 
13301   // This warning is deliberately made very specific to reduce false
13302   // positives with logic that uses '&' for hashing.  This logic mainly
13303   // looks for code trying to introspect into tagged pointers, which
13304   // code should generally never do.
13305   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13306     unsigned Diag = diag::warn_objc_pointer_masking;
13307     // Determine if we are introspecting the result of performSelectorXXX.
13308     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13309     // Special case messages to -performSelector and friends, which
13310     // can return non-pointer values boxed in a pointer value.
13311     // Some clients may wish to silence warnings in this subcase.
13312     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13313       Selector S = ME->getSelector();
13314       StringRef SelArg0 = S.getNameForSlot(0);
13315       if (SelArg0.startswith("performSelector"))
13316         Diag = diag::warn_objc_pointer_masking_performSelector;
13317     }
13318 
13319     S.Diag(OpLoc, Diag)
13320       << ObjCPointerExpr->getSourceRange();
13321   }
13322 }
13323 
13324 static NamedDecl *getDeclFromExpr(Expr *E) {
13325   if (!E)
13326     return nullptr;
13327   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13328     return DRE->getDecl();
13329   if (auto *ME = dyn_cast<MemberExpr>(E))
13330     return ME->getMemberDecl();
13331   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13332     return IRE->getDecl();
13333   return nullptr;
13334 }
13335 
13336 // This helper function promotes a binary operator's operands (which are of a
13337 // half vector type) to a vector of floats and then truncates the result to
13338 // a vector of either half or short.
13339 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13340                                       BinaryOperatorKind Opc, QualType ResultTy,
13341                                       ExprValueKind VK, ExprObjectKind OK,
13342                                       bool IsCompAssign, SourceLocation OpLoc,
13343                                       FPOptions FPFeatures) {
13344   auto &Context = S.getASTContext();
13345   assert((isVector(ResultTy, Context.HalfTy) ||
13346           isVector(ResultTy, Context.ShortTy)) &&
13347          "Result must be a vector of half or short");
13348   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13349          isVector(RHS.get()->getType(), Context.HalfTy) &&
13350          "both operands expected to be a half vector");
13351 
13352   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13353   QualType BinOpResTy = RHS.get()->getType();
13354 
13355   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13356   // change BinOpResTy to a vector of ints.
13357   if (isVector(ResultTy, Context.ShortTy))
13358     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13359 
13360   if (IsCompAssign)
13361     return new (Context) CompoundAssignOperator(
13362         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
13363         OpLoc, FPFeatures);
13364 
13365   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13366   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
13367                                           VK, OK, OpLoc, FPFeatures);
13368   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13369 }
13370 
13371 static std::pair<ExprResult, ExprResult>
13372 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13373                            Expr *RHSExpr) {
13374   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13375   if (!S.getLangOpts().CPlusPlus) {
13376     // C cannot handle TypoExpr nodes on either side of a binop because it
13377     // doesn't handle dependent types properly, so make sure any TypoExprs have
13378     // been dealt with before checking the operands.
13379     LHS = S.CorrectDelayedTyposInExpr(LHS);
13380     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13381       if (Opc != BO_Assign)
13382         return ExprResult(E);
13383       // Avoid correcting the RHS to the same Expr as the LHS.
13384       Decl *D = getDeclFromExpr(E);
13385       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13386     });
13387   }
13388   return std::make_pair(LHS, RHS);
13389 }
13390 
13391 /// Returns true if conversion between vectors of halfs and vectors of floats
13392 /// is needed.
13393 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13394                                      Expr *E0, Expr *E1 = nullptr) {
13395   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13396       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13397     return false;
13398 
13399   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13400     QualType Ty = E->IgnoreImplicit()->getType();
13401 
13402     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13403     // to vectors of floats. Although the element type of the vectors is __fp16,
13404     // the vectors shouldn't be treated as storage-only types. See the
13405     // discussion here: https://reviews.llvm.org/rG825235c140e7
13406     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13407       if (VT->getVectorKind() == VectorType::NeonVector)
13408         return false;
13409       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13410     }
13411     return false;
13412   };
13413 
13414   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13415 }
13416 
13417 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13418 /// operator @p Opc at location @c TokLoc. This routine only supports
13419 /// built-in operations; ActOnBinOp handles overloaded operators.
13420 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13421                                     BinaryOperatorKind Opc,
13422                                     Expr *LHSExpr, Expr *RHSExpr) {
13423   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13424     // The syntax only allows initializer lists on the RHS of assignment,
13425     // so we don't need to worry about accepting invalid code for
13426     // non-assignment operators.
13427     // C++11 5.17p9:
13428     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13429     //   of x = {} is x = T().
13430     InitializationKind Kind = InitializationKind::CreateDirectList(
13431         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13432     InitializedEntity Entity =
13433         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13434     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13435     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13436     if (Init.isInvalid())
13437       return Init;
13438     RHSExpr = Init.get();
13439   }
13440 
13441   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13442   QualType ResultTy;     // Result type of the binary operator.
13443   // The following two variables are used for compound assignment operators
13444   QualType CompLHSTy;    // Type of LHS after promotions for computation
13445   QualType CompResultTy; // Type of computation result
13446   ExprValueKind VK = VK_RValue;
13447   ExprObjectKind OK = OK_Ordinary;
13448   bool ConvertHalfVec = false;
13449 
13450   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13451   if (!LHS.isUsable() || !RHS.isUsable())
13452     return ExprError();
13453 
13454   if (getLangOpts().OpenCL) {
13455     QualType LHSTy = LHSExpr->getType();
13456     QualType RHSTy = RHSExpr->getType();
13457     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13458     // the ATOMIC_VAR_INIT macro.
13459     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13460       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13461       if (BO_Assign == Opc)
13462         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13463       else
13464         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13465       return ExprError();
13466     }
13467 
13468     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13469     // only with a builtin functions and therefore should be disallowed here.
13470     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13471         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13472         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13473         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13474       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13475       return ExprError();
13476     }
13477   }
13478 
13479   // Diagnose operations on the unsupported types for OpenMP device compilation.
13480   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13481     if (Opc != BO_Assign && Opc != BO_Comma) {
13482       checkOpenMPDeviceExpr(LHSExpr);
13483       checkOpenMPDeviceExpr(RHSExpr);
13484     }
13485   }
13486 
13487   switch (Opc) {
13488   case BO_Assign:
13489     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13490     if (getLangOpts().CPlusPlus &&
13491         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13492       VK = LHS.get()->getValueKind();
13493       OK = LHS.get()->getObjectKind();
13494     }
13495     if (!ResultTy.isNull()) {
13496       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13497       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13498 
13499       // Avoid copying a block to the heap if the block is assigned to a local
13500       // auto variable that is declared in the same scope as the block. This
13501       // optimization is unsafe if the local variable is declared in an outer
13502       // scope. For example:
13503       //
13504       // BlockTy b;
13505       // {
13506       //   b = ^{...};
13507       // }
13508       // // It is unsafe to invoke the block here if it wasn't copied to the
13509       // // heap.
13510       // b();
13511 
13512       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13513         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13514           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13515             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13516               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13517 
13518       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13519         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13520                               NTCUC_Assignment, NTCUK_Copy);
13521     }
13522     RecordModifiableNonNullParam(*this, LHS.get());
13523     break;
13524   case BO_PtrMemD:
13525   case BO_PtrMemI:
13526     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13527                                             Opc == BO_PtrMemI);
13528     break;
13529   case BO_Mul:
13530   case BO_Div:
13531     ConvertHalfVec = true;
13532     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13533                                            Opc == BO_Div);
13534     break;
13535   case BO_Rem:
13536     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13537     break;
13538   case BO_Add:
13539     ConvertHalfVec = true;
13540     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13541     break;
13542   case BO_Sub:
13543     ConvertHalfVec = true;
13544     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13545     break;
13546   case BO_Shl:
13547   case BO_Shr:
13548     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13549     break;
13550   case BO_LE:
13551   case BO_LT:
13552   case BO_GE:
13553   case BO_GT:
13554     ConvertHalfVec = true;
13555     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13556     break;
13557   case BO_EQ:
13558   case BO_NE:
13559     ConvertHalfVec = true;
13560     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13561     break;
13562   case BO_Cmp:
13563     ConvertHalfVec = true;
13564     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13565     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13566     break;
13567   case BO_And:
13568     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13569     LLVM_FALLTHROUGH;
13570   case BO_Xor:
13571   case BO_Or:
13572     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13573     break;
13574   case BO_LAnd:
13575   case BO_LOr:
13576     ConvertHalfVec = true;
13577     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13578     break;
13579   case BO_MulAssign:
13580   case BO_DivAssign:
13581     ConvertHalfVec = true;
13582     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13583                                                Opc == BO_DivAssign);
13584     CompLHSTy = CompResultTy;
13585     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13586       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13587     break;
13588   case BO_RemAssign:
13589     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13590     CompLHSTy = CompResultTy;
13591     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13592       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13593     break;
13594   case BO_AddAssign:
13595     ConvertHalfVec = true;
13596     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13597     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13598       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13599     break;
13600   case BO_SubAssign:
13601     ConvertHalfVec = true;
13602     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13603     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13604       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13605     break;
13606   case BO_ShlAssign:
13607   case BO_ShrAssign:
13608     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13609     CompLHSTy = CompResultTy;
13610     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13611       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13612     break;
13613   case BO_AndAssign:
13614   case BO_OrAssign: // fallthrough
13615     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13616     LLVM_FALLTHROUGH;
13617   case BO_XorAssign:
13618     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13619     CompLHSTy = CompResultTy;
13620     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13621       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13622     break;
13623   case BO_Comma:
13624     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13625     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13626       VK = RHS.get()->getValueKind();
13627       OK = RHS.get()->getObjectKind();
13628     }
13629     break;
13630   }
13631   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13632     return ExprError();
13633 
13634   // The LHS is not converted to the result type for fixed-point compound
13635   // assignment as the common type is computed on demand. Reset the CompLHSTy
13636   // to the LHS type we would have gotten after unary conversions.
13637   if (!CompLHSTy.isNull() &&
13638       (LHS.get()->getType()->isFixedPointType() ||
13639        RHS.get()->getType()->isFixedPointType()))
13640     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13641 
13642   if (ResultTy->isRealFloatingType() &&
13643       (getLangOpts().getFPRoundingMode() != RoundingMode::NearestTiesToEven ||
13644        getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13645     // Mark the current function as usng floating point constrained intrinsics
13646     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13647       F->setUsesFPIntrin(true);
13648     }
13649 
13650   // Some of the binary operations require promoting operands of half vector to
13651   // float vectors and truncating the result back to half vector. For now, we do
13652   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13653   // arm64).
13654   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13655          isVector(LHS.get()->getType(), Context.HalfTy) &&
13656          "both sides are half vectors or neither sides are");
13657   ConvertHalfVec =
13658       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13659 
13660   // Check for array bounds violations for both sides of the BinaryOperator
13661   CheckArrayAccess(LHS.get());
13662   CheckArrayAccess(RHS.get());
13663 
13664   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13665     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13666                                                  &Context.Idents.get("object_setClass"),
13667                                                  SourceLocation(), LookupOrdinaryName);
13668     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13669       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13670       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13671           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13672                                         "object_setClass(")
13673           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13674                                           ",")
13675           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13676     }
13677     else
13678       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13679   }
13680   else if (const ObjCIvarRefExpr *OIRE =
13681            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13682     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13683 
13684   // Opc is not a compound assignment if CompResultTy is null.
13685   if (CompResultTy.isNull()) {
13686     if (ConvertHalfVec)
13687       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13688                                  OpLoc, FPFeatures);
13689     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13690                                         OK, OpLoc, FPFeatures);
13691   }
13692 
13693   // Handle compound assignments.
13694   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13695       OK_ObjCProperty) {
13696     VK = VK_LValue;
13697     OK = LHS.get()->getObjectKind();
13698   }
13699 
13700   if (ConvertHalfVec)
13701     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13702                                OpLoc, FPFeatures);
13703 
13704   return new (Context) CompoundAssignOperator(
13705       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13706       OpLoc, FPFeatures);
13707 }
13708 
13709 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13710 /// operators are mixed in a way that suggests that the programmer forgot that
13711 /// comparison operators have higher precedence. The most typical example of
13712 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13713 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13714                                       SourceLocation OpLoc, Expr *LHSExpr,
13715                                       Expr *RHSExpr) {
13716   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13717   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13718 
13719   // Check that one of the sides is a comparison operator and the other isn't.
13720   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13721   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13722   if (isLeftComp == isRightComp)
13723     return;
13724 
13725   // Bitwise operations are sometimes used as eager logical ops.
13726   // Don't diagnose this.
13727   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13728   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13729   if (isLeftBitwise || isRightBitwise)
13730     return;
13731 
13732   SourceRange DiagRange = isLeftComp
13733                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13734                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13735   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13736   SourceRange ParensRange =
13737       isLeftComp
13738           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13739           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13740 
13741   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13742     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13743   SuggestParentheses(Self, OpLoc,
13744     Self.PDiag(diag::note_precedence_silence) << OpStr,
13745     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13746   SuggestParentheses(Self, OpLoc,
13747     Self.PDiag(diag::note_precedence_bitwise_first)
13748       << BinaryOperator::getOpcodeStr(Opc),
13749     ParensRange);
13750 }
13751 
13752 /// It accepts a '&&' expr that is inside a '||' one.
13753 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13754 /// in parentheses.
13755 static void
13756 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13757                                        BinaryOperator *Bop) {
13758   assert(Bop->getOpcode() == BO_LAnd);
13759   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13760       << Bop->getSourceRange() << OpLoc;
13761   SuggestParentheses(Self, Bop->getOperatorLoc(),
13762     Self.PDiag(diag::note_precedence_silence)
13763       << Bop->getOpcodeStr(),
13764     Bop->getSourceRange());
13765 }
13766 
13767 /// Returns true if the given expression can be evaluated as a constant
13768 /// 'true'.
13769 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13770   bool Res;
13771   return !E->isValueDependent() &&
13772          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13773 }
13774 
13775 /// Returns true if the given expression can be evaluated as a constant
13776 /// 'false'.
13777 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13778   bool Res;
13779   return !E->isValueDependent() &&
13780          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13781 }
13782 
13783 /// Look for '&&' in the left hand of a '||' expr.
13784 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13785                                              Expr *LHSExpr, Expr *RHSExpr) {
13786   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13787     if (Bop->getOpcode() == BO_LAnd) {
13788       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13789       if (EvaluatesAsFalse(S, RHSExpr))
13790         return;
13791       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13792       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13793         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13794     } else if (Bop->getOpcode() == BO_LOr) {
13795       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13796         // If it's "a || b && 1 || c" we didn't warn earlier for
13797         // "a || b && 1", but warn now.
13798         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13799           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13800       }
13801     }
13802   }
13803 }
13804 
13805 /// Look for '&&' in the right hand of a '||' expr.
13806 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13807                                              Expr *LHSExpr, Expr *RHSExpr) {
13808   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13809     if (Bop->getOpcode() == BO_LAnd) {
13810       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13811       if (EvaluatesAsFalse(S, LHSExpr))
13812         return;
13813       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13814       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13815         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13816     }
13817   }
13818 }
13819 
13820 /// Look for bitwise op in the left or right hand of a bitwise op with
13821 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13822 /// the '&' expression in parentheses.
13823 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13824                                          SourceLocation OpLoc, Expr *SubExpr) {
13825   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13826     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13827       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13828         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13829         << Bop->getSourceRange() << OpLoc;
13830       SuggestParentheses(S, Bop->getOperatorLoc(),
13831         S.PDiag(diag::note_precedence_silence)
13832           << Bop->getOpcodeStr(),
13833         Bop->getSourceRange());
13834     }
13835   }
13836 }
13837 
13838 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13839                                     Expr *SubExpr, StringRef Shift) {
13840   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13841     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13842       StringRef Op = Bop->getOpcodeStr();
13843       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13844           << Bop->getSourceRange() << OpLoc << Shift << Op;
13845       SuggestParentheses(S, Bop->getOperatorLoc(),
13846           S.PDiag(diag::note_precedence_silence) << Op,
13847           Bop->getSourceRange());
13848     }
13849   }
13850 }
13851 
13852 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13853                                  Expr *LHSExpr, Expr *RHSExpr) {
13854   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13855   if (!OCE)
13856     return;
13857 
13858   FunctionDecl *FD = OCE->getDirectCallee();
13859   if (!FD || !FD->isOverloadedOperator())
13860     return;
13861 
13862   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13863   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13864     return;
13865 
13866   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13867       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13868       << (Kind == OO_LessLess);
13869   SuggestParentheses(S, OCE->getOperatorLoc(),
13870                      S.PDiag(diag::note_precedence_silence)
13871                          << (Kind == OO_LessLess ? "<<" : ">>"),
13872                      OCE->getSourceRange());
13873   SuggestParentheses(
13874       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13875       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13876 }
13877 
13878 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13879 /// precedence.
13880 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13881                                     SourceLocation OpLoc, Expr *LHSExpr,
13882                                     Expr *RHSExpr){
13883   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13884   if (BinaryOperator::isBitwiseOp(Opc))
13885     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13886 
13887   // Diagnose "arg1 & arg2 | arg3"
13888   if ((Opc == BO_Or || Opc == BO_Xor) &&
13889       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13890     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13891     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13892   }
13893 
13894   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13895   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13896   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13897     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13898     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13899   }
13900 
13901   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13902       || Opc == BO_Shr) {
13903     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13904     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13905     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13906   }
13907 
13908   // Warn on overloaded shift operators and comparisons, such as:
13909   // cout << 5 == 4;
13910   if (BinaryOperator::isComparisonOp(Opc))
13911     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13912 }
13913 
13914 // Binary Operators.  'Tok' is the token for the operator.
13915 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13916                             tok::TokenKind Kind,
13917                             Expr *LHSExpr, Expr *RHSExpr) {
13918   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13919   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13920   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13921 
13922   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13923   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13924 
13925   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13926 }
13927 
13928 /// Build an overloaded binary operator expression in the given scope.
13929 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13930                                        BinaryOperatorKind Opc,
13931                                        Expr *LHS, Expr *RHS) {
13932   switch (Opc) {
13933   case BO_Assign:
13934   case BO_DivAssign:
13935   case BO_RemAssign:
13936   case BO_SubAssign:
13937   case BO_AndAssign:
13938   case BO_OrAssign:
13939   case BO_XorAssign:
13940     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13941     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13942     break;
13943   default:
13944     break;
13945   }
13946 
13947   // Find all of the overloaded operators visible from this
13948   // point. We perform both an operator-name lookup from the local
13949   // scope and an argument-dependent lookup based on the types of
13950   // the arguments.
13951   UnresolvedSet<16> Functions;
13952   OverloadedOperatorKind OverOp
13953     = BinaryOperator::getOverloadedOperator(Opc);
13954   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13955     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13956                                    RHS->getType(), Functions);
13957 
13958   // In C++20 onwards, we may have a second operator to look up.
13959   if (S.getLangOpts().CPlusPlus2a) {
13960     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13961       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13962                                      RHS->getType(), Functions);
13963   }
13964 
13965   // Build the (potentially-overloaded, potentially-dependent)
13966   // binary operation.
13967   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13968 }
13969 
13970 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13971                             BinaryOperatorKind Opc,
13972                             Expr *LHSExpr, Expr *RHSExpr) {
13973   ExprResult LHS, RHS;
13974   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13975   if (!LHS.isUsable() || !RHS.isUsable())
13976     return ExprError();
13977   LHSExpr = LHS.get();
13978   RHSExpr = RHS.get();
13979 
13980   // We want to end up calling one of checkPseudoObjectAssignment
13981   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13982   // both expressions are overloadable or either is type-dependent),
13983   // or CreateBuiltinBinOp (in any other case).  We also want to get
13984   // any placeholder types out of the way.
13985 
13986   // Handle pseudo-objects in the LHS.
13987   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13988     // Assignments with a pseudo-object l-value need special analysis.
13989     if (pty->getKind() == BuiltinType::PseudoObject &&
13990         BinaryOperator::isAssignmentOp(Opc))
13991       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13992 
13993     // Don't resolve overloads if the other type is overloadable.
13994     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13995       // We can't actually test that if we still have a placeholder,
13996       // though.  Fortunately, none of the exceptions we see in that
13997       // code below are valid when the LHS is an overload set.  Note
13998       // that an overload set can be dependently-typed, but it never
13999       // instantiates to having an overloadable type.
14000       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14001       if (resolvedRHS.isInvalid()) return ExprError();
14002       RHSExpr = resolvedRHS.get();
14003 
14004       if (RHSExpr->isTypeDependent() ||
14005           RHSExpr->getType()->isOverloadableType())
14006         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14007     }
14008 
14009     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14010     // template, diagnose the missing 'template' keyword instead of diagnosing
14011     // an invalid use of a bound member function.
14012     //
14013     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14014     // to C++1z [over.over]/1.4, but we already checked for that case above.
14015     if (Opc == BO_LT && inTemplateInstantiation() &&
14016         (pty->getKind() == BuiltinType::BoundMember ||
14017          pty->getKind() == BuiltinType::Overload)) {
14018       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14019       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14020           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14021             return isa<FunctionTemplateDecl>(ND);
14022           })) {
14023         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14024                                 : OE->getNameLoc(),
14025              diag::err_template_kw_missing)
14026           << OE->getName().getAsString() << "";
14027         return ExprError();
14028       }
14029     }
14030 
14031     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14032     if (LHS.isInvalid()) return ExprError();
14033     LHSExpr = LHS.get();
14034   }
14035 
14036   // Handle pseudo-objects in the RHS.
14037   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14038     // An overload in the RHS can potentially be resolved by the type
14039     // being assigned to.
14040     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14041       if (getLangOpts().CPlusPlus &&
14042           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14043            LHSExpr->getType()->isOverloadableType()))
14044         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14045 
14046       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14047     }
14048 
14049     // Don't resolve overloads if the other type is overloadable.
14050     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14051         LHSExpr->getType()->isOverloadableType())
14052       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14053 
14054     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14055     if (!resolvedRHS.isUsable()) return ExprError();
14056     RHSExpr = resolvedRHS.get();
14057   }
14058 
14059   if (getLangOpts().CPlusPlus) {
14060     // If either expression is type-dependent, always build an
14061     // overloaded op.
14062     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14063       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14064 
14065     // Otherwise, build an overloaded op if either expression has an
14066     // overloadable type.
14067     if (LHSExpr->getType()->isOverloadableType() ||
14068         RHSExpr->getType()->isOverloadableType())
14069       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14070   }
14071 
14072   // Build a built-in binary operation.
14073   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14074 }
14075 
14076 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14077   if (T.isNull() || T->isDependentType())
14078     return false;
14079 
14080   if (!T->isPromotableIntegerType())
14081     return true;
14082 
14083   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14084 }
14085 
14086 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14087                                       UnaryOperatorKind Opc,
14088                                       Expr *InputExpr) {
14089   ExprResult Input = InputExpr;
14090   ExprValueKind VK = VK_RValue;
14091   ExprObjectKind OK = OK_Ordinary;
14092   QualType resultType;
14093   bool CanOverflow = false;
14094 
14095   bool ConvertHalfVec = false;
14096   if (getLangOpts().OpenCL) {
14097     QualType Ty = InputExpr->getType();
14098     // The only legal unary operation for atomics is '&'.
14099     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14100     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14101     // only with a builtin functions and therefore should be disallowed here.
14102         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14103         || Ty->isBlockPointerType())) {
14104       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14105                        << InputExpr->getType()
14106                        << Input.get()->getSourceRange());
14107     }
14108   }
14109   // Diagnose operations on the unsupported types for OpenMP device compilation.
14110   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
14111     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
14112         UnaryOperator::isArithmeticOp(Opc))
14113       checkOpenMPDeviceExpr(InputExpr);
14114   }
14115 
14116   switch (Opc) {
14117   case UO_PreInc:
14118   case UO_PreDec:
14119   case UO_PostInc:
14120   case UO_PostDec:
14121     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14122                                                 OpLoc,
14123                                                 Opc == UO_PreInc ||
14124                                                 Opc == UO_PostInc,
14125                                                 Opc == UO_PreInc ||
14126                                                 Opc == UO_PreDec);
14127     CanOverflow = isOverflowingIntegerType(Context, resultType);
14128     break;
14129   case UO_AddrOf:
14130     resultType = CheckAddressOfOperand(Input, OpLoc);
14131     CheckAddressOfNoDeref(InputExpr);
14132     RecordModifiableNonNullParam(*this, InputExpr);
14133     break;
14134   case UO_Deref: {
14135     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14136     if (Input.isInvalid()) return ExprError();
14137     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14138     break;
14139   }
14140   case UO_Plus:
14141   case UO_Minus:
14142     CanOverflow = Opc == UO_Minus &&
14143                   isOverflowingIntegerType(Context, Input.get()->getType());
14144     Input = UsualUnaryConversions(Input.get());
14145     if (Input.isInvalid()) return ExprError();
14146     // Unary plus and minus require promoting an operand of half vector to a
14147     // float vector and truncating the result back to a half vector. For now, we
14148     // do this only when HalfArgsAndReturns is set (that is, when the target is
14149     // arm or arm64).
14150     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14151 
14152     // If the operand is a half vector, promote it to a float vector.
14153     if (ConvertHalfVec)
14154       Input = convertVector(Input.get(), Context.FloatTy, *this);
14155     resultType = Input.get()->getType();
14156     if (resultType->isDependentType())
14157       break;
14158     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14159       break;
14160     else if (resultType->isVectorType() &&
14161              // The z vector extensions don't allow + or - with bool vectors.
14162              (!Context.getLangOpts().ZVector ||
14163               resultType->castAs<VectorType>()->getVectorKind() !=
14164               VectorType::AltiVecBool))
14165       break;
14166     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14167              Opc == UO_Plus &&
14168              resultType->isPointerType())
14169       break;
14170 
14171     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14172       << resultType << Input.get()->getSourceRange());
14173 
14174   case UO_Not: // bitwise complement
14175     Input = UsualUnaryConversions(Input.get());
14176     if (Input.isInvalid())
14177       return ExprError();
14178     resultType = Input.get()->getType();
14179     if (resultType->isDependentType())
14180       break;
14181     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14182     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14183       // C99 does not support '~' for complex conjugation.
14184       Diag(OpLoc, diag::ext_integer_complement_complex)
14185           << resultType << Input.get()->getSourceRange();
14186     else if (resultType->hasIntegerRepresentation())
14187       break;
14188     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14189       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14190       // on vector float types.
14191       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14192       if (!T->isIntegerType())
14193         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14194                           << resultType << Input.get()->getSourceRange());
14195     } else {
14196       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14197                        << resultType << Input.get()->getSourceRange());
14198     }
14199     break;
14200 
14201   case UO_LNot: // logical negation
14202     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14203     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14204     if (Input.isInvalid()) return ExprError();
14205     resultType = Input.get()->getType();
14206 
14207     // Though we still have to promote half FP to float...
14208     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14209       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14210       resultType = Context.FloatTy;
14211     }
14212 
14213     if (resultType->isDependentType())
14214       break;
14215     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14216       // C99 6.5.3.3p1: ok, fallthrough;
14217       if (Context.getLangOpts().CPlusPlus) {
14218         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14219         // operand contextually converted to bool.
14220         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14221                                   ScalarTypeToBooleanCastKind(resultType));
14222       } else if (Context.getLangOpts().OpenCL &&
14223                  Context.getLangOpts().OpenCLVersion < 120) {
14224         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14225         // operate on scalar float types.
14226         if (!resultType->isIntegerType() && !resultType->isPointerType())
14227           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14228                            << resultType << Input.get()->getSourceRange());
14229       }
14230     } else if (resultType->isExtVectorType()) {
14231       if (Context.getLangOpts().OpenCL &&
14232           Context.getLangOpts().OpenCLVersion < 120 &&
14233           !Context.getLangOpts().OpenCLCPlusPlus) {
14234         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14235         // operate on vector float types.
14236         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14237         if (!T->isIntegerType())
14238           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14239                            << resultType << Input.get()->getSourceRange());
14240       }
14241       // Vector logical not returns the signed variant of the operand type.
14242       resultType = GetSignedVectorType(resultType);
14243       break;
14244     } else {
14245       // FIXME: GCC's vector extension permits the usage of '!' with a vector
14246       //        type in C++. We should allow that here too.
14247       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14248         << resultType << Input.get()->getSourceRange());
14249     }
14250 
14251     // LNot always has type int. C99 6.5.3.3p5.
14252     // In C++, it's bool. C++ 5.3.1p8
14253     resultType = Context.getLogicalOperationType();
14254     break;
14255   case UO_Real:
14256   case UO_Imag:
14257     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14258     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14259     // complex l-values to ordinary l-values and all other values to r-values.
14260     if (Input.isInvalid()) return ExprError();
14261     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14262       if (Input.get()->getValueKind() != VK_RValue &&
14263           Input.get()->getObjectKind() == OK_Ordinary)
14264         VK = Input.get()->getValueKind();
14265     } else if (!getLangOpts().CPlusPlus) {
14266       // In C, a volatile scalar is read by __imag. In C++, it is not.
14267       Input = DefaultLvalueConversion(Input.get());
14268     }
14269     break;
14270   case UO_Extension:
14271     resultType = Input.get()->getType();
14272     VK = Input.get()->getValueKind();
14273     OK = Input.get()->getObjectKind();
14274     break;
14275   case UO_Coawait:
14276     // It's unnecessary to represent the pass-through operator co_await in the
14277     // AST; just return the input expression instead.
14278     assert(!Input.get()->getType()->isDependentType() &&
14279                    "the co_await expression must be non-dependant before "
14280                    "building operator co_await");
14281     return Input;
14282   }
14283   if (resultType.isNull() || Input.isInvalid())
14284     return ExprError();
14285 
14286   // Check for array bounds violations in the operand of the UnaryOperator,
14287   // except for the '*' and '&' operators that have to be handled specially
14288   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14289   // that are explicitly defined as valid by the standard).
14290   if (Opc != UO_AddrOf && Opc != UO_Deref)
14291     CheckArrayAccess(Input.get());
14292 
14293   auto *UO = new (Context)
14294       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
14295 
14296   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14297       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14298     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14299 
14300   // Convert the result back to a half vector.
14301   if (ConvertHalfVec)
14302     return convertVector(UO, Context.HalfTy, *this);
14303   return UO;
14304 }
14305 
14306 /// Determine whether the given expression is a qualified member
14307 /// access expression, of a form that could be turned into a pointer to member
14308 /// with the address-of operator.
14309 bool Sema::isQualifiedMemberAccess(Expr *E) {
14310   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14311     if (!DRE->getQualifier())
14312       return false;
14313 
14314     ValueDecl *VD = DRE->getDecl();
14315     if (!VD->isCXXClassMember())
14316       return false;
14317 
14318     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14319       return true;
14320     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14321       return Method->isInstance();
14322 
14323     return false;
14324   }
14325 
14326   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14327     if (!ULE->getQualifier())
14328       return false;
14329 
14330     for (NamedDecl *D : ULE->decls()) {
14331       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14332         if (Method->isInstance())
14333           return true;
14334       } else {
14335         // Overload set does not contain methods.
14336         break;
14337       }
14338     }
14339 
14340     return false;
14341   }
14342 
14343   return false;
14344 }
14345 
14346 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14347                               UnaryOperatorKind Opc, Expr *Input) {
14348   // First things first: handle placeholders so that the
14349   // overloaded-operator check considers the right type.
14350   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14351     // Increment and decrement of pseudo-object references.
14352     if (pty->getKind() == BuiltinType::PseudoObject &&
14353         UnaryOperator::isIncrementDecrementOp(Opc))
14354       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14355 
14356     // extension is always a builtin operator.
14357     if (Opc == UO_Extension)
14358       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14359 
14360     // & gets special logic for several kinds of placeholder.
14361     // The builtin code knows what to do.
14362     if (Opc == UO_AddrOf &&
14363         (pty->getKind() == BuiltinType::Overload ||
14364          pty->getKind() == BuiltinType::UnknownAny ||
14365          pty->getKind() == BuiltinType::BoundMember))
14366       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14367 
14368     // Anything else needs to be handled now.
14369     ExprResult Result = CheckPlaceholderExpr(Input);
14370     if (Result.isInvalid()) return ExprError();
14371     Input = Result.get();
14372   }
14373 
14374   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14375       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14376       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14377     // Find all of the overloaded operators visible from this
14378     // point. We perform both an operator-name lookup from the local
14379     // scope and an argument-dependent lookup based on the types of
14380     // the arguments.
14381     UnresolvedSet<16> Functions;
14382     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14383     if (S && OverOp != OO_None)
14384       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14385                                    Functions);
14386 
14387     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14388   }
14389 
14390   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14391 }
14392 
14393 // Unary Operators.  'Tok' is the token for the operator.
14394 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14395                               tok::TokenKind Op, Expr *Input) {
14396   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14397 }
14398 
14399 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14400 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14401                                 LabelDecl *TheDecl) {
14402   TheDecl->markUsed(Context);
14403   // Create the AST node.  The address of a label always has type 'void*'.
14404   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14405                                      Context.getPointerType(Context.VoidTy));
14406 }
14407 
14408 void Sema::ActOnStartStmtExpr() {
14409   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14410 }
14411 
14412 void Sema::ActOnStmtExprError() {
14413   // Note that function is also called by TreeTransform when leaving a
14414   // StmtExpr scope without rebuilding anything.
14415 
14416   DiscardCleanupsInEvaluationContext();
14417   PopExpressionEvaluationContext();
14418 }
14419 
14420 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14421                                SourceLocation RPLoc) {
14422   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14423 }
14424 
14425 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14426                                SourceLocation RPLoc, unsigned TemplateDepth) {
14427   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14428   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14429 
14430   if (hasAnyUnrecoverableErrorsInThisFunction())
14431     DiscardCleanupsInEvaluationContext();
14432   assert(!Cleanup.exprNeedsCleanups() &&
14433          "cleanups within StmtExpr not correctly bound!");
14434   PopExpressionEvaluationContext();
14435 
14436   // FIXME: there are a variety of strange constraints to enforce here, for
14437   // example, it is not possible to goto into a stmt expression apparently.
14438   // More semantic analysis is needed.
14439 
14440   // If there are sub-stmts in the compound stmt, take the type of the last one
14441   // as the type of the stmtexpr.
14442   QualType Ty = Context.VoidTy;
14443   bool StmtExprMayBindToTemp = false;
14444   if (!Compound->body_empty()) {
14445     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14446     if (const auto *LastStmt =
14447             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14448       if (const Expr *Value = LastStmt->getExprStmt()) {
14449         StmtExprMayBindToTemp = true;
14450         Ty = Value->getType();
14451       }
14452     }
14453   }
14454 
14455   // FIXME: Check that expression type is complete/non-abstract; statement
14456   // expressions are not lvalues.
14457   Expr *ResStmtExpr =
14458       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14459   if (StmtExprMayBindToTemp)
14460     return MaybeBindToTemporary(ResStmtExpr);
14461   return ResStmtExpr;
14462 }
14463 
14464 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14465   if (ER.isInvalid())
14466     return ExprError();
14467 
14468   // Do function/array conversion on the last expression, but not
14469   // lvalue-to-rvalue.  However, initialize an unqualified type.
14470   ER = DefaultFunctionArrayConversion(ER.get());
14471   if (ER.isInvalid())
14472     return ExprError();
14473   Expr *E = ER.get();
14474 
14475   if (E->isTypeDependent())
14476     return E;
14477 
14478   // In ARC, if the final expression ends in a consume, splice
14479   // the consume out and bind it later.  In the alternate case
14480   // (when dealing with a retainable type), the result
14481   // initialization will create a produce.  In both cases the
14482   // result will be +1, and we'll need to balance that out with
14483   // a bind.
14484   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14485   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14486     return Cast->getSubExpr();
14487 
14488   // FIXME: Provide a better location for the initialization.
14489   return PerformCopyInitialization(
14490       InitializedEntity::InitializeStmtExprResult(
14491           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14492       SourceLocation(), E);
14493 }
14494 
14495 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14496                                       TypeSourceInfo *TInfo,
14497                                       ArrayRef<OffsetOfComponent> Components,
14498                                       SourceLocation RParenLoc) {
14499   QualType ArgTy = TInfo->getType();
14500   bool Dependent = ArgTy->isDependentType();
14501   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14502 
14503   // We must have at least one component that refers to the type, and the first
14504   // one is known to be a field designator.  Verify that the ArgTy represents
14505   // a struct/union/class.
14506   if (!Dependent && !ArgTy->isRecordType())
14507     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14508                        << ArgTy << TypeRange);
14509 
14510   // Type must be complete per C99 7.17p3 because a declaring a variable
14511   // with an incomplete type would be ill-formed.
14512   if (!Dependent
14513       && RequireCompleteType(BuiltinLoc, ArgTy,
14514                              diag::err_offsetof_incomplete_type, TypeRange))
14515     return ExprError();
14516 
14517   bool DidWarnAboutNonPOD = false;
14518   QualType CurrentType = ArgTy;
14519   SmallVector<OffsetOfNode, 4> Comps;
14520   SmallVector<Expr*, 4> Exprs;
14521   for (const OffsetOfComponent &OC : Components) {
14522     if (OC.isBrackets) {
14523       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14524       if (!CurrentType->isDependentType()) {
14525         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14526         if(!AT)
14527           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14528                            << CurrentType);
14529         CurrentType = AT->getElementType();
14530       } else
14531         CurrentType = Context.DependentTy;
14532 
14533       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14534       if (IdxRval.isInvalid())
14535         return ExprError();
14536       Expr *Idx = IdxRval.get();
14537 
14538       // The expression must be an integral expression.
14539       // FIXME: An integral constant expression?
14540       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14541           !Idx->getType()->isIntegerType())
14542         return ExprError(
14543             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14544             << Idx->getSourceRange());
14545 
14546       // Record this array index.
14547       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14548       Exprs.push_back(Idx);
14549       continue;
14550     }
14551 
14552     // Offset of a field.
14553     if (CurrentType->isDependentType()) {
14554       // We have the offset of a field, but we can't look into the dependent
14555       // type. Just record the identifier of the field.
14556       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14557       CurrentType = Context.DependentTy;
14558       continue;
14559     }
14560 
14561     // We need to have a complete type to look into.
14562     if (RequireCompleteType(OC.LocStart, CurrentType,
14563                             diag::err_offsetof_incomplete_type))
14564       return ExprError();
14565 
14566     // Look for the designated field.
14567     const RecordType *RC = CurrentType->getAs<RecordType>();
14568     if (!RC)
14569       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14570                        << CurrentType);
14571     RecordDecl *RD = RC->getDecl();
14572 
14573     // C++ [lib.support.types]p5:
14574     //   The macro offsetof accepts a restricted set of type arguments in this
14575     //   International Standard. type shall be a POD structure or a POD union
14576     //   (clause 9).
14577     // C++11 [support.types]p4:
14578     //   If type is not a standard-layout class (Clause 9), the results are
14579     //   undefined.
14580     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14581       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14582       unsigned DiagID =
14583         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14584                             : diag::ext_offsetof_non_pod_type;
14585 
14586       if (!IsSafe && !DidWarnAboutNonPOD &&
14587           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14588                               PDiag(DiagID)
14589                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14590                               << CurrentType))
14591         DidWarnAboutNonPOD = true;
14592     }
14593 
14594     // Look for the field.
14595     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14596     LookupQualifiedName(R, RD);
14597     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14598     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14599     if (!MemberDecl) {
14600       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14601         MemberDecl = IndirectMemberDecl->getAnonField();
14602     }
14603 
14604     if (!MemberDecl)
14605       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14606                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14607                                                               OC.LocEnd));
14608 
14609     // C99 7.17p3:
14610     //   (If the specified member is a bit-field, the behavior is undefined.)
14611     //
14612     // We diagnose this as an error.
14613     if (MemberDecl->isBitField()) {
14614       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14615         << MemberDecl->getDeclName()
14616         << SourceRange(BuiltinLoc, RParenLoc);
14617       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14618       return ExprError();
14619     }
14620 
14621     RecordDecl *Parent = MemberDecl->getParent();
14622     if (IndirectMemberDecl)
14623       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14624 
14625     // If the member was found in a base class, introduce OffsetOfNodes for
14626     // the base class indirections.
14627     CXXBasePaths Paths;
14628     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14629                       Paths)) {
14630       if (Paths.getDetectedVirtual()) {
14631         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14632           << MemberDecl->getDeclName()
14633           << SourceRange(BuiltinLoc, RParenLoc);
14634         return ExprError();
14635       }
14636 
14637       CXXBasePath &Path = Paths.front();
14638       for (const CXXBasePathElement &B : Path)
14639         Comps.push_back(OffsetOfNode(B.Base));
14640     }
14641 
14642     if (IndirectMemberDecl) {
14643       for (auto *FI : IndirectMemberDecl->chain()) {
14644         assert(isa<FieldDecl>(FI));
14645         Comps.push_back(OffsetOfNode(OC.LocStart,
14646                                      cast<FieldDecl>(FI), OC.LocEnd));
14647       }
14648     } else
14649       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14650 
14651     CurrentType = MemberDecl->getType().getNonReferenceType();
14652   }
14653 
14654   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14655                               Comps, Exprs, RParenLoc);
14656 }
14657 
14658 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14659                                       SourceLocation BuiltinLoc,
14660                                       SourceLocation TypeLoc,
14661                                       ParsedType ParsedArgTy,
14662                                       ArrayRef<OffsetOfComponent> Components,
14663                                       SourceLocation RParenLoc) {
14664 
14665   TypeSourceInfo *ArgTInfo;
14666   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14667   if (ArgTy.isNull())
14668     return ExprError();
14669 
14670   if (!ArgTInfo)
14671     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14672 
14673   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14674 }
14675 
14676 
14677 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14678                                  Expr *CondExpr,
14679                                  Expr *LHSExpr, Expr *RHSExpr,
14680                                  SourceLocation RPLoc) {
14681   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14682 
14683   ExprValueKind VK = VK_RValue;
14684   ExprObjectKind OK = OK_Ordinary;
14685   QualType resType;
14686   bool CondIsTrue = false;
14687   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14688     resType = Context.DependentTy;
14689   } else {
14690     // The conditional expression is required to be a constant expression.
14691     llvm::APSInt condEval(32);
14692     ExprResult CondICE
14693       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14694           diag::err_typecheck_choose_expr_requires_constant, false);
14695     if (CondICE.isInvalid())
14696       return ExprError();
14697     CondExpr = CondICE.get();
14698     CondIsTrue = condEval.getZExtValue();
14699 
14700     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14701     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14702 
14703     resType = ActiveExpr->getType();
14704     VK = ActiveExpr->getValueKind();
14705     OK = ActiveExpr->getObjectKind();
14706   }
14707 
14708   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14709                                   resType, VK, OK, RPLoc, CondIsTrue);
14710 }
14711 
14712 //===----------------------------------------------------------------------===//
14713 // Clang Extensions.
14714 //===----------------------------------------------------------------------===//
14715 
14716 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14717 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14718   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14719 
14720   if (LangOpts.CPlusPlus) {
14721     MangleNumberingContext *MCtx;
14722     Decl *ManglingContextDecl;
14723     std::tie(MCtx, ManglingContextDecl) =
14724         getCurrentMangleNumberContext(Block->getDeclContext());
14725     if (MCtx) {
14726       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14727       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14728     }
14729   }
14730 
14731   PushBlockScope(CurScope, Block);
14732   CurContext->addDecl(Block);
14733   if (CurScope)
14734     PushDeclContext(CurScope, Block);
14735   else
14736     CurContext = Block;
14737 
14738   getCurBlock()->HasImplicitReturnType = true;
14739 
14740   // Enter a new evaluation context to insulate the block from any
14741   // cleanups from the enclosing full-expression.
14742   PushExpressionEvaluationContext(
14743       ExpressionEvaluationContext::PotentiallyEvaluated);
14744 }
14745 
14746 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14747                                Scope *CurScope) {
14748   assert(ParamInfo.getIdentifier() == nullptr &&
14749          "block-id should have no identifier!");
14750   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14751   BlockScopeInfo *CurBlock = getCurBlock();
14752 
14753   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14754   QualType T = Sig->getType();
14755 
14756   // FIXME: We should allow unexpanded parameter packs here, but that would,
14757   // in turn, make the block expression contain unexpanded parameter packs.
14758   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14759     // Drop the parameters.
14760     FunctionProtoType::ExtProtoInfo EPI;
14761     EPI.HasTrailingReturn = false;
14762     EPI.TypeQuals.addConst();
14763     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14764     Sig = Context.getTrivialTypeSourceInfo(T);
14765   }
14766 
14767   // GetTypeForDeclarator always produces a function type for a block
14768   // literal signature.  Furthermore, it is always a FunctionProtoType
14769   // unless the function was written with a typedef.
14770   assert(T->isFunctionType() &&
14771          "GetTypeForDeclarator made a non-function block signature");
14772 
14773   // Look for an explicit signature in that function type.
14774   FunctionProtoTypeLoc ExplicitSignature;
14775 
14776   if ((ExplicitSignature = Sig->getTypeLoc()
14777                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14778 
14779     // Check whether that explicit signature was synthesized by
14780     // GetTypeForDeclarator.  If so, don't save that as part of the
14781     // written signature.
14782     if (ExplicitSignature.getLocalRangeBegin() ==
14783         ExplicitSignature.getLocalRangeEnd()) {
14784       // This would be much cheaper if we stored TypeLocs instead of
14785       // TypeSourceInfos.
14786       TypeLoc Result = ExplicitSignature.getReturnLoc();
14787       unsigned Size = Result.getFullDataSize();
14788       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14789       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14790 
14791       ExplicitSignature = FunctionProtoTypeLoc();
14792     }
14793   }
14794 
14795   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14796   CurBlock->FunctionType = T;
14797 
14798   const FunctionType *Fn = T->getAs<FunctionType>();
14799   QualType RetTy = Fn->getReturnType();
14800   bool isVariadic =
14801     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14802 
14803   CurBlock->TheDecl->setIsVariadic(isVariadic);
14804 
14805   // Context.DependentTy is used as a placeholder for a missing block
14806   // return type.  TODO:  what should we do with declarators like:
14807   //   ^ * { ... }
14808   // If the answer is "apply template argument deduction"....
14809   if (RetTy != Context.DependentTy) {
14810     CurBlock->ReturnType = RetTy;
14811     CurBlock->TheDecl->setBlockMissingReturnType(false);
14812     CurBlock->HasImplicitReturnType = false;
14813   }
14814 
14815   // Push block parameters from the declarator if we had them.
14816   SmallVector<ParmVarDecl*, 8> Params;
14817   if (ExplicitSignature) {
14818     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14819       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14820       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
14821           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
14822         // Diagnose this as an extension in C17 and earlier.
14823         if (!getLangOpts().C2x)
14824           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14825       }
14826       Params.push_back(Param);
14827     }
14828 
14829   // Fake up parameter variables if we have a typedef, like
14830   //   ^ fntype { ... }
14831   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14832     for (const auto &I : Fn->param_types()) {
14833       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14834           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14835       Params.push_back(Param);
14836     }
14837   }
14838 
14839   // Set the parameters on the block decl.
14840   if (!Params.empty()) {
14841     CurBlock->TheDecl->setParams(Params);
14842     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14843                              /*CheckParameterNames=*/false);
14844   }
14845 
14846   // Finally we can process decl attributes.
14847   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14848 
14849   // Put the parameter variables in scope.
14850   for (auto AI : CurBlock->TheDecl->parameters()) {
14851     AI->setOwningFunction(CurBlock->TheDecl);
14852 
14853     // If this has an identifier, add it to the scope stack.
14854     if (AI->getIdentifier()) {
14855       CheckShadow(CurBlock->TheScope, AI);
14856 
14857       PushOnScopeChains(AI, CurBlock->TheScope);
14858     }
14859   }
14860 }
14861 
14862 /// ActOnBlockError - If there is an error parsing a block, this callback
14863 /// is invoked to pop the information about the block from the action impl.
14864 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14865   // Leave the expression-evaluation context.
14866   DiscardCleanupsInEvaluationContext();
14867   PopExpressionEvaluationContext();
14868 
14869   // Pop off CurBlock, handle nested blocks.
14870   PopDeclContext();
14871   PopFunctionScopeInfo();
14872 }
14873 
14874 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14875 /// literal was successfully completed.  ^(int x){...}
14876 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14877                                     Stmt *Body, Scope *CurScope) {
14878   // If blocks are disabled, emit an error.
14879   if (!LangOpts.Blocks)
14880     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14881 
14882   // Leave the expression-evaluation context.
14883   if (hasAnyUnrecoverableErrorsInThisFunction())
14884     DiscardCleanupsInEvaluationContext();
14885   assert(!Cleanup.exprNeedsCleanups() &&
14886          "cleanups within block not correctly bound!");
14887   PopExpressionEvaluationContext();
14888 
14889   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14890   BlockDecl *BD = BSI->TheDecl;
14891 
14892   if (BSI->HasImplicitReturnType)
14893     deduceClosureReturnType(*BSI);
14894 
14895   QualType RetTy = Context.VoidTy;
14896   if (!BSI->ReturnType.isNull())
14897     RetTy = BSI->ReturnType;
14898 
14899   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14900   QualType BlockTy;
14901 
14902   // If the user wrote a function type in some form, try to use that.
14903   if (!BSI->FunctionType.isNull()) {
14904     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14905 
14906     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14907     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14908 
14909     // Turn protoless block types into nullary block types.
14910     if (isa<FunctionNoProtoType>(FTy)) {
14911       FunctionProtoType::ExtProtoInfo EPI;
14912       EPI.ExtInfo = Ext;
14913       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14914 
14915     // Otherwise, if we don't need to change anything about the function type,
14916     // preserve its sugar structure.
14917     } else if (FTy->getReturnType() == RetTy &&
14918                (!NoReturn || FTy->getNoReturnAttr())) {
14919       BlockTy = BSI->FunctionType;
14920 
14921     // Otherwise, make the minimal modifications to the function type.
14922     } else {
14923       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14924       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14925       EPI.TypeQuals = Qualifiers();
14926       EPI.ExtInfo = Ext;
14927       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14928     }
14929 
14930   // If we don't have a function type, just build one from nothing.
14931   } else {
14932     FunctionProtoType::ExtProtoInfo EPI;
14933     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14934     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14935   }
14936 
14937   DiagnoseUnusedParameters(BD->parameters());
14938   BlockTy = Context.getBlockPointerType(BlockTy);
14939 
14940   // If needed, diagnose invalid gotos and switches in the block.
14941   if (getCurFunction()->NeedsScopeChecking() &&
14942       !PP.isCodeCompletionEnabled())
14943     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14944 
14945   BD->setBody(cast<CompoundStmt>(Body));
14946 
14947   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14948     DiagnoseUnguardedAvailabilityViolations(BD);
14949 
14950   // Try to apply the named return value optimization. We have to check again
14951   // if we can do this, though, because blocks keep return statements around
14952   // to deduce an implicit return type.
14953   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14954       !BD->isDependentContext())
14955     computeNRVO(Body, BSI);
14956 
14957   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14958       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14959     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14960                           NTCUK_Destruct|NTCUK_Copy);
14961 
14962   PopDeclContext();
14963 
14964   // Pop the block scope now but keep it alive to the end of this function.
14965   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14966   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14967 
14968   // Set the captured variables on the block.
14969   SmallVector<BlockDecl::Capture, 4> Captures;
14970   for (Capture &Cap : BSI->Captures) {
14971     if (Cap.isInvalid() || Cap.isThisCapture())
14972       continue;
14973 
14974     VarDecl *Var = Cap.getVariable();
14975     Expr *CopyExpr = nullptr;
14976     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14977       if (const RecordType *Record =
14978               Cap.getCaptureType()->getAs<RecordType>()) {
14979         // The capture logic needs the destructor, so make sure we mark it.
14980         // Usually this is unnecessary because most local variables have
14981         // their destructors marked at declaration time, but parameters are
14982         // an exception because it's technically only the call site that
14983         // actually requires the destructor.
14984         if (isa<ParmVarDecl>(Var))
14985           FinalizeVarWithDestructor(Var, Record);
14986 
14987         // Enter a separate potentially-evaluated context while building block
14988         // initializers to isolate their cleanups from those of the block
14989         // itself.
14990         // FIXME: Is this appropriate even when the block itself occurs in an
14991         // unevaluated operand?
14992         EnterExpressionEvaluationContext EvalContext(
14993             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14994 
14995         SourceLocation Loc = Cap.getLocation();
14996 
14997         ExprResult Result = BuildDeclarationNameExpr(
14998             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14999 
15000         // According to the blocks spec, the capture of a variable from
15001         // the stack requires a const copy constructor.  This is not true
15002         // of the copy/move done to move a __block variable to the heap.
15003         if (!Result.isInvalid() &&
15004             !Result.get()->getType().isConstQualified()) {
15005           Result = ImpCastExprToType(Result.get(),
15006                                      Result.get()->getType().withConst(),
15007                                      CK_NoOp, VK_LValue);
15008         }
15009 
15010         if (!Result.isInvalid()) {
15011           Result = PerformCopyInitialization(
15012               InitializedEntity::InitializeBlock(Var->getLocation(),
15013                                                  Cap.getCaptureType(), false),
15014               Loc, Result.get());
15015         }
15016 
15017         // Build a full-expression copy expression if initialization
15018         // succeeded and used a non-trivial constructor.  Recover from
15019         // errors by pretending that the copy isn't necessary.
15020         if (!Result.isInvalid() &&
15021             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15022                 ->isTrivial()) {
15023           Result = MaybeCreateExprWithCleanups(Result);
15024           CopyExpr = Result.get();
15025         }
15026       }
15027     }
15028 
15029     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15030                               CopyExpr);
15031     Captures.push_back(NewCap);
15032   }
15033   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15034 
15035   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15036 
15037   // If the block isn't obviously global, i.e. it captures anything at
15038   // all, then we need to do a few things in the surrounding context:
15039   if (Result->getBlockDecl()->hasCaptures()) {
15040     // First, this expression has a new cleanup object.
15041     ExprCleanupObjects.push_back(Result->getBlockDecl());
15042     Cleanup.setExprNeedsCleanups(true);
15043 
15044     // It also gets a branch-protected scope if any of the captured
15045     // variables needs destruction.
15046     for (const auto &CI : Result->getBlockDecl()->captures()) {
15047       const VarDecl *var = CI.getVariable();
15048       if (var->getType().isDestructedType() != QualType::DK_none) {
15049         setFunctionHasBranchProtectedScope();
15050         break;
15051       }
15052     }
15053   }
15054 
15055   if (getCurFunction())
15056     getCurFunction()->addBlock(BD);
15057 
15058   return Result;
15059 }
15060 
15061 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15062                             SourceLocation RPLoc) {
15063   TypeSourceInfo *TInfo;
15064   GetTypeFromParser(Ty, &TInfo);
15065   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15066 }
15067 
15068 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15069                                 Expr *E, TypeSourceInfo *TInfo,
15070                                 SourceLocation RPLoc) {
15071   Expr *OrigExpr = E;
15072   bool IsMS = false;
15073 
15074   // CUDA device code does not support varargs.
15075   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15076     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15077       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15078       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15079         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15080     }
15081   }
15082 
15083   // NVPTX does not support va_arg expression.
15084   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15085       Context.getTargetInfo().getTriple().isNVPTX())
15086     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15087 
15088   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15089   // as Microsoft ABI on an actual Microsoft platform, where
15090   // __builtin_ms_va_list and __builtin_va_list are the same.)
15091   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15092       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15093     QualType MSVaListType = Context.getBuiltinMSVaListType();
15094     if (Context.hasSameType(MSVaListType, E->getType())) {
15095       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15096         return ExprError();
15097       IsMS = true;
15098     }
15099   }
15100 
15101   // Get the va_list type
15102   QualType VaListType = Context.getBuiltinVaListType();
15103   if (!IsMS) {
15104     if (VaListType->isArrayType()) {
15105       // Deal with implicit array decay; for example, on x86-64,
15106       // va_list is an array, but it's supposed to decay to
15107       // a pointer for va_arg.
15108       VaListType = Context.getArrayDecayedType(VaListType);
15109       // Make sure the input expression also decays appropriately.
15110       ExprResult Result = UsualUnaryConversions(E);
15111       if (Result.isInvalid())
15112         return ExprError();
15113       E = Result.get();
15114     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15115       // If va_list is a record type and we are compiling in C++ mode,
15116       // check the argument using reference binding.
15117       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15118           Context, Context.getLValueReferenceType(VaListType), false);
15119       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15120       if (Init.isInvalid())
15121         return ExprError();
15122       E = Init.getAs<Expr>();
15123     } else {
15124       // Otherwise, the va_list argument must be an l-value because
15125       // it is modified by va_arg.
15126       if (!E->isTypeDependent() &&
15127           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15128         return ExprError();
15129     }
15130   }
15131 
15132   if (!IsMS && !E->isTypeDependent() &&
15133       !Context.hasSameType(VaListType, E->getType()))
15134     return ExprError(
15135         Diag(E->getBeginLoc(),
15136              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15137         << OrigExpr->getType() << E->getSourceRange());
15138 
15139   if (!TInfo->getType()->isDependentType()) {
15140     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15141                             diag::err_second_parameter_to_va_arg_incomplete,
15142                             TInfo->getTypeLoc()))
15143       return ExprError();
15144 
15145     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15146                                TInfo->getType(),
15147                                diag::err_second_parameter_to_va_arg_abstract,
15148                                TInfo->getTypeLoc()))
15149       return ExprError();
15150 
15151     if (!TInfo->getType().isPODType(Context)) {
15152       Diag(TInfo->getTypeLoc().getBeginLoc(),
15153            TInfo->getType()->isObjCLifetimeType()
15154              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15155              : diag::warn_second_parameter_to_va_arg_not_pod)
15156         << TInfo->getType()
15157         << TInfo->getTypeLoc().getSourceRange();
15158     }
15159 
15160     // Check for va_arg where arguments of the given type will be promoted
15161     // (i.e. this va_arg is guaranteed to have undefined behavior).
15162     QualType PromoteType;
15163     if (TInfo->getType()->isPromotableIntegerType()) {
15164       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15165       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15166         PromoteType = QualType();
15167     }
15168     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15169       PromoteType = Context.DoubleTy;
15170     if (!PromoteType.isNull())
15171       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15172                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15173                           << TInfo->getType()
15174                           << PromoteType
15175                           << TInfo->getTypeLoc().getSourceRange());
15176   }
15177 
15178   QualType T = TInfo->getType().getNonLValueExprType(Context);
15179   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15180 }
15181 
15182 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15183   // The type of __null will be int or long, depending on the size of
15184   // pointers on the target.
15185   QualType Ty;
15186   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15187   if (pw == Context.getTargetInfo().getIntWidth())
15188     Ty = Context.IntTy;
15189   else if (pw == Context.getTargetInfo().getLongWidth())
15190     Ty = Context.LongTy;
15191   else if (pw == Context.getTargetInfo().getLongLongWidth())
15192     Ty = Context.LongLongTy;
15193   else {
15194     llvm_unreachable("I don't know size of pointer!");
15195   }
15196 
15197   return new (Context) GNUNullExpr(Ty, TokenLoc);
15198 }
15199 
15200 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15201                                     SourceLocation BuiltinLoc,
15202                                     SourceLocation RPLoc) {
15203   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15204 }
15205 
15206 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15207                                     SourceLocation BuiltinLoc,
15208                                     SourceLocation RPLoc,
15209                                     DeclContext *ParentContext) {
15210   return new (Context)
15211       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15212 }
15213 
15214 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
15215                                               bool Diagnose) {
15216   if (!getLangOpts().ObjC)
15217     return false;
15218 
15219   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15220   if (!PT)
15221     return false;
15222 
15223   if (!PT->isObjCIdType()) {
15224     // Check if the destination is the 'NSString' interface.
15225     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15226     if (!ID || !ID->getIdentifier()->isStr("NSString"))
15227       return false;
15228   }
15229 
15230   // Ignore any parens, implicit casts (should only be
15231   // array-to-pointer decays), and not-so-opaque values.  The last is
15232   // important for making this trigger for property assignments.
15233   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15234   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15235     if (OV->getSourceExpr())
15236       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15237 
15238   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
15239   if (!SL || !SL->isAscii())
15240     return false;
15241   if (Diagnose) {
15242     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15243         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15244     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15245   }
15246   return true;
15247 }
15248 
15249 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15250                                               const Expr *SrcExpr) {
15251   if (!DstType->isFunctionPointerType() ||
15252       !SrcExpr->getType()->isFunctionType())
15253     return false;
15254 
15255   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15256   if (!DRE)
15257     return false;
15258 
15259   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15260   if (!FD)
15261     return false;
15262 
15263   return !S.checkAddressOfFunctionIsAvailable(FD,
15264                                               /*Complain=*/true,
15265                                               SrcExpr->getBeginLoc());
15266 }
15267 
15268 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15269                                     SourceLocation Loc,
15270                                     QualType DstType, QualType SrcType,
15271                                     Expr *SrcExpr, AssignmentAction Action,
15272                                     bool *Complained) {
15273   if (Complained)
15274     *Complained = false;
15275 
15276   // Decode the result (notice that AST's are still created for extensions).
15277   bool CheckInferredResultType = false;
15278   bool isInvalid = false;
15279   unsigned DiagKind = 0;
15280   FixItHint Hint;
15281   ConversionFixItGenerator ConvHints;
15282   bool MayHaveConvFixit = false;
15283   bool MayHaveFunctionDiff = false;
15284   const ObjCInterfaceDecl *IFace = nullptr;
15285   const ObjCProtocolDecl *PDecl = nullptr;
15286 
15287   switch (ConvTy) {
15288   case Compatible:
15289       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15290       return false;
15291 
15292   case PointerToInt:
15293     if (getLangOpts().CPlusPlus) {
15294       DiagKind = diag::err_typecheck_convert_pointer_int;
15295       isInvalid = true;
15296     } else {
15297       DiagKind = diag::ext_typecheck_convert_pointer_int;
15298     }
15299     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15300     MayHaveConvFixit = true;
15301     break;
15302   case IntToPointer:
15303     if (getLangOpts().CPlusPlus) {
15304       DiagKind = diag::err_typecheck_convert_int_pointer;
15305       isInvalid = true;
15306     } else {
15307       DiagKind = diag::ext_typecheck_convert_int_pointer;
15308     }
15309     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15310     MayHaveConvFixit = true;
15311     break;
15312   case IncompatibleFunctionPointer:
15313     if (getLangOpts().CPlusPlus) {
15314       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15315       isInvalid = true;
15316     } else {
15317       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15318     }
15319     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15320     MayHaveConvFixit = true;
15321     break;
15322   case IncompatiblePointer:
15323     if (Action == AA_Passing_CFAudited) {
15324       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15325     } else if (getLangOpts().CPlusPlus) {
15326       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15327       isInvalid = true;
15328     } else {
15329       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15330     }
15331     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15332       SrcType->isObjCObjectPointerType();
15333     if (Hint.isNull() && !CheckInferredResultType) {
15334       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15335     }
15336     else if (CheckInferredResultType) {
15337       SrcType = SrcType.getUnqualifiedType();
15338       DstType = DstType.getUnqualifiedType();
15339     }
15340     MayHaveConvFixit = true;
15341     break;
15342   case IncompatiblePointerSign:
15343     if (getLangOpts().CPlusPlus) {
15344       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15345       isInvalid = true;
15346     } else {
15347       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15348     }
15349     break;
15350   case FunctionVoidPointer:
15351     if (getLangOpts().CPlusPlus) {
15352       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15353       isInvalid = true;
15354     } else {
15355       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15356     }
15357     break;
15358   case IncompatiblePointerDiscardsQualifiers: {
15359     // Perform array-to-pointer decay if necessary.
15360     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15361 
15362     isInvalid = true;
15363 
15364     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15365     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15366     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15367       DiagKind = diag::err_typecheck_incompatible_address_space;
15368       break;
15369 
15370     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15371       DiagKind = diag::err_typecheck_incompatible_ownership;
15372       break;
15373     }
15374 
15375     llvm_unreachable("unknown error case for discarding qualifiers!");
15376     // fallthrough
15377   }
15378   case CompatiblePointerDiscardsQualifiers:
15379     // If the qualifiers lost were because we were applying the
15380     // (deprecated) C++ conversion from a string literal to a char*
15381     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15382     // Ideally, this check would be performed in
15383     // checkPointerTypesForAssignment. However, that would require a
15384     // bit of refactoring (so that the second argument is an
15385     // expression, rather than a type), which should be done as part
15386     // of a larger effort to fix checkPointerTypesForAssignment for
15387     // C++ semantics.
15388     if (getLangOpts().CPlusPlus &&
15389         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15390       return false;
15391     if (getLangOpts().CPlusPlus) {
15392       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15393       isInvalid = true;
15394     } else {
15395       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15396     }
15397 
15398     break;
15399   case IncompatibleNestedPointerQualifiers:
15400     if (getLangOpts().CPlusPlus) {
15401       isInvalid = true;
15402       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15403     } else {
15404       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15405     }
15406     break;
15407   case IncompatibleNestedPointerAddressSpaceMismatch:
15408     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15409     isInvalid = true;
15410     break;
15411   case IntToBlockPointer:
15412     DiagKind = diag::err_int_to_block_pointer;
15413     isInvalid = true;
15414     break;
15415   case IncompatibleBlockPointer:
15416     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15417     isInvalid = true;
15418     break;
15419   case IncompatibleObjCQualifiedId: {
15420     if (SrcType->isObjCQualifiedIdType()) {
15421       const ObjCObjectPointerType *srcOPT =
15422                 SrcType->castAs<ObjCObjectPointerType>();
15423       for (auto *srcProto : srcOPT->quals()) {
15424         PDecl = srcProto;
15425         break;
15426       }
15427       if (const ObjCInterfaceType *IFaceT =
15428             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15429         IFace = IFaceT->getDecl();
15430     }
15431     else if (DstType->isObjCQualifiedIdType()) {
15432       const ObjCObjectPointerType *dstOPT =
15433         DstType->castAs<ObjCObjectPointerType>();
15434       for (auto *dstProto : dstOPT->quals()) {
15435         PDecl = dstProto;
15436         break;
15437       }
15438       if (const ObjCInterfaceType *IFaceT =
15439             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15440         IFace = IFaceT->getDecl();
15441     }
15442     if (getLangOpts().CPlusPlus) {
15443       DiagKind = diag::err_incompatible_qualified_id;
15444       isInvalid = true;
15445     } else {
15446       DiagKind = diag::warn_incompatible_qualified_id;
15447     }
15448     break;
15449   }
15450   case IncompatibleVectors:
15451     if (getLangOpts().CPlusPlus) {
15452       DiagKind = diag::err_incompatible_vectors;
15453       isInvalid = true;
15454     } else {
15455       DiagKind = diag::warn_incompatible_vectors;
15456     }
15457     break;
15458   case IncompatibleObjCWeakRef:
15459     DiagKind = diag::err_arc_weak_unavailable_assign;
15460     isInvalid = true;
15461     break;
15462   case Incompatible:
15463     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15464       if (Complained)
15465         *Complained = true;
15466       return true;
15467     }
15468 
15469     DiagKind = diag::err_typecheck_convert_incompatible;
15470     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15471     MayHaveConvFixit = true;
15472     isInvalid = true;
15473     MayHaveFunctionDiff = true;
15474     break;
15475   }
15476 
15477   QualType FirstType, SecondType;
15478   switch (Action) {
15479   case AA_Assigning:
15480   case AA_Initializing:
15481     // The destination type comes first.
15482     FirstType = DstType;
15483     SecondType = SrcType;
15484     break;
15485 
15486   case AA_Returning:
15487   case AA_Passing:
15488   case AA_Passing_CFAudited:
15489   case AA_Converting:
15490   case AA_Sending:
15491   case AA_Casting:
15492     // The source type comes first.
15493     FirstType = SrcType;
15494     SecondType = DstType;
15495     break;
15496   }
15497 
15498   PartialDiagnostic FDiag = PDiag(DiagKind);
15499   if (Action == AA_Passing_CFAudited)
15500     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15501   else
15502     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15503 
15504   // If we can fix the conversion, suggest the FixIts.
15505   assert(ConvHints.isNull() || Hint.isNull());
15506   if (!ConvHints.isNull()) {
15507     for (FixItHint &H : ConvHints.Hints)
15508       FDiag << H;
15509   } else {
15510     FDiag << Hint;
15511   }
15512   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15513 
15514   if (MayHaveFunctionDiff)
15515     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15516 
15517   Diag(Loc, FDiag);
15518   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15519        DiagKind == diag::err_incompatible_qualified_id) &&
15520       PDecl && IFace && !IFace->hasDefinition())
15521     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15522         << IFace << PDecl;
15523 
15524   if (SecondType == Context.OverloadTy)
15525     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15526                               FirstType, /*TakingAddress=*/true);
15527 
15528   if (CheckInferredResultType)
15529     EmitRelatedResultTypeNote(SrcExpr);
15530 
15531   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15532     EmitRelatedResultTypeNoteForReturn(DstType);
15533 
15534   if (Complained)
15535     *Complained = true;
15536   return isInvalid;
15537 }
15538 
15539 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15540                                                  llvm::APSInt *Result) {
15541   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15542   public:
15543     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15544       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15545     }
15546   } Diagnoser;
15547 
15548   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15549 }
15550 
15551 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15552                                                  llvm::APSInt *Result,
15553                                                  unsigned DiagID,
15554                                                  bool AllowFold) {
15555   class IDDiagnoser : public VerifyICEDiagnoser {
15556     unsigned DiagID;
15557 
15558   public:
15559     IDDiagnoser(unsigned DiagID)
15560       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15561 
15562     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15563       S.Diag(Loc, DiagID) << SR;
15564     }
15565   } Diagnoser(DiagID);
15566 
15567   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15568 }
15569 
15570 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15571                                             SourceRange SR) {
15572   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15573 }
15574 
15575 ExprResult
15576 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15577                                       VerifyICEDiagnoser &Diagnoser,
15578                                       bool AllowFold) {
15579   SourceLocation DiagLoc = E->getBeginLoc();
15580 
15581   if (getLangOpts().CPlusPlus11) {
15582     // C++11 [expr.const]p5:
15583     //   If an expression of literal class type is used in a context where an
15584     //   integral constant expression is required, then that class type shall
15585     //   have a single non-explicit conversion function to an integral or
15586     //   unscoped enumeration type
15587     ExprResult Converted;
15588     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15589     public:
15590       CXX11ConvertDiagnoser(bool Silent)
15591           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15592                                 Silent, true) {}
15593 
15594       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15595                                            QualType T) override {
15596         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15597       }
15598 
15599       SemaDiagnosticBuilder diagnoseIncomplete(
15600           Sema &S, SourceLocation Loc, QualType T) override {
15601         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15602       }
15603 
15604       SemaDiagnosticBuilder diagnoseExplicitConv(
15605           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15606         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15607       }
15608 
15609       SemaDiagnosticBuilder noteExplicitConv(
15610           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15611         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15612                  << ConvTy->isEnumeralType() << ConvTy;
15613       }
15614 
15615       SemaDiagnosticBuilder diagnoseAmbiguous(
15616           Sema &S, SourceLocation Loc, QualType T) override {
15617         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15618       }
15619 
15620       SemaDiagnosticBuilder noteAmbiguous(
15621           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15622         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15623                  << ConvTy->isEnumeralType() << ConvTy;
15624       }
15625 
15626       SemaDiagnosticBuilder diagnoseConversion(
15627           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15628         llvm_unreachable("conversion functions are permitted");
15629       }
15630     } ConvertDiagnoser(Diagnoser.Suppress);
15631 
15632     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15633                                                     ConvertDiagnoser);
15634     if (Converted.isInvalid())
15635       return Converted;
15636     E = Converted.get();
15637     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15638       return ExprError();
15639   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15640     // An ICE must be of integral or unscoped enumeration type.
15641     if (!Diagnoser.Suppress)
15642       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15643     return ExprError();
15644   }
15645 
15646   ExprResult RValueExpr = DefaultLvalueConversion(E);
15647   if (RValueExpr.isInvalid())
15648     return ExprError();
15649 
15650   E = RValueExpr.get();
15651 
15652   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15653   // in the non-ICE case.
15654   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15655     if (Result)
15656       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15657     if (!isa<ConstantExpr>(E))
15658       E = ConstantExpr::Create(Context, E);
15659     return E;
15660   }
15661 
15662   Expr::EvalResult EvalResult;
15663   SmallVector<PartialDiagnosticAt, 8> Notes;
15664   EvalResult.Diag = &Notes;
15665 
15666   // Try to evaluate the expression, and produce diagnostics explaining why it's
15667   // not a constant expression as a side-effect.
15668   bool Folded =
15669       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15670       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15671 
15672   if (!isa<ConstantExpr>(E))
15673     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15674 
15675   // In C++11, we can rely on diagnostics being produced for any expression
15676   // which is not a constant expression. If no diagnostics were produced, then
15677   // this is a constant expression.
15678   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15679     if (Result)
15680       *Result = EvalResult.Val.getInt();
15681     return E;
15682   }
15683 
15684   // If our only note is the usual "invalid subexpression" note, just point
15685   // the caret at its location rather than producing an essentially
15686   // redundant note.
15687   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15688         diag::note_invalid_subexpr_in_const_expr) {
15689     DiagLoc = Notes[0].first;
15690     Notes.clear();
15691   }
15692 
15693   if (!Folded || !AllowFold) {
15694     if (!Diagnoser.Suppress) {
15695       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15696       for (const PartialDiagnosticAt &Note : Notes)
15697         Diag(Note.first, Note.second);
15698     }
15699 
15700     return ExprError();
15701   }
15702 
15703   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15704   for (const PartialDiagnosticAt &Note : Notes)
15705     Diag(Note.first, Note.second);
15706 
15707   if (Result)
15708     *Result = EvalResult.Val.getInt();
15709   return E;
15710 }
15711 
15712 namespace {
15713   // Handle the case where we conclude a expression which we speculatively
15714   // considered to be unevaluated is actually evaluated.
15715   class TransformToPE : public TreeTransform<TransformToPE> {
15716     typedef TreeTransform<TransformToPE> BaseTransform;
15717 
15718   public:
15719     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15720 
15721     // Make sure we redo semantic analysis
15722     bool AlwaysRebuild() { return true; }
15723     bool ReplacingOriginal() { return true; }
15724 
15725     // We need to special-case DeclRefExprs referring to FieldDecls which
15726     // are not part of a member pointer formation; normal TreeTransforming
15727     // doesn't catch this case because of the way we represent them in the AST.
15728     // FIXME: This is a bit ugly; is it really the best way to handle this
15729     // case?
15730     //
15731     // Error on DeclRefExprs referring to FieldDecls.
15732     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15733       if (isa<FieldDecl>(E->getDecl()) &&
15734           !SemaRef.isUnevaluatedContext())
15735         return SemaRef.Diag(E->getLocation(),
15736                             diag::err_invalid_non_static_member_use)
15737             << E->getDecl() << E->getSourceRange();
15738 
15739       return BaseTransform::TransformDeclRefExpr(E);
15740     }
15741 
15742     // Exception: filter out member pointer formation
15743     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15744       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15745         return E;
15746 
15747       return BaseTransform::TransformUnaryOperator(E);
15748     }
15749 
15750     // The body of a lambda-expression is in a separate expression evaluation
15751     // context so never needs to be transformed.
15752     // FIXME: Ideally we wouldn't transform the closure type either, and would
15753     // just recreate the capture expressions and lambda expression.
15754     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15755       return SkipLambdaBody(E, Body);
15756     }
15757   };
15758 }
15759 
15760 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15761   assert(isUnevaluatedContext() &&
15762          "Should only transform unevaluated expressions");
15763   ExprEvalContexts.back().Context =
15764       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15765   if (isUnevaluatedContext())
15766     return E;
15767   return TransformToPE(*this).TransformExpr(E);
15768 }
15769 
15770 void
15771 Sema::PushExpressionEvaluationContext(
15772     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15773     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15774   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15775                                 LambdaContextDecl, ExprContext);
15776   Cleanup.reset();
15777   if (!MaybeODRUseExprs.empty())
15778     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15779 }
15780 
15781 void
15782 Sema::PushExpressionEvaluationContext(
15783     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15784     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15785   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15786   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15787 }
15788 
15789 namespace {
15790 
15791 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15792   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15793   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15794     if (E->getOpcode() == UO_Deref)
15795       return CheckPossibleDeref(S, E->getSubExpr());
15796   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15797     return CheckPossibleDeref(S, E->getBase());
15798   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15799     return CheckPossibleDeref(S, E->getBase());
15800   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15801     QualType Inner;
15802     QualType Ty = E->getType();
15803     if (const auto *Ptr = Ty->getAs<PointerType>())
15804       Inner = Ptr->getPointeeType();
15805     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15806       Inner = Arr->getElementType();
15807     else
15808       return nullptr;
15809 
15810     if (Inner->hasAttr(attr::NoDeref))
15811       return E;
15812   }
15813   return nullptr;
15814 }
15815 
15816 } // namespace
15817 
15818 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15819   for (const Expr *E : Rec.PossibleDerefs) {
15820     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15821     if (DeclRef) {
15822       const ValueDecl *Decl = DeclRef->getDecl();
15823       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15824           << Decl->getName() << E->getSourceRange();
15825       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15826     } else {
15827       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15828           << E->getSourceRange();
15829     }
15830   }
15831   Rec.PossibleDerefs.clear();
15832 }
15833 
15834 /// Check whether E, which is either a discarded-value expression or an
15835 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15836 /// and if so, remove it from the list of volatile-qualified assignments that
15837 /// we are going to warn are deprecated.
15838 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15839   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15840     return;
15841 
15842   // Note: ignoring parens here is not justified by the standard rules, but
15843   // ignoring parentheses seems like a more reasonable approach, and this only
15844   // drives a deprecation warning so doesn't affect conformance.
15845   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15846     if (BO->getOpcode() == BO_Assign) {
15847       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15848       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15849                  LHSs.end());
15850     }
15851   }
15852 }
15853 
15854 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15855   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15856       RebuildingImmediateInvocation)
15857     return E;
15858 
15859   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15860   /// It's OK if this fails; we'll also remove this in
15861   /// HandleImmediateInvocations, but catching it here allows us to avoid
15862   /// walking the AST looking for it in simple cases.
15863   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15864     if (auto *DeclRef =
15865             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15866       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15867 
15868   E = MaybeCreateExprWithCleanups(E);
15869 
15870   ConstantExpr *Res = ConstantExpr::Create(
15871       getASTContext(), E.get(),
15872       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15873                                    getASTContext()),
15874       /*IsImmediateInvocation*/ true);
15875   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15876   return Res;
15877 }
15878 
15879 static void EvaluateAndDiagnoseImmediateInvocation(
15880     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15881   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15882   Expr::EvalResult Eval;
15883   Eval.Diag = &Notes;
15884   ConstantExpr *CE = Candidate.getPointer();
15885   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15886                                            SemaRef.getASTContext(), true);
15887   if (!Result || !Notes.empty()) {
15888     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15889     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
15890       InnerExpr = FunctionalCast->getSubExpr();
15891     FunctionDecl *FD = nullptr;
15892     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15893       FD = cast<FunctionDecl>(Call->getCalleeDecl());
15894     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15895       FD = Call->getConstructor();
15896     else
15897       llvm_unreachable("unhandled decl kind");
15898     assert(FD->isConsteval());
15899     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15900     for (auto &Note : Notes)
15901       SemaRef.Diag(Note.first, Note.second);
15902     return;
15903   }
15904   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15905 }
15906 
15907 static void RemoveNestedImmediateInvocation(
15908     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15909     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15910   struct ComplexRemove : TreeTransform<ComplexRemove> {
15911     using Base = TreeTransform<ComplexRemove>;
15912     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15913     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15914     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15915         CurrentII;
15916     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15917                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15918                   SmallVector<Sema::ImmediateInvocationCandidate,
15919                               4>::reverse_iterator Current)
15920         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15921     void RemoveImmediateInvocation(ConstantExpr* E) {
15922       auto It = std::find_if(CurrentII, IISet.rend(),
15923                              [E](Sema::ImmediateInvocationCandidate Elem) {
15924                                return Elem.getPointer() == E;
15925                              });
15926       assert(It != IISet.rend() &&
15927              "ConstantExpr marked IsImmediateInvocation should "
15928              "be present");
15929       It->setInt(1); // Mark as deleted
15930     }
15931     ExprResult TransformConstantExpr(ConstantExpr *E) {
15932       if (!E->isImmediateInvocation())
15933         return Base::TransformConstantExpr(E);
15934       RemoveImmediateInvocation(E);
15935       return Base::TransformExpr(E->getSubExpr());
15936     }
15937     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15938     /// we need to remove its DeclRefExpr from the DRSet.
15939     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15940       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15941       return Base::TransformCXXOperatorCallExpr(E);
15942     }
15943     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15944     /// here.
15945     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15946       if (!Init)
15947         return Init;
15948       /// ConstantExpr are the first layer of implicit node to be removed so if
15949       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15950       if (auto *CE = dyn_cast<ConstantExpr>(Init))
15951         if (CE->isImmediateInvocation())
15952           RemoveImmediateInvocation(CE);
15953       return Base::TransformInitializer(Init, NotCopyInit);
15954     }
15955     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15956       DRSet.erase(E);
15957       return E;
15958     }
15959     bool AlwaysRebuild() { return false; }
15960     bool ReplacingOriginal() { return true; }
15961     bool AllowSkippingCXXConstructExpr() {
15962       bool Res = AllowSkippingFirstCXXConstructExpr;
15963       AllowSkippingFirstCXXConstructExpr = true;
15964       return Res;
15965     }
15966     bool AllowSkippingFirstCXXConstructExpr = true;
15967   } Transformer(SemaRef, Rec.ReferenceToConsteval,
15968                 Rec.ImmediateInvocationCandidates, It);
15969 
15970   /// CXXConstructExpr with a single argument are getting skipped by
15971   /// TreeTransform in some situtation because they could be implicit. This
15972   /// can only occur for the top-level CXXConstructExpr because it is used
15973   /// nowhere in the expression being transformed therefore will not be rebuilt.
15974   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
15975   /// skipping the first CXXConstructExpr.
15976   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
15977     Transformer.AllowSkippingFirstCXXConstructExpr = false;
15978 
15979   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
15980   assert(Res.isUsable());
15981   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
15982   It->getPointer()->setSubExpr(Res.get());
15983 }
15984 
15985 static void
15986 HandleImmediateInvocations(Sema &SemaRef,
15987                            Sema::ExpressionEvaluationContextRecord &Rec) {
15988   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
15989        Rec.ReferenceToConsteval.size() == 0) ||
15990       SemaRef.RebuildingImmediateInvocation)
15991     return;
15992 
15993   /// When we have more then 1 ImmediateInvocationCandidates we need to check
15994   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
15995   /// need to remove ReferenceToConsteval in the immediate invocation.
15996   if (Rec.ImmediateInvocationCandidates.size() > 1) {
15997 
15998     /// Prevent sema calls during the tree transform from adding pointers that
15999     /// are already in the sets.
16000     llvm::SaveAndRestore<bool> DisableIITracking(
16001         SemaRef.RebuildingImmediateInvocation, true);
16002 
16003     /// Prevent diagnostic during tree transfrom as they are duplicates
16004     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16005 
16006     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16007          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16008       if (!It->getInt())
16009         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16010   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16011              Rec.ReferenceToConsteval.size()) {
16012     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16013       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16014       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16015       bool VisitDeclRefExpr(DeclRefExpr *E) {
16016         DRSet.erase(E);
16017         return DRSet.size();
16018       }
16019     } Visitor(Rec.ReferenceToConsteval);
16020     Visitor.TraverseStmt(
16021         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16022   }
16023   for (auto CE : Rec.ImmediateInvocationCandidates)
16024     if (!CE.getInt())
16025       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16026   for (auto DR : Rec.ReferenceToConsteval) {
16027     auto *FD = cast<FunctionDecl>(DR->getDecl());
16028     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16029         << FD;
16030     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16031   }
16032 }
16033 
16034 void Sema::PopExpressionEvaluationContext() {
16035   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16036   unsigned NumTypos = Rec.NumTypos;
16037 
16038   if (!Rec.Lambdas.empty()) {
16039     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16040     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16041         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16042       unsigned D;
16043       if (Rec.isUnevaluated()) {
16044         // C++11 [expr.prim.lambda]p2:
16045         //   A lambda-expression shall not appear in an unevaluated operand
16046         //   (Clause 5).
16047         D = diag::err_lambda_unevaluated_operand;
16048       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16049         // C++1y [expr.const]p2:
16050         //   A conditional-expression e is a core constant expression unless the
16051         //   evaluation of e, following the rules of the abstract machine, would
16052         //   evaluate [...] a lambda-expression.
16053         D = diag::err_lambda_in_constant_expression;
16054       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16055         // C++17 [expr.prim.lamda]p2:
16056         // A lambda-expression shall not appear [...] in a template-argument.
16057         D = diag::err_lambda_in_invalid_context;
16058       } else
16059         llvm_unreachable("Couldn't infer lambda error message.");
16060 
16061       for (const auto *L : Rec.Lambdas)
16062         Diag(L->getBeginLoc(), D);
16063     }
16064   }
16065 
16066   WarnOnPendingNoDerefs(Rec);
16067   HandleImmediateInvocations(*this, Rec);
16068 
16069   // Warn on any volatile-qualified simple-assignments that are not discarded-
16070   // value expressions nor unevaluated operands (those cases get removed from
16071   // this list by CheckUnusedVolatileAssignment).
16072   for (auto *BO : Rec.VolatileAssignmentLHSs)
16073     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16074         << BO->getType();
16075 
16076   // When are coming out of an unevaluated context, clear out any
16077   // temporaries that we may have created as part of the evaluation of
16078   // the expression in that context: they aren't relevant because they
16079   // will never be constructed.
16080   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16081     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16082                              ExprCleanupObjects.end());
16083     Cleanup = Rec.ParentCleanup;
16084     CleanupVarDeclMarking();
16085     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16086   // Otherwise, merge the contexts together.
16087   } else {
16088     Cleanup.mergeFrom(Rec.ParentCleanup);
16089     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16090                             Rec.SavedMaybeODRUseExprs.end());
16091   }
16092 
16093   // Pop the current expression evaluation context off the stack.
16094   ExprEvalContexts.pop_back();
16095 
16096   // The global expression evaluation context record is never popped.
16097   ExprEvalContexts.back().NumTypos += NumTypos;
16098 }
16099 
16100 void Sema::DiscardCleanupsInEvaluationContext() {
16101   ExprCleanupObjects.erase(
16102          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16103          ExprCleanupObjects.end());
16104   Cleanup.reset();
16105   MaybeODRUseExprs.clear();
16106 }
16107 
16108 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16109   ExprResult Result = CheckPlaceholderExpr(E);
16110   if (Result.isInvalid())
16111     return ExprError();
16112   E = Result.get();
16113   if (!E->getType()->isVariablyModifiedType())
16114     return E;
16115   return TransformToPotentiallyEvaluated(E);
16116 }
16117 
16118 /// Are we in a context that is potentially constant evaluated per C++20
16119 /// [expr.const]p12?
16120 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16121   /// C++2a [expr.const]p12:
16122   //   An expression or conversion is potentially constant evaluated if it is
16123   switch (SemaRef.ExprEvalContexts.back().Context) {
16124     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16125       // -- a manifestly constant-evaluated expression,
16126     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16127     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16128     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16129       // -- a potentially-evaluated expression,
16130     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16131       // -- an immediate subexpression of a braced-init-list,
16132 
16133       // -- [FIXME] an expression of the form & cast-expression that occurs
16134       //    within a templated entity
16135       // -- a subexpression of one of the above that is not a subexpression of
16136       // a nested unevaluated operand.
16137       return true;
16138 
16139     case Sema::ExpressionEvaluationContext::Unevaluated:
16140     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16141       // Expressions in this context are never evaluated.
16142       return false;
16143   }
16144   llvm_unreachable("Invalid context");
16145 }
16146 
16147 /// Return true if this function has a calling convention that requires mangling
16148 /// in the size of the parameter pack.
16149 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16150   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16151   // we don't need parameter type sizes.
16152   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16153   if (!TT.isOSWindows() || !TT.isX86())
16154     return false;
16155 
16156   // If this is C++ and this isn't an extern "C" function, parameters do not
16157   // need to be complete. In this case, C++ mangling will apply, which doesn't
16158   // use the size of the parameters.
16159   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16160     return false;
16161 
16162   // Stdcall, fastcall, and vectorcall need this special treatment.
16163   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16164   switch (CC) {
16165   case CC_X86StdCall:
16166   case CC_X86FastCall:
16167   case CC_X86VectorCall:
16168     return true;
16169   default:
16170     break;
16171   }
16172   return false;
16173 }
16174 
16175 /// Require that all of the parameter types of function be complete. Normally,
16176 /// parameter types are only required to be complete when a function is called
16177 /// or defined, but to mangle functions with certain calling conventions, the
16178 /// mangler needs to know the size of the parameter list. In this situation,
16179 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16180 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16181 /// result in a linker error. Clang doesn't implement this behavior, and instead
16182 /// attempts to error at compile time.
16183 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16184                                                   SourceLocation Loc) {
16185   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16186     FunctionDecl *FD;
16187     ParmVarDecl *Param;
16188 
16189   public:
16190     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16191         : FD(FD), Param(Param) {}
16192 
16193     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16194       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16195       StringRef CCName;
16196       switch (CC) {
16197       case CC_X86StdCall:
16198         CCName = "stdcall";
16199         break;
16200       case CC_X86FastCall:
16201         CCName = "fastcall";
16202         break;
16203       case CC_X86VectorCall:
16204         CCName = "vectorcall";
16205         break;
16206       default:
16207         llvm_unreachable("CC does not need mangling");
16208       }
16209 
16210       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16211           << Param->getDeclName() << FD->getDeclName() << CCName;
16212     }
16213   };
16214 
16215   for (ParmVarDecl *Param : FD->parameters()) {
16216     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16217     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16218   }
16219 }
16220 
16221 namespace {
16222 enum class OdrUseContext {
16223   /// Declarations in this context are not odr-used.
16224   None,
16225   /// Declarations in this context are formally odr-used, but this is a
16226   /// dependent context.
16227   Dependent,
16228   /// Declarations in this context are odr-used but not actually used (yet).
16229   FormallyOdrUsed,
16230   /// Declarations in this context are used.
16231   Used
16232 };
16233 }
16234 
16235 /// Are we within a context in which references to resolved functions or to
16236 /// variables result in odr-use?
16237 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16238   OdrUseContext Result;
16239 
16240   switch (SemaRef.ExprEvalContexts.back().Context) {
16241     case Sema::ExpressionEvaluationContext::Unevaluated:
16242     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16243     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16244       return OdrUseContext::None;
16245 
16246     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16247     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16248       Result = OdrUseContext::Used;
16249       break;
16250 
16251     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16252       Result = OdrUseContext::FormallyOdrUsed;
16253       break;
16254 
16255     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16256       // A default argument formally results in odr-use, but doesn't actually
16257       // result in a use in any real sense until it itself is used.
16258       Result = OdrUseContext::FormallyOdrUsed;
16259       break;
16260   }
16261 
16262   if (SemaRef.CurContext->isDependentContext())
16263     return OdrUseContext::Dependent;
16264 
16265   return Result;
16266 }
16267 
16268 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16269   return Func->isConstexpr() &&
16270          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16271 }
16272 
16273 /// Mark a function referenced, and check whether it is odr-used
16274 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16275 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16276                                   bool MightBeOdrUse) {
16277   assert(Func && "No function?");
16278 
16279   Func->setReferenced();
16280 
16281   // Recursive functions aren't really used until they're used from some other
16282   // context.
16283   bool IsRecursiveCall = CurContext == Func;
16284 
16285   // C++11 [basic.def.odr]p3:
16286   //   A function whose name appears as a potentially-evaluated expression is
16287   //   odr-used if it is the unique lookup result or the selected member of a
16288   //   set of overloaded functions [...].
16289   //
16290   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16291   // can just check that here.
16292   OdrUseContext OdrUse =
16293       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16294   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16295     OdrUse = OdrUseContext::FormallyOdrUsed;
16296 
16297   // Trivial default constructors and destructors are never actually used.
16298   // FIXME: What about other special members?
16299   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16300       OdrUse == OdrUseContext::Used) {
16301     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16302       if (Constructor->isDefaultConstructor())
16303         OdrUse = OdrUseContext::FormallyOdrUsed;
16304     if (isa<CXXDestructorDecl>(Func))
16305       OdrUse = OdrUseContext::FormallyOdrUsed;
16306   }
16307 
16308   // C++20 [expr.const]p12:
16309   //   A function [...] is needed for constant evaluation if it is [...] a
16310   //   constexpr function that is named by an expression that is potentially
16311   //   constant evaluated
16312   bool NeededForConstantEvaluation =
16313       isPotentiallyConstantEvaluatedContext(*this) &&
16314       isImplicitlyDefinableConstexprFunction(Func);
16315 
16316   // Determine whether we require a function definition to exist, per
16317   // C++11 [temp.inst]p3:
16318   //   Unless a function template specialization has been explicitly
16319   //   instantiated or explicitly specialized, the function template
16320   //   specialization is implicitly instantiated when the specialization is
16321   //   referenced in a context that requires a function definition to exist.
16322   // C++20 [temp.inst]p7:
16323   //   The existence of a definition of a [...] function is considered to
16324   //   affect the semantics of the program if the [...] function is needed for
16325   //   constant evaluation by an expression
16326   // C++20 [basic.def.odr]p10:
16327   //   Every program shall contain exactly one definition of every non-inline
16328   //   function or variable that is odr-used in that program outside of a
16329   //   discarded statement
16330   // C++20 [special]p1:
16331   //   The implementation will implicitly define [defaulted special members]
16332   //   if they are odr-used or needed for constant evaluation.
16333   //
16334   // Note that we skip the implicit instantiation of templates that are only
16335   // used in unused default arguments or by recursive calls to themselves.
16336   // This is formally non-conforming, but seems reasonable in practice.
16337   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16338                                              NeededForConstantEvaluation);
16339 
16340   // C++14 [temp.expl.spec]p6:
16341   //   If a template [...] is explicitly specialized then that specialization
16342   //   shall be declared before the first use of that specialization that would
16343   //   cause an implicit instantiation to take place, in every translation unit
16344   //   in which such a use occurs
16345   if (NeedDefinition &&
16346       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16347        Func->getMemberSpecializationInfo()))
16348     checkSpecializationVisibility(Loc, Func);
16349 
16350   if (getLangOpts().CUDA)
16351     CheckCUDACall(Loc, Func);
16352 
16353   // If we need a definition, try to create one.
16354   if (NeedDefinition && !Func->getBody()) {
16355     runWithSufficientStackSpace(Loc, [&] {
16356       if (CXXConstructorDecl *Constructor =
16357               dyn_cast<CXXConstructorDecl>(Func)) {
16358         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16359         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16360           if (Constructor->isDefaultConstructor()) {
16361             if (Constructor->isTrivial() &&
16362                 !Constructor->hasAttr<DLLExportAttr>())
16363               return;
16364             DefineImplicitDefaultConstructor(Loc, Constructor);
16365           } else if (Constructor->isCopyConstructor()) {
16366             DefineImplicitCopyConstructor(Loc, Constructor);
16367           } else if (Constructor->isMoveConstructor()) {
16368             DefineImplicitMoveConstructor(Loc, Constructor);
16369           }
16370         } else if (Constructor->getInheritedConstructor()) {
16371           DefineInheritingConstructor(Loc, Constructor);
16372         }
16373       } else if (CXXDestructorDecl *Destructor =
16374                      dyn_cast<CXXDestructorDecl>(Func)) {
16375         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16376         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16377           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16378             return;
16379           DefineImplicitDestructor(Loc, Destructor);
16380         }
16381         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16382           MarkVTableUsed(Loc, Destructor->getParent());
16383       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16384         if (MethodDecl->isOverloadedOperator() &&
16385             MethodDecl->getOverloadedOperator() == OO_Equal) {
16386           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16387           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16388             if (MethodDecl->isCopyAssignmentOperator())
16389               DefineImplicitCopyAssignment(Loc, MethodDecl);
16390             else if (MethodDecl->isMoveAssignmentOperator())
16391               DefineImplicitMoveAssignment(Loc, MethodDecl);
16392           }
16393         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16394                    MethodDecl->getParent()->isLambda()) {
16395           CXXConversionDecl *Conversion =
16396               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16397           if (Conversion->isLambdaToBlockPointerConversion())
16398             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16399           else
16400             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16401         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16402           MarkVTableUsed(Loc, MethodDecl->getParent());
16403       }
16404 
16405       if (Func->isDefaulted() && !Func->isDeleted()) {
16406         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16407         if (DCK != DefaultedComparisonKind::None)
16408           DefineDefaultedComparison(Loc, Func, DCK);
16409       }
16410 
16411       // Implicit instantiation of function templates and member functions of
16412       // class templates.
16413       if (Func->isImplicitlyInstantiable()) {
16414         TemplateSpecializationKind TSK =
16415             Func->getTemplateSpecializationKindForInstantiation();
16416         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16417         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16418         if (FirstInstantiation) {
16419           PointOfInstantiation = Loc;
16420           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16421         } else if (TSK != TSK_ImplicitInstantiation) {
16422           // Use the point of use as the point of instantiation, instead of the
16423           // point of explicit instantiation (which we track as the actual point
16424           // of instantiation). This gives better backtraces in diagnostics.
16425           PointOfInstantiation = Loc;
16426         }
16427 
16428         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16429             Func->isConstexpr()) {
16430           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16431               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16432               CodeSynthesisContexts.size())
16433             PendingLocalImplicitInstantiations.push_back(
16434                 std::make_pair(Func, PointOfInstantiation));
16435           else if (Func->isConstexpr())
16436             // Do not defer instantiations of constexpr functions, to avoid the
16437             // expression evaluator needing to call back into Sema if it sees a
16438             // call to such a function.
16439             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16440           else {
16441             Func->setInstantiationIsPending(true);
16442             PendingInstantiations.push_back(
16443                 std::make_pair(Func, PointOfInstantiation));
16444             // Notify the consumer that a function was implicitly instantiated.
16445             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16446           }
16447         }
16448       } else {
16449         // Walk redefinitions, as some of them may be instantiable.
16450         for (auto i : Func->redecls()) {
16451           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16452             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16453         }
16454       }
16455     });
16456   }
16457 
16458   // C++14 [except.spec]p17:
16459   //   An exception-specification is considered to be needed when:
16460   //   - the function is odr-used or, if it appears in an unevaluated operand,
16461   //     would be odr-used if the expression were potentially-evaluated;
16462   //
16463   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16464   // function is a pure virtual function we're calling, and in that case the
16465   // function was selected by overload resolution and we need to resolve its
16466   // exception specification for a different reason.
16467   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16468   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16469     ResolveExceptionSpec(Loc, FPT);
16470 
16471   // If this is the first "real" use, act on that.
16472   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16473     // Keep track of used but undefined functions.
16474     if (!Func->isDefined()) {
16475       if (mightHaveNonExternalLinkage(Func))
16476         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16477       else if (Func->getMostRecentDecl()->isInlined() &&
16478                !LangOpts.GNUInline &&
16479                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16480         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16481       else if (isExternalWithNoLinkageType(Func))
16482         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16483     }
16484 
16485     // Some x86 Windows calling conventions mangle the size of the parameter
16486     // pack into the name. Computing the size of the parameters requires the
16487     // parameter types to be complete. Check that now.
16488     if (funcHasParameterSizeMangling(*this, Func))
16489       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16490 
16491     // In the MS C++ ABI, the compiler emits destructor variants where they are
16492     // used. If the destructor is used here but defined elsewhere, mark the
16493     // virtual base destructors referenced. If those virtual base destructors
16494     // are inline, this will ensure they are defined when emitting the complete
16495     // destructor variant. This checking may be redundant if the destructor is
16496     // provided later in this TU.
16497     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16498       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16499         CXXRecordDecl *Parent = Dtor->getParent();
16500         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16501           CheckCompleteDestructorVariant(Loc, Dtor);
16502       }
16503     }
16504 
16505     Func->markUsed(Context);
16506   }
16507 }
16508 
16509 /// Directly mark a variable odr-used. Given a choice, prefer to use
16510 /// MarkVariableReferenced since it does additional checks and then
16511 /// calls MarkVarDeclODRUsed.
16512 /// If the variable must be captured:
16513 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16514 ///  - else capture it in the DeclContext that maps to the
16515 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16516 static void
16517 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16518                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16519   // Keep track of used but undefined variables.
16520   // FIXME: We shouldn't suppress this warning for static data members.
16521   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16522       (!Var->isExternallyVisible() || Var->isInline() ||
16523        SemaRef.isExternalWithNoLinkageType(Var)) &&
16524       !(Var->isStaticDataMember() && Var->hasInit())) {
16525     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16526     if (old.isInvalid())
16527       old = Loc;
16528   }
16529   QualType CaptureType, DeclRefType;
16530   if (SemaRef.LangOpts.OpenMP)
16531     SemaRef.tryCaptureOpenMPLambdas(Var);
16532   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16533     /*EllipsisLoc*/ SourceLocation(),
16534     /*BuildAndDiagnose*/ true,
16535     CaptureType, DeclRefType,
16536     FunctionScopeIndexToStopAt);
16537 
16538   Var->markUsed(SemaRef.Context);
16539 }
16540 
16541 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16542                                              SourceLocation Loc,
16543                                              unsigned CapturingScopeIndex) {
16544   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16545 }
16546 
16547 static void
16548 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16549                                    ValueDecl *var, DeclContext *DC) {
16550   DeclContext *VarDC = var->getDeclContext();
16551 
16552   //  If the parameter still belongs to the translation unit, then
16553   //  we're actually just using one parameter in the declaration of
16554   //  the next.
16555   if (isa<ParmVarDecl>(var) &&
16556       isa<TranslationUnitDecl>(VarDC))
16557     return;
16558 
16559   // For C code, don't diagnose about capture if we're not actually in code
16560   // right now; it's impossible to write a non-constant expression outside of
16561   // function context, so we'll get other (more useful) diagnostics later.
16562   //
16563   // For C++, things get a bit more nasty... it would be nice to suppress this
16564   // diagnostic for certain cases like using a local variable in an array bound
16565   // for a member of a local class, but the correct predicate is not obvious.
16566   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16567     return;
16568 
16569   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16570   unsigned ContextKind = 3; // unknown
16571   if (isa<CXXMethodDecl>(VarDC) &&
16572       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16573     ContextKind = 2;
16574   } else if (isa<FunctionDecl>(VarDC)) {
16575     ContextKind = 0;
16576   } else if (isa<BlockDecl>(VarDC)) {
16577     ContextKind = 1;
16578   }
16579 
16580   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16581     << var << ValueKind << ContextKind << VarDC;
16582   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16583       << var;
16584 
16585   // FIXME: Add additional diagnostic info about class etc. which prevents
16586   // capture.
16587 }
16588 
16589 
16590 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16591                                       bool &SubCapturesAreNested,
16592                                       QualType &CaptureType,
16593                                       QualType &DeclRefType) {
16594    // Check whether we've already captured it.
16595   if (CSI->CaptureMap.count(Var)) {
16596     // If we found a capture, any subcaptures are nested.
16597     SubCapturesAreNested = true;
16598 
16599     // Retrieve the capture type for this variable.
16600     CaptureType = CSI->getCapture(Var).getCaptureType();
16601 
16602     // Compute the type of an expression that refers to this variable.
16603     DeclRefType = CaptureType.getNonReferenceType();
16604 
16605     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16606     // are mutable in the sense that user can change their value - they are
16607     // private instances of the captured declarations.
16608     const Capture &Cap = CSI->getCapture(Var);
16609     if (Cap.isCopyCapture() &&
16610         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16611         !(isa<CapturedRegionScopeInfo>(CSI) &&
16612           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16613       DeclRefType.addConst();
16614     return true;
16615   }
16616   return false;
16617 }
16618 
16619 // Only block literals, captured statements, and lambda expressions can
16620 // capture; other scopes don't work.
16621 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16622                                  SourceLocation Loc,
16623                                  const bool Diagnose, Sema &S) {
16624   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16625     return getLambdaAwareParentOfDeclContext(DC);
16626   else if (Var->hasLocalStorage()) {
16627     if (Diagnose)
16628        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16629   }
16630   return nullptr;
16631 }
16632 
16633 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16634 // certain types of variables (unnamed, variably modified types etc.)
16635 // so check for eligibility.
16636 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16637                                  SourceLocation Loc,
16638                                  const bool Diagnose, Sema &S) {
16639 
16640   bool IsBlock = isa<BlockScopeInfo>(CSI);
16641   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16642 
16643   // Lambdas are not allowed to capture unnamed variables
16644   // (e.g. anonymous unions).
16645   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16646   // assuming that's the intent.
16647   if (IsLambda && !Var->getDeclName()) {
16648     if (Diagnose) {
16649       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16650       S.Diag(Var->getLocation(), diag::note_declared_at);
16651     }
16652     return false;
16653   }
16654 
16655   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16656   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16657     if (Diagnose) {
16658       S.Diag(Loc, diag::err_ref_vm_type);
16659       S.Diag(Var->getLocation(), diag::note_previous_decl)
16660         << Var->getDeclName();
16661     }
16662     return false;
16663   }
16664   // Prohibit structs with flexible array members too.
16665   // We cannot capture what is in the tail end of the struct.
16666   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16667     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16668       if (Diagnose) {
16669         if (IsBlock)
16670           S.Diag(Loc, diag::err_ref_flexarray_type);
16671         else
16672           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16673             << Var->getDeclName();
16674         S.Diag(Var->getLocation(), diag::note_previous_decl)
16675           << Var->getDeclName();
16676       }
16677       return false;
16678     }
16679   }
16680   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16681   // Lambdas and captured statements are not allowed to capture __block
16682   // variables; they don't support the expected semantics.
16683   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16684     if (Diagnose) {
16685       S.Diag(Loc, diag::err_capture_block_variable)
16686         << Var->getDeclName() << !IsLambda;
16687       S.Diag(Var->getLocation(), diag::note_previous_decl)
16688         << Var->getDeclName();
16689     }
16690     return false;
16691   }
16692   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16693   if (S.getLangOpts().OpenCL && IsBlock &&
16694       Var->getType()->isBlockPointerType()) {
16695     if (Diagnose)
16696       S.Diag(Loc, diag::err_opencl_block_ref_block);
16697     return false;
16698   }
16699 
16700   return true;
16701 }
16702 
16703 // Returns true if the capture by block was successful.
16704 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16705                                  SourceLocation Loc,
16706                                  const bool BuildAndDiagnose,
16707                                  QualType &CaptureType,
16708                                  QualType &DeclRefType,
16709                                  const bool Nested,
16710                                  Sema &S, bool Invalid) {
16711   bool ByRef = false;
16712 
16713   // Blocks are not allowed to capture arrays, excepting OpenCL.
16714   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16715   // (decayed to pointers).
16716   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16717     if (BuildAndDiagnose) {
16718       S.Diag(Loc, diag::err_ref_array_type);
16719       S.Diag(Var->getLocation(), diag::note_previous_decl)
16720       << Var->getDeclName();
16721       Invalid = true;
16722     } else {
16723       return false;
16724     }
16725   }
16726 
16727   // Forbid the block-capture of autoreleasing variables.
16728   if (!Invalid &&
16729       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16730     if (BuildAndDiagnose) {
16731       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16732         << /*block*/ 0;
16733       S.Diag(Var->getLocation(), diag::note_previous_decl)
16734         << Var->getDeclName();
16735       Invalid = true;
16736     } else {
16737       return false;
16738     }
16739   }
16740 
16741   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16742   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16743     QualType PointeeTy = PT->getPointeeType();
16744 
16745     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16746         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16747         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16748       if (BuildAndDiagnose) {
16749         SourceLocation VarLoc = Var->getLocation();
16750         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16751         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16752       }
16753     }
16754   }
16755 
16756   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16757   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16758       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16759     // Block capture by reference does not change the capture or
16760     // declaration reference types.
16761     ByRef = true;
16762   } else {
16763     // Block capture by copy introduces 'const'.
16764     CaptureType = CaptureType.getNonReferenceType().withConst();
16765     DeclRefType = CaptureType;
16766   }
16767 
16768   // Actually capture the variable.
16769   if (BuildAndDiagnose)
16770     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16771                     CaptureType, Invalid);
16772 
16773   return !Invalid;
16774 }
16775 
16776 
16777 /// Capture the given variable in the captured region.
16778 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16779                                     VarDecl *Var,
16780                                     SourceLocation Loc,
16781                                     const bool BuildAndDiagnose,
16782                                     QualType &CaptureType,
16783                                     QualType &DeclRefType,
16784                                     const bool RefersToCapturedVariable,
16785                                     Sema &S, bool Invalid) {
16786   // By default, capture variables by reference.
16787   bool ByRef = true;
16788   // Using an LValue reference type is consistent with Lambdas (see below).
16789   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16790     if (S.isOpenMPCapturedDecl(Var)) {
16791       bool HasConst = DeclRefType.isConstQualified();
16792       DeclRefType = DeclRefType.getUnqualifiedType();
16793       // Don't lose diagnostics about assignments to const.
16794       if (HasConst)
16795         DeclRefType.addConst();
16796     }
16797     // Do not capture firstprivates in tasks.
16798     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
16799         OMPC_unknown)
16800       return true;
16801     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16802                                     RSI->OpenMPCaptureLevel);
16803   }
16804 
16805   if (ByRef)
16806     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16807   else
16808     CaptureType = DeclRefType;
16809 
16810   // Actually capture the variable.
16811   if (BuildAndDiagnose)
16812     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16813                     Loc, SourceLocation(), CaptureType, Invalid);
16814 
16815   return !Invalid;
16816 }
16817 
16818 /// Capture the given variable in the lambda.
16819 static bool captureInLambda(LambdaScopeInfo *LSI,
16820                             VarDecl *Var,
16821                             SourceLocation Loc,
16822                             const bool BuildAndDiagnose,
16823                             QualType &CaptureType,
16824                             QualType &DeclRefType,
16825                             const bool RefersToCapturedVariable,
16826                             const Sema::TryCaptureKind Kind,
16827                             SourceLocation EllipsisLoc,
16828                             const bool IsTopScope,
16829                             Sema &S, bool Invalid) {
16830   // Determine whether we are capturing by reference or by value.
16831   bool ByRef = false;
16832   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16833     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16834   } else {
16835     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16836   }
16837 
16838   // Compute the type of the field that will capture this variable.
16839   if (ByRef) {
16840     // C++11 [expr.prim.lambda]p15:
16841     //   An entity is captured by reference if it is implicitly or
16842     //   explicitly captured but not captured by copy. It is
16843     //   unspecified whether additional unnamed non-static data
16844     //   members are declared in the closure type for entities
16845     //   captured by reference.
16846     //
16847     // FIXME: It is not clear whether we want to build an lvalue reference
16848     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16849     // to do the former, while EDG does the latter. Core issue 1249 will
16850     // clarify, but for now we follow GCC because it's a more permissive and
16851     // easily defensible position.
16852     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16853   } else {
16854     // C++11 [expr.prim.lambda]p14:
16855     //   For each entity captured by copy, an unnamed non-static
16856     //   data member is declared in the closure type. The
16857     //   declaration order of these members is unspecified. The type
16858     //   of such a data member is the type of the corresponding
16859     //   captured entity if the entity is not a reference to an
16860     //   object, or the referenced type otherwise. [Note: If the
16861     //   captured entity is a reference to a function, the
16862     //   corresponding data member is also a reference to a
16863     //   function. - end note ]
16864     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16865       if (!RefType->getPointeeType()->isFunctionType())
16866         CaptureType = RefType->getPointeeType();
16867     }
16868 
16869     // Forbid the lambda copy-capture of autoreleasing variables.
16870     if (!Invalid &&
16871         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16872       if (BuildAndDiagnose) {
16873         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16874         S.Diag(Var->getLocation(), diag::note_previous_decl)
16875           << Var->getDeclName();
16876         Invalid = true;
16877       } else {
16878         return false;
16879       }
16880     }
16881 
16882     // Make sure that by-copy captures are of a complete and non-abstract type.
16883     if (!Invalid && BuildAndDiagnose) {
16884       if (!CaptureType->isDependentType() &&
16885           S.RequireCompleteSizedType(
16886               Loc, CaptureType,
16887               diag::err_capture_of_incomplete_or_sizeless_type,
16888               Var->getDeclName()))
16889         Invalid = true;
16890       else if (S.RequireNonAbstractType(Loc, CaptureType,
16891                                         diag::err_capture_of_abstract_type))
16892         Invalid = true;
16893     }
16894   }
16895 
16896   // Compute the type of a reference to this captured variable.
16897   if (ByRef)
16898     DeclRefType = CaptureType.getNonReferenceType();
16899   else {
16900     // C++ [expr.prim.lambda]p5:
16901     //   The closure type for a lambda-expression has a public inline
16902     //   function call operator [...]. This function call operator is
16903     //   declared const (9.3.1) if and only if the lambda-expression's
16904     //   parameter-declaration-clause is not followed by mutable.
16905     DeclRefType = CaptureType.getNonReferenceType();
16906     if (!LSI->Mutable && !CaptureType->isReferenceType())
16907       DeclRefType.addConst();
16908   }
16909 
16910   // Add the capture.
16911   if (BuildAndDiagnose)
16912     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16913                     Loc, EllipsisLoc, CaptureType, Invalid);
16914 
16915   return !Invalid;
16916 }
16917 
16918 bool Sema::tryCaptureVariable(
16919     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16920     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16921     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16922   // An init-capture is notionally from the context surrounding its
16923   // declaration, but its parent DC is the lambda class.
16924   DeclContext *VarDC = Var->getDeclContext();
16925   if (Var->isInitCapture())
16926     VarDC = VarDC->getParent();
16927 
16928   DeclContext *DC = CurContext;
16929   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16930       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16931   // We need to sync up the Declaration Context with the
16932   // FunctionScopeIndexToStopAt
16933   if (FunctionScopeIndexToStopAt) {
16934     unsigned FSIndex = FunctionScopes.size() - 1;
16935     while (FSIndex != MaxFunctionScopesIndex) {
16936       DC = getLambdaAwareParentOfDeclContext(DC);
16937       --FSIndex;
16938     }
16939   }
16940 
16941 
16942   // If the variable is declared in the current context, there is no need to
16943   // capture it.
16944   if (VarDC == DC) return true;
16945 
16946   // Capture global variables if it is required to use private copy of this
16947   // variable.
16948   bool IsGlobal = !Var->hasLocalStorage();
16949   if (IsGlobal &&
16950       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16951                                                 MaxFunctionScopesIndex)))
16952     return true;
16953   Var = Var->getCanonicalDecl();
16954 
16955   // Walk up the stack to determine whether we can capture the variable,
16956   // performing the "simple" checks that don't depend on type. We stop when
16957   // we've either hit the declared scope of the variable or find an existing
16958   // capture of that variable.  We start from the innermost capturing-entity
16959   // (the DC) and ensure that all intervening capturing-entities
16960   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16961   // declcontext can either capture the variable or have already captured
16962   // the variable.
16963   CaptureType = Var->getType();
16964   DeclRefType = CaptureType.getNonReferenceType();
16965   bool Nested = false;
16966   bool Explicit = (Kind != TryCapture_Implicit);
16967   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16968   do {
16969     // Only block literals, captured statements, and lambda expressions can
16970     // capture; other scopes don't work.
16971     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16972                                                               ExprLoc,
16973                                                               BuildAndDiagnose,
16974                                                               *this);
16975     // We need to check for the parent *first* because, if we *have*
16976     // private-captured a global variable, we need to recursively capture it in
16977     // intermediate blocks, lambdas, etc.
16978     if (!ParentDC) {
16979       if (IsGlobal) {
16980         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16981         break;
16982       }
16983       return true;
16984     }
16985 
16986     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16987     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16988 
16989 
16990     // Check whether we've already captured it.
16991     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16992                                              DeclRefType)) {
16993       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16994       break;
16995     }
16996     // If we are instantiating a generic lambda call operator body,
16997     // we do not want to capture new variables.  What was captured
16998     // during either a lambdas transformation or initial parsing
16999     // should be used.
17000     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17001       if (BuildAndDiagnose) {
17002         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17003         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17004           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17005           Diag(Var->getLocation(), diag::note_previous_decl)
17006              << Var->getDeclName();
17007           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17008         } else
17009           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17010       }
17011       return true;
17012     }
17013 
17014     // Try to capture variable-length arrays types.
17015     if (Var->getType()->isVariablyModifiedType()) {
17016       // We're going to walk down into the type and look for VLA
17017       // expressions.
17018       QualType QTy = Var->getType();
17019       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17020         QTy = PVD->getOriginalType();
17021       captureVariablyModifiedType(Context, QTy, CSI);
17022     }
17023 
17024     if (getLangOpts().OpenMP) {
17025       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17026         // OpenMP private variables should not be captured in outer scope, so
17027         // just break here. Similarly, global variables that are captured in a
17028         // target region should not be captured outside the scope of the region.
17029         if (RSI->CapRegionKind == CR_OpenMP) {
17030           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17031               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17032           // If the variable is private (i.e. not captured) and has variably
17033           // modified type, we still need to capture the type for correct
17034           // codegen in all regions, associated with the construct. Currently,
17035           // it is captured in the innermost captured region only.
17036           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17037               Var->getType()->isVariablyModifiedType()) {
17038             QualType QTy = Var->getType();
17039             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17040               QTy = PVD->getOriginalType();
17041             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17042                  I < E; ++I) {
17043               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17044                   FunctionScopes[FunctionScopesIndex - I]);
17045               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17046                      "Wrong number of captured regions associated with the "
17047                      "OpenMP construct.");
17048               captureVariablyModifiedType(Context, QTy, OuterRSI);
17049             }
17050           }
17051           bool IsTargetCap =
17052               IsOpenMPPrivateDecl != OMPC_private &&
17053               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17054                                          RSI->OpenMPCaptureLevel);
17055           // Do not capture global if it is not privatized in outer regions.
17056           bool IsGlobalCap =
17057               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17058                                                      RSI->OpenMPCaptureLevel);
17059 
17060           // When we detect target captures we are looking from inside the
17061           // target region, therefore we need to propagate the capture from the
17062           // enclosing region. Therefore, the capture is not initially nested.
17063           if (IsTargetCap)
17064             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17065 
17066           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17067               (IsGlobal && !IsGlobalCap)) {
17068             Nested = !IsTargetCap;
17069             DeclRefType = DeclRefType.getUnqualifiedType();
17070             CaptureType = Context.getLValueReferenceType(DeclRefType);
17071             break;
17072           }
17073         }
17074       }
17075     }
17076     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17077       // No capture-default, and this is not an explicit capture
17078       // so cannot capture this variable.
17079       if (BuildAndDiagnose) {
17080         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17081         Diag(Var->getLocation(), diag::note_previous_decl)
17082           << Var->getDeclName();
17083         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17084           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17085                diag::note_lambda_decl);
17086         // FIXME: If we error out because an outer lambda can not implicitly
17087         // capture a variable that an inner lambda explicitly captures, we
17088         // should have the inner lambda do the explicit capture - because
17089         // it makes for cleaner diagnostics later.  This would purely be done
17090         // so that the diagnostic does not misleadingly claim that a variable
17091         // can not be captured by a lambda implicitly even though it is captured
17092         // explicitly.  Suggestion:
17093         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17094         //    at the function head
17095         //  - cache the StartingDeclContext - this must be a lambda
17096         //  - captureInLambda in the innermost lambda the variable.
17097       }
17098       return true;
17099     }
17100 
17101     FunctionScopesIndex--;
17102     DC = ParentDC;
17103     Explicit = false;
17104   } while (!VarDC->Equals(DC));
17105 
17106   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17107   // computing the type of the capture at each step, checking type-specific
17108   // requirements, and adding captures if requested.
17109   // If the variable had already been captured previously, we start capturing
17110   // at the lambda nested within that one.
17111   bool Invalid = false;
17112   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17113        ++I) {
17114     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17115 
17116     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17117     // certain types of variables (unnamed, variably modified types etc.)
17118     // so check for eligibility.
17119     if (!Invalid)
17120       Invalid =
17121           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17122 
17123     // After encountering an error, if we're actually supposed to capture, keep
17124     // capturing in nested contexts to suppress any follow-on diagnostics.
17125     if (Invalid && !BuildAndDiagnose)
17126       return true;
17127 
17128     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17129       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17130                                DeclRefType, Nested, *this, Invalid);
17131       Nested = true;
17132     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17133       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17134                                          CaptureType, DeclRefType, Nested,
17135                                          *this, Invalid);
17136       Nested = true;
17137     } else {
17138       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17139       Invalid =
17140           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17141                            DeclRefType, Nested, Kind, EllipsisLoc,
17142                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17143       Nested = true;
17144     }
17145 
17146     if (Invalid && !BuildAndDiagnose)
17147       return true;
17148   }
17149   return Invalid;
17150 }
17151 
17152 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17153                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17154   QualType CaptureType;
17155   QualType DeclRefType;
17156   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17157                             /*BuildAndDiagnose=*/true, CaptureType,
17158                             DeclRefType, nullptr);
17159 }
17160 
17161 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17162   QualType CaptureType;
17163   QualType DeclRefType;
17164   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17165                              /*BuildAndDiagnose=*/false, CaptureType,
17166                              DeclRefType, nullptr);
17167 }
17168 
17169 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17170   QualType CaptureType;
17171   QualType DeclRefType;
17172 
17173   // Determine whether we can capture this variable.
17174   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17175                          /*BuildAndDiagnose=*/false, CaptureType,
17176                          DeclRefType, nullptr))
17177     return QualType();
17178 
17179   return DeclRefType;
17180 }
17181 
17182 namespace {
17183 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17184 // The produced TemplateArgumentListInfo* points to data stored within this
17185 // object, so should only be used in contexts where the pointer will not be
17186 // used after the CopiedTemplateArgs object is destroyed.
17187 class CopiedTemplateArgs {
17188   bool HasArgs;
17189   TemplateArgumentListInfo TemplateArgStorage;
17190 public:
17191   template<typename RefExpr>
17192   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17193     if (HasArgs)
17194       E->copyTemplateArgumentsInto(TemplateArgStorage);
17195   }
17196   operator TemplateArgumentListInfo*()
17197 #ifdef __has_cpp_attribute
17198 #if __has_cpp_attribute(clang::lifetimebound)
17199   [[clang::lifetimebound]]
17200 #endif
17201 #endif
17202   {
17203     return HasArgs ? &TemplateArgStorage : nullptr;
17204   }
17205 };
17206 }
17207 
17208 /// Walk the set of potential results of an expression and mark them all as
17209 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17210 ///
17211 /// \return A new expression if we found any potential results, ExprEmpty() if
17212 ///         not, and ExprError() if we diagnosed an error.
17213 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17214                                                       NonOdrUseReason NOUR) {
17215   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17216   // an object that satisfies the requirements for appearing in a
17217   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17218   // is immediately applied."  This function handles the lvalue-to-rvalue
17219   // conversion part.
17220   //
17221   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17222   // transform it into the relevant kind of non-odr-use node and rebuild the
17223   // tree of nodes leading to it.
17224   //
17225   // This is a mini-TreeTransform that only transforms a restricted subset of
17226   // nodes (and only certain operands of them).
17227 
17228   // Rebuild a subexpression.
17229   auto Rebuild = [&](Expr *Sub) {
17230     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17231   };
17232 
17233   // Check whether a potential result satisfies the requirements of NOUR.
17234   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17235     // Any entity other than a VarDecl is always odr-used whenever it's named
17236     // in a potentially-evaluated expression.
17237     auto *VD = dyn_cast<VarDecl>(D);
17238     if (!VD)
17239       return true;
17240 
17241     // C++2a [basic.def.odr]p4:
17242     //   A variable x whose name appears as a potentially-evalauted expression
17243     //   e is odr-used by e unless
17244     //   -- x is a reference that is usable in constant expressions, or
17245     //   -- x is a variable of non-reference type that is usable in constant
17246     //      expressions and has no mutable subobjects, and e is an element of
17247     //      the set of potential results of an expression of
17248     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17249     //      conversion is applied, or
17250     //   -- x is a variable of non-reference type, and e is an element of the
17251     //      set of potential results of a discarded-value expression to which
17252     //      the lvalue-to-rvalue conversion is not applied
17253     //
17254     // We check the first bullet and the "potentially-evaluated" condition in
17255     // BuildDeclRefExpr. We check the type requirements in the second bullet
17256     // in CheckLValueToRValueConversionOperand below.
17257     switch (NOUR) {
17258     case NOUR_None:
17259     case NOUR_Unevaluated:
17260       llvm_unreachable("unexpected non-odr-use-reason");
17261 
17262     case NOUR_Constant:
17263       // Constant references were handled when they were built.
17264       if (VD->getType()->isReferenceType())
17265         return true;
17266       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17267         if (RD->hasMutableFields())
17268           return true;
17269       if (!VD->isUsableInConstantExpressions(S.Context))
17270         return true;
17271       break;
17272 
17273     case NOUR_Discarded:
17274       if (VD->getType()->isReferenceType())
17275         return true;
17276       break;
17277     }
17278     return false;
17279   };
17280 
17281   // Mark that this expression does not constitute an odr-use.
17282   auto MarkNotOdrUsed = [&] {
17283     S.MaybeODRUseExprs.erase(E);
17284     if (LambdaScopeInfo *LSI = S.getCurLambda())
17285       LSI->markVariableExprAsNonODRUsed(E);
17286   };
17287 
17288   // C++2a [basic.def.odr]p2:
17289   //   The set of potential results of an expression e is defined as follows:
17290   switch (E->getStmtClass()) {
17291   //   -- If e is an id-expression, ...
17292   case Expr::DeclRefExprClass: {
17293     auto *DRE = cast<DeclRefExpr>(E);
17294     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17295       break;
17296 
17297     // Rebuild as a non-odr-use DeclRefExpr.
17298     MarkNotOdrUsed();
17299     return DeclRefExpr::Create(
17300         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17301         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17302         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17303         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17304   }
17305 
17306   case Expr::FunctionParmPackExprClass: {
17307     auto *FPPE = cast<FunctionParmPackExpr>(E);
17308     // If any of the declarations in the pack is odr-used, then the expression
17309     // as a whole constitutes an odr-use.
17310     for (VarDecl *D : *FPPE)
17311       if (IsPotentialResultOdrUsed(D))
17312         return ExprEmpty();
17313 
17314     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17315     // nothing cares about whether we marked this as an odr-use, but it might
17316     // be useful for non-compiler tools.
17317     MarkNotOdrUsed();
17318     break;
17319   }
17320 
17321   //   -- If e is a subscripting operation with an array operand...
17322   case Expr::ArraySubscriptExprClass: {
17323     auto *ASE = cast<ArraySubscriptExpr>(E);
17324     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17325     if (!OldBase->getType()->isArrayType())
17326       break;
17327     ExprResult Base = Rebuild(OldBase);
17328     if (!Base.isUsable())
17329       return Base;
17330     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17331     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17332     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17333     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17334                                      ASE->getRBracketLoc());
17335   }
17336 
17337   case Expr::MemberExprClass: {
17338     auto *ME = cast<MemberExpr>(E);
17339     // -- If e is a class member access expression [...] naming a non-static
17340     //    data member...
17341     if (isa<FieldDecl>(ME->getMemberDecl())) {
17342       ExprResult Base = Rebuild(ME->getBase());
17343       if (!Base.isUsable())
17344         return Base;
17345       return MemberExpr::Create(
17346           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17347           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17348           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17349           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17350           ME->getObjectKind(), ME->isNonOdrUse());
17351     }
17352 
17353     if (ME->getMemberDecl()->isCXXInstanceMember())
17354       break;
17355 
17356     // -- If e is a class member access expression naming a static data member,
17357     //    ...
17358     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17359       break;
17360 
17361     // Rebuild as a non-odr-use MemberExpr.
17362     MarkNotOdrUsed();
17363     return MemberExpr::Create(
17364         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17365         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17366         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17367         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17368     return ExprEmpty();
17369   }
17370 
17371   case Expr::BinaryOperatorClass: {
17372     auto *BO = cast<BinaryOperator>(E);
17373     Expr *LHS = BO->getLHS();
17374     Expr *RHS = BO->getRHS();
17375     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17376     if (BO->getOpcode() == BO_PtrMemD) {
17377       ExprResult Sub = Rebuild(LHS);
17378       if (!Sub.isUsable())
17379         return Sub;
17380       LHS = Sub.get();
17381     //   -- If e is a comma expression, ...
17382     } else if (BO->getOpcode() == BO_Comma) {
17383       ExprResult Sub = Rebuild(RHS);
17384       if (!Sub.isUsable())
17385         return Sub;
17386       RHS = Sub.get();
17387     } else {
17388       break;
17389     }
17390     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17391                         LHS, RHS);
17392   }
17393 
17394   //   -- If e has the form (e1)...
17395   case Expr::ParenExprClass: {
17396     auto *PE = cast<ParenExpr>(E);
17397     ExprResult Sub = Rebuild(PE->getSubExpr());
17398     if (!Sub.isUsable())
17399       return Sub;
17400     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17401   }
17402 
17403   //   -- If e is a glvalue conditional expression, ...
17404   // We don't apply this to a binary conditional operator. FIXME: Should we?
17405   case Expr::ConditionalOperatorClass: {
17406     auto *CO = cast<ConditionalOperator>(E);
17407     ExprResult LHS = Rebuild(CO->getLHS());
17408     if (LHS.isInvalid())
17409       return ExprError();
17410     ExprResult RHS = Rebuild(CO->getRHS());
17411     if (RHS.isInvalid())
17412       return ExprError();
17413     if (!LHS.isUsable() && !RHS.isUsable())
17414       return ExprEmpty();
17415     if (!LHS.isUsable())
17416       LHS = CO->getLHS();
17417     if (!RHS.isUsable())
17418       RHS = CO->getRHS();
17419     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17420                                 CO->getCond(), LHS.get(), RHS.get());
17421   }
17422 
17423   // [Clang extension]
17424   //   -- If e has the form __extension__ e1...
17425   case Expr::UnaryOperatorClass: {
17426     auto *UO = cast<UnaryOperator>(E);
17427     if (UO->getOpcode() != UO_Extension)
17428       break;
17429     ExprResult Sub = Rebuild(UO->getSubExpr());
17430     if (!Sub.isUsable())
17431       return Sub;
17432     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17433                           Sub.get());
17434   }
17435 
17436   // [Clang extension]
17437   //   -- If e has the form _Generic(...), the set of potential results is the
17438   //      union of the sets of potential results of the associated expressions.
17439   case Expr::GenericSelectionExprClass: {
17440     auto *GSE = cast<GenericSelectionExpr>(E);
17441 
17442     SmallVector<Expr *, 4> AssocExprs;
17443     bool AnyChanged = false;
17444     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17445       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17446       if (AssocExpr.isInvalid())
17447         return ExprError();
17448       if (AssocExpr.isUsable()) {
17449         AssocExprs.push_back(AssocExpr.get());
17450         AnyChanged = true;
17451       } else {
17452         AssocExprs.push_back(OrigAssocExpr);
17453       }
17454     }
17455 
17456     return AnyChanged ? S.CreateGenericSelectionExpr(
17457                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17458                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17459                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17460                       : ExprEmpty();
17461   }
17462 
17463   // [Clang extension]
17464   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17465   //      results is the union of the sets of potential results of the
17466   //      second and third subexpressions.
17467   case Expr::ChooseExprClass: {
17468     auto *CE = cast<ChooseExpr>(E);
17469 
17470     ExprResult LHS = Rebuild(CE->getLHS());
17471     if (LHS.isInvalid())
17472       return ExprError();
17473 
17474     ExprResult RHS = Rebuild(CE->getLHS());
17475     if (RHS.isInvalid())
17476       return ExprError();
17477 
17478     if (!LHS.get() && !RHS.get())
17479       return ExprEmpty();
17480     if (!LHS.isUsable())
17481       LHS = CE->getLHS();
17482     if (!RHS.isUsable())
17483       RHS = CE->getRHS();
17484 
17485     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17486                              RHS.get(), CE->getRParenLoc());
17487   }
17488 
17489   // Step through non-syntactic nodes.
17490   case Expr::ConstantExprClass: {
17491     auto *CE = cast<ConstantExpr>(E);
17492     ExprResult Sub = Rebuild(CE->getSubExpr());
17493     if (!Sub.isUsable())
17494       return Sub;
17495     return ConstantExpr::Create(S.Context, Sub.get());
17496   }
17497 
17498   // We could mostly rely on the recursive rebuilding to rebuild implicit
17499   // casts, but not at the top level, so rebuild them here.
17500   case Expr::ImplicitCastExprClass: {
17501     auto *ICE = cast<ImplicitCastExpr>(E);
17502     // Only step through the narrow set of cast kinds we expect to encounter.
17503     // Anything else suggests we've left the region in which potential results
17504     // can be found.
17505     switch (ICE->getCastKind()) {
17506     case CK_NoOp:
17507     case CK_DerivedToBase:
17508     case CK_UncheckedDerivedToBase: {
17509       ExprResult Sub = Rebuild(ICE->getSubExpr());
17510       if (!Sub.isUsable())
17511         return Sub;
17512       CXXCastPath Path(ICE->path());
17513       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17514                                  ICE->getValueKind(), &Path);
17515     }
17516 
17517     default:
17518       break;
17519     }
17520     break;
17521   }
17522 
17523   default:
17524     break;
17525   }
17526 
17527   // Can't traverse through this node. Nothing to do.
17528   return ExprEmpty();
17529 }
17530 
17531 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17532   // Check whether the operand is or contains an object of non-trivial C union
17533   // type.
17534   if (E->getType().isVolatileQualified() &&
17535       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17536        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17537     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17538                           Sema::NTCUC_LValueToRValueVolatile,
17539                           NTCUK_Destruct|NTCUK_Copy);
17540 
17541   // C++2a [basic.def.odr]p4:
17542   //   [...] an expression of non-volatile-qualified non-class type to which
17543   //   the lvalue-to-rvalue conversion is applied [...]
17544   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17545     return E;
17546 
17547   ExprResult Result =
17548       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17549   if (Result.isInvalid())
17550     return ExprError();
17551   return Result.get() ? Result : E;
17552 }
17553 
17554 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17555   Res = CorrectDelayedTyposInExpr(Res);
17556 
17557   if (!Res.isUsable())
17558     return Res;
17559 
17560   // If a constant-expression is a reference to a variable where we delay
17561   // deciding whether it is an odr-use, just assume we will apply the
17562   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17563   // (a non-type template argument), we have special handling anyway.
17564   return CheckLValueToRValueConversionOperand(Res.get());
17565 }
17566 
17567 void Sema::CleanupVarDeclMarking() {
17568   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17569   // call.
17570   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17571   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17572 
17573   for (Expr *E : LocalMaybeODRUseExprs) {
17574     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17575       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17576                          DRE->getLocation(), *this);
17577     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17578       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17579                          *this);
17580     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17581       for (VarDecl *VD : *FP)
17582         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17583     } else {
17584       llvm_unreachable("Unexpected expression");
17585     }
17586   }
17587 
17588   assert(MaybeODRUseExprs.empty() &&
17589          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17590 }
17591 
17592 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17593                                     VarDecl *Var, Expr *E) {
17594   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17595           isa<FunctionParmPackExpr>(E)) &&
17596          "Invalid Expr argument to DoMarkVarDeclReferenced");
17597   Var->setReferenced();
17598 
17599   if (Var->isInvalidDecl())
17600     return;
17601 
17602   auto *MSI = Var->getMemberSpecializationInfo();
17603   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17604                                        : Var->getTemplateSpecializationKind();
17605 
17606   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17607   bool UsableInConstantExpr =
17608       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17609 
17610   // C++20 [expr.const]p12:
17611   //   A variable [...] is needed for constant evaluation if it is [...] a
17612   //   variable whose name appears as a potentially constant evaluated
17613   //   expression that is either a contexpr variable or is of non-volatile
17614   //   const-qualified integral type or of reference type
17615   bool NeededForConstantEvaluation =
17616       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17617 
17618   bool NeedDefinition =
17619       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17620 
17621   VarTemplateSpecializationDecl *VarSpec =
17622       dyn_cast<VarTemplateSpecializationDecl>(Var);
17623   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17624          "Can't instantiate a partial template specialization.");
17625 
17626   // If this might be a member specialization of a static data member, check
17627   // the specialization is visible. We already did the checks for variable
17628   // template specializations when we created them.
17629   if (NeedDefinition && TSK != TSK_Undeclared &&
17630       !isa<VarTemplateSpecializationDecl>(Var))
17631     SemaRef.checkSpecializationVisibility(Loc, Var);
17632 
17633   // Perform implicit instantiation of static data members, static data member
17634   // templates of class templates, and variable template specializations. Delay
17635   // instantiations of variable templates, except for those that could be used
17636   // in a constant expression.
17637   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17638     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17639     // instantiation declaration if a variable is usable in a constant
17640     // expression (among other cases).
17641     bool TryInstantiating =
17642         TSK == TSK_ImplicitInstantiation ||
17643         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17644 
17645     if (TryInstantiating) {
17646       SourceLocation PointOfInstantiation =
17647           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17648       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17649       if (FirstInstantiation) {
17650         PointOfInstantiation = Loc;
17651         if (MSI)
17652           MSI->setPointOfInstantiation(PointOfInstantiation);
17653         else
17654           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17655       }
17656 
17657       bool InstantiationDependent = false;
17658       bool IsNonDependent =
17659           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17660                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17661                   : true;
17662 
17663       // Do not instantiate specializations that are still type-dependent.
17664       if (IsNonDependent) {
17665         if (UsableInConstantExpr) {
17666           // Do not defer instantiations of variables that could be used in a
17667           // constant expression.
17668           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17669             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17670           });
17671         } else if (FirstInstantiation ||
17672                    isa<VarTemplateSpecializationDecl>(Var)) {
17673           // FIXME: For a specialization of a variable template, we don't
17674           // distinguish between "declaration and type implicitly instantiated"
17675           // and "implicit instantiation of definition requested", so we have
17676           // no direct way to avoid enqueueing the pending instantiation
17677           // multiple times.
17678           SemaRef.PendingInstantiations
17679               .push_back(std::make_pair(Var, PointOfInstantiation));
17680         }
17681       }
17682     }
17683   }
17684 
17685   // C++2a [basic.def.odr]p4:
17686   //   A variable x whose name appears as a potentially-evaluated expression e
17687   //   is odr-used by e unless
17688   //   -- x is a reference that is usable in constant expressions
17689   //   -- x is a variable of non-reference type that is usable in constant
17690   //      expressions and has no mutable subobjects [FIXME], and e is an
17691   //      element of the set of potential results of an expression of
17692   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17693   //      conversion is applied
17694   //   -- x is a variable of non-reference type, and e is an element of the set
17695   //      of potential results of a discarded-value expression to which the
17696   //      lvalue-to-rvalue conversion is not applied [FIXME]
17697   //
17698   // We check the first part of the second bullet here, and
17699   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17700   // FIXME: To get the third bullet right, we need to delay this even for
17701   // variables that are not usable in constant expressions.
17702 
17703   // If we already know this isn't an odr-use, there's nothing more to do.
17704   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17705     if (DRE->isNonOdrUse())
17706       return;
17707   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17708     if (ME->isNonOdrUse())
17709       return;
17710 
17711   switch (OdrUse) {
17712   case OdrUseContext::None:
17713     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17714            "missing non-odr-use marking for unevaluated decl ref");
17715     break;
17716 
17717   case OdrUseContext::FormallyOdrUsed:
17718     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17719     // behavior.
17720     break;
17721 
17722   case OdrUseContext::Used:
17723     // If we might later find that this expression isn't actually an odr-use,
17724     // delay the marking.
17725     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17726       SemaRef.MaybeODRUseExprs.insert(E);
17727     else
17728       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17729     break;
17730 
17731   case OdrUseContext::Dependent:
17732     // If this is a dependent context, we don't need to mark variables as
17733     // odr-used, but we may still need to track them for lambda capture.
17734     // FIXME: Do we also need to do this inside dependent typeid expressions
17735     // (which are modeled as unevaluated at this point)?
17736     const bool RefersToEnclosingScope =
17737         (SemaRef.CurContext != Var->getDeclContext() &&
17738          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17739     if (RefersToEnclosingScope) {
17740       LambdaScopeInfo *const LSI =
17741           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17742       if (LSI && (!LSI->CallOperator ||
17743                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17744         // If a variable could potentially be odr-used, defer marking it so
17745         // until we finish analyzing the full expression for any
17746         // lvalue-to-rvalue
17747         // or discarded value conversions that would obviate odr-use.
17748         // Add it to the list of potential captures that will be analyzed
17749         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17750         // unless the variable is a reference that was initialized by a constant
17751         // expression (this will never need to be captured or odr-used).
17752         //
17753         // FIXME: We can simplify this a lot after implementing P0588R1.
17754         assert(E && "Capture variable should be used in an expression.");
17755         if (!Var->getType()->isReferenceType() ||
17756             !Var->isUsableInConstantExpressions(SemaRef.Context))
17757           LSI->addPotentialCapture(E->IgnoreParens());
17758       }
17759     }
17760     break;
17761   }
17762 }
17763 
17764 /// Mark a variable referenced, and check whether it is odr-used
17765 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17766 /// used directly for normal expressions referring to VarDecl.
17767 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17768   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17769 }
17770 
17771 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17772                                Decl *D, Expr *E, bool MightBeOdrUse) {
17773   if (SemaRef.isInOpenMPDeclareTargetContext())
17774     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17775 
17776   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17777     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17778     return;
17779   }
17780 
17781   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17782 
17783   // If this is a call to a method via a cast, also mark the method in the
17784   // derived class used in case codegen can devirtualize the call.
17785   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17786   if (!ME)
17787     return;
17788   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17789   if (!MD)
17790     return;
17791   // Only attempt to devirtualize if this is truly a virtual call.
17792   bool IsVirtualCall = MD->isVirtual() &&
17793                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17794   if (!IsVirtualCall)
17795     return;
17796 
17797   // If it's possible to devirtualize the call, mark the called function
17798   // referenced.
17799   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17800       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17801   if (DM)
17802     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17803 }
17804 
17805 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17806 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17807   // TODO: update this with DR# once a defect report is filed.
17808   // C++11 defect. The address of a pure member should not be an ODR use, even
17809   // if it's a qualified reference.
17810   bool OdrUse = true;
17811   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17812     if (Method->isVirtual() &&
17813         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17814       OdrUse = false;
17815 
17816   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17817     if (!isConstantEvaluated() && FD->isConsteval() &&
17818         !RebuildingImmediateInvocation)
17819       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17820   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17821 }
17822 
17823 /// Perform reference-marking and odr-use handling for a MemberExpr.
17824 void Sema::MarkMemberReferenced(MemberExpr *E) {
17825   // C++11 [basic.def.odr]p2:
17826   //   A non-overloaded function whose name appears as a potentially-evaluated
17827   //   expression or a member of a set of candidate functions, if selected by
17828   //   overload resolution when referred to from a potentially-evaluated
17829   //   expression, is odr-used, unless it is a pure virtual function and its
17830   //   name is not explicitly qualified.
17831   bool MightBeOdrUse = true;
17832   if (E->performsVirtualDispatch(getLangOpts())) {
17833     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17834       if (Method->isPure())
17835         MightBeOdrUse = false;
17836   }
17837   SourceLocation Loc =
17838       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17839   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17840 }
17841 
17842 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17843 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17844   for (VarDecl *VD : *E)
17845     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17846 }
17847 
17848 /// Perform marking for a reference to an arbitrary declaration.  It
17849 /// marks the declaration referenced, and performs odr-use checking for
17850 /// functions and variables. This method should not be used when building a
17851 /// normal expression which refers to a variable.
17852 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17853                                  bool MightBeOdrUse) {
17854   if (MightBeOdrUse) {
17855     if (auto *VD = dyn_cast<VarDecl>(D)) {
17856       MarkVariableReferenced(Loc, VD);
17857       return;
17858     }
17859   }
17860   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17861     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17862     return;
17863   }
17864   D->setReferenced();
17865 }
17866 
17867 namespace {
17868   // Mark all of the declarations used by a type as referenced.
17869   // FIXME: Not fully implemented yet! We need to have a better understanding
17870   // of when we're entering a context we should not recurse into.
17871   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17872   // TreeTransforms rebuilding the type in a new context. Rather than
17873   // duplicating the TreeTransform logic, we should consider reusing it here.
17874   // Currently that causes problems when rebuilding LambdaExprs.
17875   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17876     Sema &S;
17877     SourceLocation Loc;
17878 
17879   public:
17880     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17881 
17882     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17883 
17884     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17885   };
17886 }
17887 
17888 bool MarkReferencedDecls::TraverseTemplateArgument(
17889     const TemplateArgument &Arg) {
17890   {
17891     // A non-type template argument is a constant-evaluated context.
17892     EnterExpressionEvaluationContext Evaluated(
17893         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17894     if (Arg.getKind() == TemplateArgument::Declaration) {
17895       if (Decl *D = Arg.getAsDecl())
17896         S.MarkAnyDeclReferenced(Loc, D, true);
17897     } else if (Arg.getKind() == TemplateArgument::Expression) {
17898       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17899     }
17900   }
17901 
17902   return Inherited::TraverseTemplateArgument(Arg);
17903 }
17904 
17905 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17906   MarkReferencedDecls Marker(*this, Loc);
17907   Marker.TraverseType(T);
17908 }
17909 
17910 namespace {
17911 /// Helper class that marks all of the declarations referenced by
17912 /// potentially-evaluated subexpressions as "referenced".
17913 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
17914 public:
17915   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
17916   bool SkipLocalVariables;
17917 
17918   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17919       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
17920 
17921   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17922     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
17923   }
17924 
17925   void VisitDeclRefExpr(DeclRefExpr *E) {
17926     // If we were asked not to visit local variables, don't.
17927     if (SkipLocalVariables) {
17928       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17929         if (VD->hasLocalStorage())
17930           return;
17931     }
17932     S.MarkDeclRefReferenced(E);
17933   }
17934 
17935   void VisitMemberExpr(MemberExpr *E) {
17936     S.MarkMemberReferenced(E);
17937     Visit(E->getBase());
17938   }
17939 };
17940 } // namespace
17941 
17942 /// Mark any declarations that appear within this expression or any
17943 /// potentially-evaluated subexpressions as "referenced".
17944 ///
17945 /// \param SkipLocalVariables If true, don't mark local variables as
17946 /// 'referenced'.
17947 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17948                                             bool SkipLocalVariables) {
17949   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17950 }
17951 
17952 /// Emit a diagnostic that describes an effect on the run-time behavior
17953 /// of the program being compiled.
17954 ///
17955 /// This routine emits the given diagnostic when the code currently being
17956 /// type-checked is "potentially evaluated", meaning that there is a
17957 /// possibility that the code will actually be executable. Code in sizeof()
17958 /// expressions, code used only during overload resolution, etc., are not
17959 /// potentially evaluated. This routine will suppress such diagnostics or,
17960 /// in the absolutely nutty case of potentially potentially evaluated
17961 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17962 /// later.
17963 ///
17964 /// This routine should be used for all diagnostics that describe the run-time
17965 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17966 /// Failure to do so will likely result in spurious diagnostics or failures
17967 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17968 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17969                                const PartialDiagnostic &PD) {
17970   switch (ExprEvalContexts.back().Context) {
17971   case ExpressionEvaluationContext::Unevaluated:
17972   case ExpressionEvaluationContext::UnevaluatedList:
17973   case ExpressionEvaluationContext::UnevaluatedAbstract:
17974   case ExpressionEvaluationContext::DiscardedStatement:
17975     // The argument will never be evaluated, so don't complain.
17976     break;
17977 
17978   case ExpressionEvaluationContext::ConstantEvaluated:
17979     // Relevant diagnostics should be produced by constant evaluation.
17980     break;
17981 
17982   case ExpressionEvaluationContext::PotentiallyEvaluated:
17983   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17984     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17985       FunctionScopes.back()->PossiblyUnreachableDiags.
17986         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17987       return true;
17988     }
17989 
17990     // The initializer of a constexpr variable or of the first declaration of a
17991     // static data member is not syntactically a constant evaluated constant,
17992     // but nonetheless is always required to be a constant expression, so we
17993     // can skip diagnosing.
17994     // FIXME: Using the mangling context here is a hack.
17995     if (auto *VD = dyn_cast_or_null<VarDecl>(
17996             ExprEvalContexts.back().ManglingContextDecl)) {
17997       if (VD->isConstexpr() ||
17998           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17999         break;
18000       // FIXME: For any other kind of variable, we should build a CFG for its
18001       // initializer and check whether the context in question is reachable.
18002     }
18003 
18004     Diag(Loc, PD);
18005     return true;
18006   }
18007 
18008   return false;
18009 }
18010 
18011 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18012                                const PartialDiagnostic &PD) {
18013   return DiagRuntimeBehavior(
18014       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18015 }
18016 
18017 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18018                                CallExpr *CE, FunctionDecl *FD) {
18019   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18020     return false;
18021 
18022   // If we're inside a decltype's expression, don't check for a valid return
18023   // type or construct temporaries until we know whether this is the last call.
18024   if (ExprEvalContexts.back().ExprContext ==
18025       ExpressionEvaluationContextRecord::EK_Decltype) {
18026     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18027     return false;
18028   }
18029 
18030   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18031     FunctionDecl *FD;
18032     CallExpr *CE;
18033 
18034   public:
18035     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18036       : FD(FD), CE(CE) { }
18037 
18038     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18039       if (!FD) {
18040         S.Diag(Loc, diag::err_call_incomplete_return)
18041           << T << CE->getSourceRange();
18042         return;
18043       }
18044 
18045       S.Diag(Loc, diag::err_call_function_incomplete_return)
18046         << CE->getSourceRange() << FD->getDeclName() << T;
18047       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18048           << FD->getDeclName();
18049     }
18050   } Diagnoser(FD, CE);
18051 
18052   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18053     return true;
18054 
18055   return false;
18056 }
18057 
18058 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18059 // will prevent this condition from triggering, which is what we want.
18060 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18061   SourceLocation Loc;
18062 
18063   unsigned diagnostic = diag::warn_condition_is_assignment;
18064   bool IsOrAssign = false;
18065 
18066   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18067     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18068       return;
18069 
18070     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18071 
18072     // Greylist some idioms by putting them into a warning subcategory.
18073     if (ObjCMessageExpr *ME
18074           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18075       Selector Sel = ME->getSelector();
18076 
18077       // self = [<foo> init...]
18078       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18079         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18080 
18081       // <foo> = [<bar> nextObject]
18082       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18083         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18084     }
18085 
18086     Loc = Op->getOperatorLoc();
18087   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18088     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18089       return;
18090 
18091     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18092     Loc = Op->getOperatorLoc();
18093   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18094     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18095   else {
18096     // Not an assignment.
18097     return;
18098   }
18099 
18100   Diag(Loc, diagnostic) << E->getSourceRange();
18101 
18102   SourceLocation Open = E->getBeginLoc();
18103   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18104   Diag(Loc, diag::note_condition_assign_silence)
18105         << FixItHint::CreateInsertion(Open, "(")
18106         << FixItHint::CreateInsertion(Close, ")");
18107 
18108   if (IsOrAssign)
18109     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18110       << FixItHint::CreateReplacement(Loc, "!=");
18111   else
18112     Diag(Loc, diag::note_condition_assign_to_comparison)
18113       << FixItHint::CreateReplacement(Loc, "==");
18114 }
18115 
18116 /// Redundant parentheses over an equality comparison can indicate
18117 /// that the user intended an assignment used as condition.
18118 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18119   // Don't warn if the parens came from a macro.
18120   SourceLocation parenLoc = ParenE->getBeginLoc();
18121   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18122     return;
18123   // Don't warn for dependent expressions.
18124   if (ParenE->isTypeDependent())
18125     return;
18126 
18127   Expr *E = ParenE->IgnoreParens();
18128 
18129   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18130     if (opE->getOpcode() == BO_EQ &&
18131         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18132                                                            == Expr::MLV_Valid) {
18133       SourceLocation Loc = opE->getOperatorLoc();
18134 
18135       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18136       SourceRange ParenERange = ParenE->getSourceRange();
18137       Diag(Loc, diag::note_equality_comparison_silence)
18138         << FixItHint::CreateRemoval(ParenERange.getBegin())
18139         << FixItHint::CreateRemoval(ParenERange.getEnd());
18140       Diag(Loc, diag::note_equality_comparison_to_assign)
18141         << FixItHint::CreateReplacement(Loc, "=");
18142     }
18143 }
18144 
18145 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18146                                        bool IsConstexpr) {
18147   DiagnoseAssignmentAsCondition(E);
18148   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18149     DiagnoseEqualityWithExtraParens(parenE);
18150 
18151   ExprResult result = CheckPlaceholderExpr(E);
18152   if (result.isInvalid()) return ExprError();
18153   E = result.get();
18154 
18155   if (!E->isTypeDependent()) {
18156     if (getLangOpts().CPlusPlus)
18157       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18158 
18159     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18160     if (ERes.isInvalid())
18161       return ExprError();
18162     E = ERes.get();
18163 
18164     QualType T = E->getType();
18165     if (!T->isScalarType()) { // C99 6.8.4.1p1
18166       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18167         << T << E->getSourceRange();
18168       return ExprError();
18169     }
18170     CheckBoolLikeConversion(E, Loc);
18171   }
18172 
18173   return E;
18174 }
18175 
18176 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18177                                            Expr *SubExpr, ConditionKind CK) {
18178   // Empty conditions are valid in for-statements.
18179   if (!SubExpr)
18180     return ConditionResult();
18181 
18182   ExprResult Cond;
18183   switch (CK) {
18184   case ConditionKind::Boolean:
18185     Cond = CheckBooleanCondition(Loc, SubExpr);
18186     break;
18187 
18188   case ConditionKind::ConstexprIf:
18189     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18190     break;
18191 
18192   case ConditionKind::Switch:
18193     Cond = CheckSwitchCondition(Loc, SubExpr);
18194     break;
18195   }
18196   if (Cond.isInvalid())
18197     return ConditionError();
18198 
18199   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18200   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18201   if (!FullExpr.get())
18202     return ConditionError();
18203 
18204   return ConditionResult(*this, nullptr, FullExpr,
18205                          CK == ConditionKind::ConstexprIf);
18206 }
18207 
18208 namespace {
18209   /// A visitor for rebuilding a call to an __unknown_any expression
18210   /// to have an appropriate type.
18211   struct RebuildUnknownAnyFunction
18212     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18213 
18214     Sema &S;
18215 
18216     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18217 
18218     ExprResult VisitStmt(Stmt *S) {
18219       llvm_unreachable("unexpected statement!");
18220     }
18221 
18222     ExprResult VisitExpr(Expr *E) {
18223       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18224         << E->getSourceRange();
18225       return ExprError();
18226     }
18227 
18228     /// Rebuild an expression which simply semantically wraps another
18229     /// expression which it shares the type and value kind of.
18230     template <class T> ExprResult rebuildSugarExpr(T *E) {
18231       ExprResult SubResult = Visit(E->getSubExpr());
18232       if (SubResult.isInvalid()) return ExprError();
18233 
18234       Expr *SubExpr = SubResult.get();
18235       E->setSubExpr(SubExpr);
18236       E->setType(SubExpr->getType());
18237       E->setValueKind(SubExpr->getValueKind());
18238       assert(E->getObjectKind() == OK_Ordinary);
18239       return E;
18240     }
18241 
18242     ExprResult VisitParenExpr(ParenExpr *E) {
18243       return rebuildSugarExpr(E);
18244     }
18245 
18246     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18247       return rebuildSugarExpr(E);
18248     }
18249 
18250     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18251       ExprResult SubResult = Visit(E->getSubExpr());
18252       if (SubResult.isInvalid()) return ExprError();
18253 
18254       Expr *SubExpr = SubResult.get();
18255       E->setSubExpr(SubExpr);
18256       E->setType(S.Context.getPointerType(SubExpr->getType()));
18257       assert(E->getValueKind() == VK_RValue);
18258       assert(E->getObjectKind() == OK_Ordinary);
18259       return E;
18260     }
18261 
18262     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18263       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18264 
18265       E->setType(VD->getType());
18266 
18267       assert(E->getValueKind() == VK_RValue);
18268       if (S.getLangOpts().CPlusPlus &&
18269           !(isa<CXXMethodDecl>(VD) &&
18270             cast<CXXMethodDecl>(VD)->isInstance()))
18271         E->setValueKind(VK_LValue);
18272 
18273       return E;
18274     }
18275 
18276     ExprResult VisitMemberExpr(MemberExpr *E) {
18277       return resolveDecl(E, E->getMemberDecl());
18278     }
18279 
18280     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18281       return resolveDecl(E, E->getDecl());
18282     }
18283   };
18284 }
18285 
18286 /// Given a function expression of unknown-any type, try to rebuild it
18287 /// to have a function type.
18288 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18289   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18290   if (Result.isInvalid()) return ExprError();
18291   return S.DefaultFunctionArrayConversion(Result.get());
18292 }
18293 
18294 namespace {
18295   /// A visitor for rebuilding an expression of type __unknown_anytype
18296   /// into one which resolves the type directly on the referring
18297   /// expression.  Strict preservation of the original source
18298   /// structure is not a goal.
18299   struct RebuildUnknownAnyExpr
18300     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18301 
18302     Sema &S;
18303 
18304     /// The current destination type.
18305     QualType DestType;
18306 
18307     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18308       : S(S), DestType(CastType) {}
18309 
18310     ExprResult VisitStmt(Stmt *S) {
18311       llvm_unreachable("unexpected statement!");
18312     }
18313 
18314     ExprResult VisitExpr(Expr *E) {
18315       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18316         << E->getSourceRange();
18317       return ExprError();
18318     }
18319 
18320     ExprResult VisitCallExpr(CallExpr *E);
18321     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18322 
18323     /// Rebuild an expression which simply semantically wraps another
18324     /// expression which it shares the type and value kind of.
18325     template <class T> ExprResult rebuildSugarExpr(T *E) {
18326       ExprResult SubResult = Visit(E->getSubExpr());
18327       if (SubResult.isInvalid()) return ExprError();
18328       Expr *SubExpr = SubResult.get();
18329       E->setSubExpr(SubExpr);
18330       E->setType(SubExpr->getType());
18331       E->setValueKind(SubExpr->getValueKind());
18332       assert(E->getObjectKind() == OK_Ordinary);
18333       return E;
18334     }
18335 
18336     ExprResult VisitParenExpr(ParenExpr *E) {
18337       return rebuildSugarExpr(E);
18338     }
18339 
18340     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18341       return rebuildSugarExpr(E);
18342     }
18343 
18344     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18345       const PointerType *Ptr = DestType->getAs<PointerType>();
18346       if (!Ptr) {
18347         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18348           << E->getSourceRange();
18349         return ExprError();
18350       }
18351 
18352       if (isa<CallExpr>(E->getSubExpr())) {
18353         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18354           << E->getSourceRange();
18355         return ExprError();
18356       }
18357 
18358       assert(E->getValueKind() == VK_RValue);
18359       assert(E->getObjectKind() == OK_Ordinary);
18360       E->setType(DestType);
18361 
18362       // Build the sub-expression as if it were an object of the pointee type.
18363       DestType = Ptr->getPointeeType();
18364       ExprResult SubResult = Visit(E->getSubExpr());
18365       if (SubResult.isInvalid()) return ExprError();
18366       E->setSubExpr(SubResult.get());
18367       return E;
18368     }
18369 
18370     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18371 
18372     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18373 
18374     ExprResult VisitMemberExpr(MemberExpr *E) {
18375       return resolveDecl(E, E->getMemberDecl());
18376     }
18377 
18378     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18379       return resolveDecl(E, E->getDecl());
18380     }
18381   };
18382 }
18383 
18384 /// Rebuilds a call expression which yielded __unknown_anytype.
18385 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18386   Expr *CalleeExpr = E->getCallee();
18387 
18388   enum FnKind {
18389     FK_MemberFunction,
18390     FK_FunctionPointer,
18391     FK_BlockPointer
18392   };
18393 
18394   FnKind Kind;
18395   QualType CalleeType = CalleeExpr->getType();
18396   if (CalleeType == S.Context.BoundMemberTy) {
18397     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18398     Kind = FK_MemberFunction;
18399     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18400   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18401     CalleeType = Ptr->getPointeeType();
18402     Kind = FK_FunctionPointer;
18403   } else {
18404     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18405     Kind = FK_BlockPointer;
18406   }
18407   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18408 
18409   // Verify that this is a legal result type of a function.
18410   if (DestType->isArrayType() || DestType->isFunctionType()) {
18411     unsigned diagID = diag::err_func_returning_array_function;
18412     if (Kind == FK_BlockPointer)
18413       diagID = diag::err_block_returning_array_function;
18414 
18415     S.Diag(E->getExprLoc(), diagID)
18416       << DestType->isFunctionType() << DestType;
18417     return ExprError();
18418   }
18419 
18420   // Otherwise, go ahead and set DestType as the call's result.
18421   E->setType(DestType.getNonLValueExprType(S.Context));
18422   E->setValueKind(Expr::getValueKindForType(DestType));
18423   assert(E->getObjectKind() == OK_Ordinary);
18424 
18425   // Rebuild the function type, replacing the result type with DestType.
18426   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18427   if (Proto) {
18428     // __unknown_anytype(...) is a special case used by the debugger when
18429     // it has no idea what a function's signature is.
18430     //
18431     // We want to build this call essentially under the K&R
18432     // unprototyped rules, but making a FunctionNoProtoType in C++
18433     // would foul up all sorts of assumptions.  However, we cannot
18434     // simply pass all arguments as variadic arguments, nor can we
18435     // portably just call the function under a non-variadic type; see
18436     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18437     // However, it turns out that in practice it is generally safe to
18438     // call a function declared as "A foo(B,C,D);" under the prototype
18439     // "A foo(B,C,D,...);".  The only known exception is with the
18440     // Windows ABI, where any variadic function is implicitly cdecl
18441     // regardless of its normal CC.  Therefore we change the parameter
18442     // types to match the types of the arguments.
18443     //
18444     // This is a hack, but it is far superior to moving the
18445     // corresponding target-specific code from IR-gen to Sema/AST.
18446 
18447     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18448     SmallVector<QualType, 8> ArgTypes;
18449     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18450       ArgTypes.reserve(E->getNumArgs());
18451       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18452         Expr *Arg = E->getArg(i);
18453         QualType ArgType = Arg->getType();
18454         if (E->isLValue()) {
18455           ArgType = S.Context.getLValueReferenceType(ArgType);
18456         } else if (E->isXValue()) {
18457           ArgType = S.Context.getRValueReferenceType(ArgType);
18458         }
18459         ArgTypes.push_back(ArgType);
18460       }
18461       ParamTypes = ArgTypes;
18462     }
18463     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18464                                          Proto->getExtProtoInfo());
18465   } else {
18466     DestType = S.Context.getFunctionNoProtoType(DestType,
18467                                                 FnType->getExtInfo());
18468   }
18469 
18470   // Rebuild the appropriate pointer-to-function type.
18471   switch (Kind) {
18472   case FK_MemberFunction:
18473     // Nothing to do.
18474     break;
18475 
18476   case FK_FunctionPointer:
18477     DestType = S.Context.getPointerType(DestType);
18478     break;
18479 
18480   case FK_BlockPointer:
18481     DestType = S.Context.getBlockPointerType(DestType);
18482     break;
18483   }
18484 
18485   // Finally, we can recurse.
18486   ExprResult CalleeResult = Visit(CalleeExpr);
18487   if (!CalleeResult.isUsable()) return ExprError();
18488   E->setCallee(CalleeResult.get());
18489 
18490   // Bind a temporary if necessary.
18491   return S.MaybeBindToTemporary(E);
18492 }
18493 
18494 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18495   // Verify that this is a legal result type of a call.
18496   if (DestType->isArrayType() || DestType->isFunctionType()) {
18497     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18498       << DestType->isFunctionType() << DestType;
18499     return ExprError();
18500   }
18501 
18502   // Rewrite the method result type if available.
18503   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18504     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18505     Method->setReturnType(DestType);
18506   }
18507 
18508   // Change the type of the message.
18509   E->setType(DestType.getNonReferenceType());
18510   E->setValueKind(Expr::getValueKindForType(DestType));
18511 
18512   return S.MaybeBindToTemporary(E);
18513 }
18514 
18515 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18516   // The only case we should ever see here is a function-to-pointer decay.
18517   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18518     assert(E->getValueKind() == VK_RValue);
18519     assert(E->getObjectKind() == OK_Ordinary);
18520 
18521     E->setType(DestType);
18522 
18523     // Rebuild the sub-expression as the pointee (function) type.
18524     DestType = DestType->castAs<PointerType>()->getPointeeType();
18525 
18526     ExprResult Result = Visit(E->getSubExpr());
18527     if (!Result.isUsable()) return ExprError();
18528 
18529     E->setSubExpr(Result.get());
18530     return E;
18531   } else if (E->getCastKind() == CK_LValueToRValue) {
18532     assert(E->getValueKind() == VK_RValue);
18533     assert(E->getObjectKind() == OK_Ordinary);
18534 
18535     assert(isa<BlockPointerType>(E->getType()));
18536 
18537     E->setType(DestType);
18538 
18539     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18540     DestType = S.Context.getLValueReferenceType(DestType);
18541 
18542     ExprResult Result = Visit(E->getSubExpr());
18543     if (!Result.isUsable()) return ExprError();
18544 
18545     E->setSubExpr(Result.get());
18546     return E;
18547   } else {
18548     llvm_unreachable("Unhandled cast type!");
18549   }
18550 }
18551 
18552 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18553   ExprValueKind ValueKind = VK_LValue;
18554   QualType Type = DestType;
18555 
18556   // We know how to make this work for certain kinds of decls:
18557 
18558   //  - functions
18559   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18560     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18561       DestType = Ptr->getPointeeType();
18562       ExprResult Result = resolveDecl(E, VD);
18563       if (Result.isInvalid()) return ExprError();
18564       return S.ImpCastExprToType(Result.get(), Type,
18565                                  CK_FunctionToPointerDecay, VK_RValue);
18566     }
18567 
18568     if (!Type->isFunctionType()) {
18569       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18570         << VD << E->getSourceRange();
18571       return ExprError();
18572     }
18573     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18574       // We must match the FunctionDecl's type to the hack introduced in
18575       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18576       // type. See the lengthy commentary in that routine.
18577       QualType FDT = FD->getType();
18578       const FunctionType *FnType = FDT->castAs<FunctionType>();
18579       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18580       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18581       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18582         SourceLocation Loc = FD->getLocation();
18583         FunctionDecl *NewFD = FunctionDecl::Create(
18584             S.Context, FD->getDeclContext(), Loc, Loc,
18585             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18586             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18587             /*ConstexprKind*/ CSK_unspecified);
18588 
18589         if (FD->getQualifier())
18590           NewFD->setQualifierInfo(FD->getQualifierLoc());
18591 
18592         SmallVector<ParmVarDecl*, 16> Params;
18593         for (const auto &AI : FT->param_types()) {
18594           ParmVarDecl *Param =
18595             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18596           Param->setScopeInfo(0, Params.size());
18597           Params.push_back(Param);
18598         }
18599         NewFD->setParams(Params);
18600         DRE->setDecl(NewFD);
18601         VD = DRE->getDecl();
18602       }
18603     }
18604 
18605     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18606       if (MD->isInstance()) {
18607         ValueKind = VK_RValue;
18608         Type = S.Context.BoundMemberTy;
18609       }
18610 
18611     // Function references aren't l-values in C.
18612     if (!S.getLangOpts().CPlusPlus)
18613       ValueKind = VK_RValue;
18614 
18615   //  - variables
18616   } else if (isa<VarDecl>(VD)) {
18617     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18618       Type = RefTy->getPointeeType();
18619     } else if (Type->isFunctionType()) {
18620       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18621         << VD << E->getSourceRange();
18622       return ExprError();
18623     }
18624 
18625   //  - nothing else
18626   } else {
18627     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18628       << VD << E->getSourceRange();
18629     return ExprError();
18630   }
18631 
18632   // Modifying the declaration like this is friendly to IR-gen but
18633   // also really dangerous.
18634   VD->setType(DestType);
18635   E->setType(Type);
18636   E->setValueKind(ValueKind);
18637   return E;
18638 }
18639 
18640 /// Check a cast of an unknown-any type.  We intentionally only
18641 /// trigger this for C-style casts.
18642 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18643                                      Expr *CastExpr, CastKind &CastKind,
18644                                      ExprValueKind &VK, CXXCastPath &Path) {
18645   // The type we're casting to must be either void or complete.
18646   if (!CastType->isVoidType() &&
18647       RequireCompleteType(TypeRange.getBegin(), CastType,
18648                           diag::err_typecheck_cast_to_incomplete))
18649     return ExprError();
18650 
18651   // Rewrite the casted expression from scratch.
18652   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18653   if (!result.isUsable()) return ExprError();
18654 
18655   CastExpr = result.get();
18656   VK = CastExpr->getValueKind();
18657   CastKind = CK_NoOp;
18658 
18659   return CastExpr;
18660 }
18661 
18662 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18663   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18664 }
18665 
18666 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18667                                     Expr *arg, QualType &paramType) {
18668   // If the syntactic form of the argument is not an explicit cast of
18669   // any sort, just do default argument promotion.
18670   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18671   if (!castArg) {
18672     ExprResult result = DefaultArgumentPromotion(arg);
18673     if (result.isInvalid()) return ExprError();
18674     paramType = result.get()->getType();
18675     return result;
18676   }
18677 
18678   // Otherwise, use the type that was written in the explicit cast.
18679   assert(!arg->hasPlaceholderType());
18680   paramType = castArg->getTypeAsWritten();
18681 
18682   // Copy-initialize a parameter of that type.
18683   InitializedEntity entity =
18684     InitializedEntity::InitializeParameter(Context, paramType,
18685                                            /*consumed*/ false);
18686   return PerformCopyInitialization(entity, callLoc, arg);
18687 }
18688 
18689 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18690   Expr *orig = E;
18691   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18692   while (true) {
18693     E = E->IgnoreParenImpCasts();
18694     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18695       E = call->getCallee();
18696       diagID = diag::err_uncasted_call_of_unknown_any;
18697     } else {
18698       break;
18699     }
18700   }
18701 
18702   SourceLocation loc;
18703   NamedDecl *d;
18704   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18705     loc = ref->getLocation();
18706     d = ref->getDecl();
18707   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18708     loc = mem->getMemberLoc();
18709     d = mem->getMemberDecl();
18710   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18711     diagID = diag::err_uncasted_call_of_unknown_any;
18712     loc = msg->getSelectorStartLoc();
18713     d = msg->getMethodDecl();
18714     if (!d) {
18715       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18716         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18717         << orig->getSourceRange();
18718       return ExprError();
18719     }
18720   } else {
18721     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18722       << E->getSourceRange();
18723     return ExprError();
18724   }
18725 
18726   S.Diag(loc, diagID) << d << orig->getSourceRange();
18727 
18728   // Never recoverable.
18729   return ExprError();
18730 }
18731 
18732 /// Check for operands with placeholder types and complain if found.
18733 /// Returns ExprError() if there was an error and no recovery was possible.
18734 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18735   if (!getLangOpts().CPlusPlus) {
18736     // C cannot handle TypoExpr nodes on either side of a binop because it
18737     // doesn't handle dependent types properly, so make sure any TypoExprs have
18738     // been dealt with before checking the operands.
18739     ExprResult Result = CorrectDelayedTyposInExpr(E);
18740     if (!Result.isUsable()) return ExprError();
18741     E = Result.get();
18742   }
18743 
18744   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18745   if (!placeholderType) return E;
18746 
18747   switch (placeholderType->getKind()) {
18748 
18749   // Overloaded expressions.
18750   case BuiltinType::Overload: {
18751     // Try to resolve a single function template specialization.
18752     // This is obligatory.
18753     ExprResult Result = E;
18754     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18755       return Result;
18756 
18757     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18758     // leaves Result unchanged on failure.
18759     Result = E;
18760     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18761       return Result;
18762 
18763     // If that failed, try to recover with a call.
18764     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18765                          /*complain*/ true);
18766     return Result;
18767   }
18768 
18769   // Bound member functions.
18770   case BuiltinType::BoundMember: {
18771     ExprResult result = E;
18772     const Expr *BME = E->IgnoreParens();
18773     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18774     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18775     if (isa<CXXPseudoDestructorExpr>(BME)) {
18776       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18777     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18778       if (ME->getMemberNameInfo().getName().getNameKind() ==
18779           DeclarationName::CXXDestructorName)
18780         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18781     }
18782     tryToRecoverWithCall(result, PD,
18783                          /*complain*/ true);
18784     return result;
18785   }
18786 
18787   // ARC unbridged casts.
18788   case BuiltinType::ARCUnbridgedCast: {
18789     Expr *realCast = stripARCUnbridgedCast(E);
18790     diagnoseARCUnbridgedCast(realCast);
18791     return realCast;
18792   }
18793 
18794   // Expressions of unknown type.
18795   case BuiltinType::UnknownAny:
18796     return diagnoseUnknownAnyExpr(*this, E);
18797 
18798   // Pseudo-objects.
18799   case BuiltinType::PseudoObject:
18800     return checkPseudoObjectRValue(E);
18801 
18802   case BuiltinType::BuiltinFn: {
18803     // Accept __noop without parens by implicitly converting it to a call expr.
18804     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18805     if (DRE) {
18806       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18807       if (FD->getBuiltinID() == Builtin::BI__noop) {
18808         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18809                               CK_BuiltinFnToFnPtr)
18810                 .get();
18811         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18812                                 VK_RValue, SourceLocation());
18813       }
18814     }
18815 
18816     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18817     return ExprError();
18818   }
18819 
18820   // Expressions of unknown type.
18821   case BuiltinType::OMPArraySection:
18822     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18823     return ExprError();
18824 
18825   // Expressions of unknown type.
18826   case BuiltinType::OMPArrayShaping:
18827     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
18828 
18829   case BuiltinType::OMPIterator:
18830     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
18831 
18832   // Everything else should be impossible.
18833 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18834   case BuiltinType::Id:
18835 #include "clang/Basic/OpenCLImageTypes.def"
18836 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18837   case BuiltinType::Id:
18838 #include "clang/Basic/OpenCLExtensionTypes.def"
18839 #define SVE_TYPE(Name, Id, SingletonId) \
18840   case BuiltinType::Id:
18841 #include "clang/Basic/AArch64SVEACLETypes.def"
18842 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18843 #define PLACEHOLDER_TYPE(Id, SingletonId)
18844 #include "clang/AST/BuiltinTypes.def"
18845     break;
18846   }
18847 
18848   llvm_unreachable("invalid placeholder type!");
18849 }
18850 
18851 bool Sema::CheckCaseExpression(Expr *E) {
18852   if (E->isTypeDependent())
18853     return true;
18854   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18855     return E->getType()->isIntegralOrEnumerationType();
18856   return false;
18857 }
18858 
18859 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18860 ExprResult
18861 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18862   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18863          "Unknown Objective-C Boolean value!");
18864   QualType BoolT = Context.ObjCBuiltinBoolTy;
18865   if (!Context.getBOOLDecl()) {
18866     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18867                         Sema::LookupOrdinaryName);
18868     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18869       NamedDecl *ND = Result.getFoundDecl();
18870       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18871         Context.setBOOLDecl(TD);
18872     }
18873   }
18874   if (Context.getBOOLDecl())
18875     BoolT = Context.getBOOLType();
18876   return new (Context)
18877       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18878 }
18879 
18880 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18881     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18882     SourceLocation RParen) {
18883 
18884   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18885 
18886   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18887     return Spec.getPlatform() == Platform;
18888   });
18889 
18890   VersionTuple Version;
18891   if (Spec != AvailSpecs.end())
18892     Version = Spec->getVersion();
18893 
18894   // The use of `@available` in the enclosing function should be analyzed to
18895   // warn when it's used inappropriately (i.e. not if(@available)).
18896   if (getCurFunctionOrMethodDecl())
18897     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18898   else if (getCurBlock() || getCurLambda())
18899     getCurFunction()->HasPotentialAvailabilityViolations = true;
18900 
18901   return new (Context)
18902       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18903 }
18904 
18905 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18906   assert(E->isTypeDependent());
18907   return isa<UnresolvedLookupExpr>(E);
18908 }
18909 
18910 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
18911                                     ArrayRef<Expr *> SubExprs) {
18912   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
18913   // bogus diagnostics and this trick does not work in C.
18914   // FIXME: use containsErrors() to suppress unwanted diags in C.
18915   if (!Context.getLangOpts().RecoveryAST)
18916     return ExprError();
18917 
18918   if (isSFINAEContext())
18919     return ExprError();
18920 
18921   return RecoveryExpr::Create(Context, Begin, End, SubExprs);
18922 }
18923