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     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361 
362   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
363       !isUnevaluatedContext()) {
364     // C++ [expr.prim.req.nested] p3
365     //   A local parameter shall only appear as an unevaluated operand
366     //   (Clause 8) within the constraint-expression.
367     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
368         << D;
369     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
370     return true;
371   }
372 
373   return false;
374 }
375 
376 /// DiagnoseSentinelCalls - This routine checks whether a call or
377 /// message-send is to a declaration with the sentinel attribute, and
378 /// if so, it checks that the requirements of the sentinel are
379 /// satisfied.
380 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
381                                  ArrayRef<Expr *> Args) {
382   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
383   if (!attr)
384     return;
385 
386   // The number of formal parameters of the declaration.
387   unsigned numFormalParams;
388 
389   // The kind of declaration.  This is also an index into a %select in
390   // the diagnostic.
391   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
392 
393   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
394     numFormalParams = MD->param_size();
395     calleeType = CT_Method;
396   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
397     numFormalParams = FD->param_size();
398     calleeType = CT_Function;
399   } else if (isa<VarDecl>(D)) {
400     QualType type = cast<ValueDecl>(D)->getType();
401     const FunctionType *fn = nullptr;
402     if (const PointerType *ptr = type->getAs<PointerType>()) {
403       fn = ptr->getPointeeType()->getAs<FunctionType>();
404       if (!fn) return;
405       calleeType = CT_Function;
406     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
407       fn = ptr->getPointeeType()->castAs<FunctionType>();
408       calleeType = CT_Block;
409     } else {
410       return;
411     }
412 
413     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
414       numFormalParams = proto->getNumParams();
415     } else {
416       numFormalParams = 0;
417     }
418   } else {
419     return;
420   }
421 
422   // "nullPos" is the number of formal parameters at the end which
423   // effectively count as part of the variadic arguments.  This is
424   // useful if you would prefer to not have *any* formal parameters,
425   // but the language forces you to have at least one.
426   unsigned nullPos = attr->getNullPos();
427   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
428   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
429 
430   // The number of arguments which should follow the sentinel.
431   unsigned numArgsAfterSentinel = attr->getSentinel();
432 
433   // If there aren't enough arguments for all the formal parameters,
434   // the sentinel, and the args after the sentinel, complain.
435   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
436     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
437     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
438     return;
439   }
440 
441   // Otherwise, find the sentinel expression.
442   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
443   if (!sentinelExpr) return;
444   if (sentinelExpr->isValueDependent()) return;
445   if (Context.isSentinelNullExpr(sentinelExpr)) return;
446 
447   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
448   // or 'NULL' if those are actually defined in the context.  Only use
449   // 'nil' for ObjC methods, where it's much more likely that the
450   // variadic arguments form a list of object pointers.
451   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
452   std::string NullValue;
453   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
454     NullValue = "nil";
455   else if (getLangOpts().CPlusPlus11)
456     NullValue = "nullptr";
457   else if (PP.isMacroDefined("NULL"))
458     NullValue = "NULL";
459   else
460     NullValue = "(void*) 0";
461 
462   if (MissingNilLoc.isInvalid())
463     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
464   else
465     Diag(MissingNilLoc, diag::warn_missing_sentinel)
466       << int(calleeType)
467       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
468   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
469 }
470 
471 SourceRange Sema::getExprRange(Expr *E) const {
472   return E ? E->getSourceRange() : SourceRange();
473 }
474 
475 //===----------------------------------------------------------------------===//
476 //  Standard Promotions and Conversions
477 //===----------------------------------------------------------------------===//
478 
479 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
480 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
481   // Handle any placeholder expressions which made it here.
482   if (E->getType()->isPlaceholderType()) {
483     ExprResult result = CheckPlaceholderExpr(E);
484     if (result.isInvalid()) return ExprError();
485     E = result.get();
486   }
487 
488   QualType Ty = E->getType();
489   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
490 
491   if (Ty->isFunctionType()) {
492     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
493       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
494         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
495           return ExprError();
496 
497     E = ImpCastExprToType(E, Context.getPointerType(Ty),
498                           CK_FunctionToPointerDecay).get();
499   } else if (Ty->isArrayType()) {
500     // In C90 mode, arrays only promote to pointers if the array expression is
501     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
502     // type 'array of type' is converted to an expression that has type 'pointer
503     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
504     // that has type 'array of type' ...".  The relevant change is "an lvalue"
505     // (C90) to "an expression" (C99).
506     //
507     // C++ 4.2p1:
508     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
509     // T" can be converted to an rvalue of type "pointer to T".
510     //
511     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
512       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
513                             CK_ArrayToPointerDecay).get();
514   }
515   return E;
516 }
517 
518 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
519   // Check to see if we are dereferencing a null pointer.  If so,
520   // and if not volatile-qualified, this is undefined behavior that the
521   // optimizer will delete, so warn about it.  People sometimes try to use this
522   // to get a deterministic trap and are surprised by clang's behavior.  This
523   // only handles the pattern "*null", which is a very syntactic check.
524   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
525   if (UO && UO->getOpcode() == UO_Deref &&
526       UO->getSubExpr()->getType()->isPointerType()) {
527     const LangAS AS =
528         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
529     if ((!isTargetAddressSpace(AS) ||
530          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
531         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
532             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
533         !UO->getType().isVolatileQualified()) {
534       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
535                             S.PDiag(diag::warn_indirection_through_null)
536                                 << UO->getSubExpr()->getSourceRange());
537       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
538                             S.PDiag(diag::note_indirection_through_null));
539     }
540   }
541 }
542 
543 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
544                                     SourceLocation AssignLoc,
545                                     const Expr* RHS) {
546   const ObjCIvarDecl *IV = OIRE->getDecl();
547   if (!IV)
548     return;
549 
550   DeclarationName MemberName = IV->getDeclName();
551   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
552   if (!Member || !Member->isStr("isa"))
553     return;
554 
555   const Expr *Base = OIRE->getBase();
556   QualType BaseType = Base->getType();
557   if (OIRE->isArrow())
558     BaseType = BaseType->getPointeeType();
559   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
560     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
561       ObjCInterfaceDecl *ClassDeclared = nullptr;
562       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
563       if (!ClassDeclared->getSuperClass()
564           && (*ClassDeclared->ivar_begin()) == IV) {
565         if (RHS) {
566           NamedDecl *ObjectSetClass =
567             S.LookupSingleName(S.TUScope,
568                                &S.Context.Idents.get("object_setClass"),
569                                SourceLocation(), S.LookupOrdinaryName);
570           if (ObjectSetClass) {
571             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
572             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
573                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
574                                               "object_setClass(")
575                 << FixItHint::CreateReplacement(
576                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
577                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
578           }
579           else
580             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
581         } else {
582           NamedDecl *ObjectGetClass =
583             S.LookupSingleName(S.TUScope,
584                                &S.Context.Idents.get("object_getClass"),
585                                SourceLocation(), S.LookupOrdinaryName);
586           if (ObjectGetClass)
587             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
588                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
589                                               "object_getClass(")
590                 << FixItHint::CreateReplacement(
591                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
592           else
593             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
594         }
595         S.Diag(IV->getLocation(), diag::note_ivar_decl);
596       }
597     }
598 }
599 
600 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
601   // Handle any placeholder expressions which made it here.
602   if (E->getType()->isPlaceholderType()) {
603     ExprResult result = CheckPlaceholderExpr(E);
604     if (result.isInvalid()) return ExprError();
605     E = result.get();
606   }
607 
608   // C++ [conv.lval]p1:
609   //   A glvalue of a non-function, non-array type T can be
610   //   converted to a prvalue.
611   if (!E->isGLValue()) return E;
612 
613   QualType T = E->getType();
614   assert(!T.isNull() && "r-value conversion on typeless expression?");
615 
616   // lvalue-to-rvalue conversion cannot be applied to function or array types.
617   if (T->isFunctionType() || T->isArrayType())
618     return E;
619 
620   // We don't want to throw lvalue-to-rvalue casts on top of
621   // expressions of certain types in C++.
622   if (getLangOpts().CPlusPlus &&
623       (E->getType() == Context.OverloadTy ||
624        T->isDependentType() ||
625        T->isRecordType()))
626     return E;
627 
628   // The C standard is actually really unclear on this point, and
629   // DR106 tells us what the result should be but not why.  It's
630   // generally best to say that void types just doesn't undergo
631   // lvalue-to-rvalue at all.  Note that expressions of unqualified
632   // 'void' type are never l-values, but qualified void can be.
633   if (T->isVoidType())
634     return E;
635 
636   // OpenCL usually rejects direct accesses to values of 'half' type.
637   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
638       T->isHalfType()) {
639     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
640       << 0 << T;
641     return ExprError();
642   }
643 
644   CheckForNullPointerDereference(*this, E);
645   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
646     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
647                                      &Context.Idents.get("object_getClass"),
648                                      SourceLocation(), LookupOrdinaryName);
649     if (ObjectGetClass)
650       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
651           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
652           << FixItHint::CreateReplacement(
653                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
654     else
655       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
656   }
657   else if (const ObjCIvarRefExpr *OIRE =
658             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
659     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
660 
661   // C++ [conv.lval]p1:
662   //   [...] If T is a non-class type, the type of the prvalue is the
663   //   cv-unqualified version of T. Otherwise, the type of the
664   //   rvalue is T.
665   //
666   // C99 6.3.2.1p2:
667   //   If the lvalue has qualified type, the value has the unqualified
668   //   version of the type of the lvalue; otherwise, the value has the
669   //   type of the lvalue.
670   if (T.hasQualifiers())
671     T = T.getUnqualifiedType();
672 
673   // Under the MS ABI, lock down the inheritance model now.
674   if (T->isMemberPointerType() &&
675       Context.getTargetInfo().getCXXABI().isMicrosoft())
676     (void)isCompleteType(E->getExprLoc(), T);
677 
678   ExprResult Res = CheckLValueToRValueConversionOperand(E);
679   if (Res.isInvalid())
680     return Res;
681   E = Res.get();
682 
683   // Loading a __weak object implicitly retains the value, so we need a cleanup to
684   // balance that.
685   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
686     Cleanup.setExprNeedsCleanups(true);
687 
688   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
689     Cleanup.setExprNeedsCleanups(true);
690 
691   // C++ [conv.lval]p3:
692   //   If T is cv std::nullptr_t, the result is a null pointer constant.
693   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
694   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
695 
696   // C11 6.3.2.1p2:
697   //   ... if the lvalue has atomic type, the value has the non-atomic version
698   //   of the type of the lvalue ...
699   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
700     T = Atomic->getValueType().getUnqualifiedType();
701     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
702                                    nullptr, VK_RValue);
703   }
704 
705   return Res;
706 }
707 
708 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
709   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
710   if (Res.isInvalid())
711     return ExprError();
712   Res = DefaultLvalueConversion(Res.get());
713   if (Res.isInvalid())
714     return ExprError();
715   return Res;
716 }
717 
718 /// CallExprUnaryConversions - a special case of an unary conversion
719 /// performed on a function designator of a call expression.
720 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
721   QualType Ty = E->getType();
722   ExprResult Res = E;
723   // Only do implicit cast for a function type, but not for a pointer
724   // to function type.
725   if (Ty->isFunctionType()) {
726     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
727                             CK_FunctionToPointerDecay);
728     if (Res.isInvalid())
729       return ExprError();
730   }
731   Res = DefaultLvalueConversion(Res.get());
732   if (Res.isInvalid())
733     return ExprError();
734   return Res.get();
735 }
736 
737 /// UsualUnaryConversions - Performs various conversions that are common to most
738 /// operators (C99 6.3). The conversions of array and function types are
739 /// sometimes suppressed. For example, the array->pointer conversion doesn't
740 /// apply if the array is an argument to the sizeof or address (&) operators.
741 /// In these instances, this routine should *not* be called.
742 ExprResult Sema::UsualUnaryConversions(Expr *E) {
743   // First, convert to an r-value.
744   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
745   if (Res.isInvalid())
746     return ExprError();
747   E = Res.get();
748 
749   QualType Ty = E->getType();
750   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
751 
752   // Half FP have to be promoted to float unless it is natively supported
753   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
754     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
755 
756   // Try to perform integral promotions if the object has a theoretically
757   // promotable type.
758   if (Ty->isIntegralOrUnscopedEnumerationType()) {
759     // C99 6.3.1.1p2:
760     //
761     //   The following may be used in an expression wherever an int or
762     //   unsigned int may be used:
763     //     - an object or expression with an integer type whose integer
764     //       conversion rank is less than or equal to the rank of int
765     //       and unsigned int.
766     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
767     //
768     //   If an int can represent all values of the original type, the
769     //   value is converted to an int; otherwise, it is converted to an
770     //   unsigned int. These are called the integer promotions. All
771     //   other types are unchanged by the integer promotions.
772 
773     QualType PTy = Context.isPromotableBitField(E);
774     if (!PTy.isNull()) {
775       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
776       return E;
777     }
778     if (Ty->isPromotableIntegerType()) {
779       QualType PT = Context.getPromotedIntegerType(Ty);
780       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
781       return E;
782     }
783   }
784   return E;
785 }
786 
787 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
788 /// do not have a prototype. Arguments that have type float or __fp16
789 /// are promoted to double. All other argument types are converted by
790 /// UsualUnaryConversions().
791 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
792   QualType Ty = E->getType();
793   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
794 
795   ExprResult Res = UsualUnaryConversions(E);
796   if (Res.isInvalid())
797     return ExprError();
798   E = Res.get();
799 
800   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
801   // promote to double.
802   // Note that default argument promotion applies only to float (and
803   // half/fp16); it does not apply to _Float16.
804   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
805   if (BTy && (BTy->getKind() == BuiltinType::Half ||
806               BTy->getKind() == BuiltinType::Float)) {
807     if (getLangOpts().OpenCL &&
808         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
809         if (BTy->getKind() == BuiltinType::Half) {
810             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
811         }
812     } else {
813       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
814     }
815   }
816 
817   // C++ performs lvalue-to-rvalue conversion as a default argument
818   // promotion, even on class types, but note:
819   //   C++11 [conv.lval]p2:
820   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
821   //     operand or a subexpression thereof the value contained in the
822   //     referenced object is not accessed. Otherwise, if the glvalue
823   //     has a class type, the conversion copy-initializes a temporary
824   //     of type T from the glvalue and the result of the conversion
825   //     is a prvalue for the temporary.
826   // FIXME: add some way to gate this entire thing for correctness in
827   // potentially potentially evaluated contexts.
828   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
829     ExprResult Temp = PerformCopyInitialization(
830                        InitializedEntity::InitializeTemporary(E->getType()),
831                                                 E->getExprLoc(), E);
832     if (Temp.isInvalid())
833       return ExprError();
834     E = Temp.get();
835   }
836 
837   return E;
838 }
839 
840 /// Determine the degree of POD-ness for an expression.
841 /// Incomplete types are considered POD, since this check can be performed
842 /// when we're in an unevaluated context.
843 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
844   if (Ty->isIncompleteType()) {
845     // C++11 [expr.call]p7:
846     //   After these conversions, if the argument does not have arithmetic,
847     //   enumeration, pointer, pointer to member, or class type, the program
848     //   is ill-formed.
849     //
850     // Since we've already performed array-to-pointer and function-to-pointer
851     // decay, the only such type in C++ is cv void. This also handles
852     // initializer lists as variadic arguments.
853     if (Ty->isVoidType())
854       return VAK_Invalid;
855 
856     if (Ty->isObjCObjectType())
857       return VAK_Invalid;
858     return VAK_Valid;
859   }
860 
861   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
862     return VAK_Invalid;
863 
864   if (Ty.isCXX98PODType(Context))
865     return VAK_Valid;
866 
867   // C++11 [expr.call]p7:
868   //   Passing a potentially-evaluated argument of class type (Clause 9)
869   //   having a non-trivial copy constructor, a non-trivial move constructor,
870   //   or a non-trivial destructor, with no corresponding parameter,
871   //   is conditionally-supported with implementation-defined semantics.
872   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
873     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
874       if (!Record->hasNonTrivialCopyConstructor() &&
875           !Record->hasNonTrivialMoveConstructor() &&
876           !Record->hasNonTrivialDestructor())
877         return VAK_ValidInCXX11;
878 
879   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
880     return VAK_Valid;
881 
882   if (Ty->isObjCObjectType())
883     return VAK_Invalid;
884 
885   if (getLangOpts().MSVCCompat)
886     return VAK_MSVCUndefined;
887 
888   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
889   // permitted to reject them. We should consider doing so.
890   return VAK_Undefined;
891 }
892 
893 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
894   // Don't allow one to pass an Objective-C interface to a vararg.
895   const QualType &Ty = E->getType();
896   VarArgKind VAK = isValidVarArgType(Ty);
897 
898   // Complain about passing non-POD types through varargs.
899   switch (VAK) {
900   case VAK_ValidInCXX11:
901     DiagRuntimeBehavior(
902         E->getBeginLoc(), nullptr,
903         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
904     LLVM_FALLTHROUGH;
905   case VAK_Valid:
906     if (Ty->isRecordType()) {
907       // This is unlikely to be what the user intended. If the class has a
908       // 'c_str' member function, the user probably meant to call that.
909       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
910                           PDiag(diag::warn_pass_class_arg_to_vararg)
911                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
912     }
913     break;
914 
915   case VAK_Undefined:
916   case VAK_MSVCUndefined:
917     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
918                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
919                             << getLangOpts().CPlusPlus11 << Ty << CT);
920     break;
921 
922   case VAK_Invalid:
923     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
924       Diag(E->getBeginLoc(),
925            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
926           << Ty << CT;
927     else if (Ty->isObjCObjectType())
928       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
929                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
930                               << Ty << CT);
931     else
932       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
933           << isa<InitListExpr>(E) << Ty << CT;
934     break;
935   }
936 }
937 
938 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
939 /// will create a trap if the resulting type is not a POD type.
940 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
941                                                   FunctionDecl *FDecl) {
942   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
943     // Strip the unbridged-cast placeholder expression off, if applicable.
944     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
945         (CT == VariadicMethod ||
946          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
947       E = stripARCUnbridgedCast(E);
948 
949     // Otherwise, do normal placeholder checking.
950     } else {
951       ExprResult ExprRes = CheckPlaceholderExpr(E);
952       if (ExprRes.isInvalid())
953         return ExprError();
954       E = ExprRes.get();
955     }
956   }
957 
958   ExprResult ExprRes = DefaultArgumentPromotion(E);
959   if (ExprRes.isInvalid())
960     return ExprError();
961   E = ExprRes.get();
962 
963   // Diagnostics regarding non-POD argument types are
964   // emitted along with format string checking in Sema::CheckFunctionCall().
965   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
966     // Turn this into a trap.
967     CXXScopeSpec SS;
968     SourceLocation TemplateKWLoc;
969     UnqualifiedId Name;
970     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
971                        E->getBeginLoc());
972     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
973                                           /*HasTrailingLParen=*/true,
974                                           /*IsAddressOfOperand=*/false);
975     if (TrapFn.isInvalid())
976       return ExprError();
977 
978     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
979                                     None, E->getEndLoc());
980     if (Call.isInvalid())
981       return ExprError();
982 
983     ExprResult Comma =
984         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
985     if (Comma.isInvalid())
986       return ExprError();
987     return Comma.get();
988   }
989 
990   if (!getLangOpts().CPlusPlus &&
991       RequireCompleteType(E->getExprLoc(), E->getType(),
992                           diag::err_call_incomplete_argument))
993     return ExprError();
994 
995   return E;
996 }
997 
998 /// Converts an integer to complex float type.  Helper function of
999 /// UsualArithmeticConversions()
1000 ///
1001 /// \return false if the integer expression is an integer type and is
1002 /// successfully converted to the complex type.
1003 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1004                                                   ExprResult &ComplexExpr,
1005                                                   QualType IntTy,
1006                                                   QualType ComplexTy,
1007                                                   bool SkipCast) {
1008   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1009   if (SkipCast) return false;
1010   if (IntTy->isIntegerType()) {
1011     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1012     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1013     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1014                                   CK_FloatingRealToComplex);
1015   } else {
1016     assert(IntTy->isComplexIntegerType());
1017     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1018                                   CK_IntegralComplexToFloatingComplex);
1019   }
1020   return false;
1021 }
1022 
1023 /// Handle arithmetic conversion with complex types.  Helper function of
1024 /// UsualArithmeticConversions()
1025 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1026                                              ExprResult &RHS, QualType LHSType,
1027                                              QualType RHSType,
1028                                              bool IsCompAssign) {
1029   // if we have an integer operand, the result is the complex type.
1030   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1031                                              /*skipCast*/false))
1032     return LHSType;
1033   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1034                                              /*skipCast*/IsCompAssign))
1035     return RHSType;
1036 
1037   // This handles complex/complex, complex/float, or float/complex.
1038   // When both operands are complex, the shorter operand is converted to the
1039   // type of the longer, and that is the type of the result. This corresponds
1040   // to what is done when combining two real floating-point operands.
1041   // The fun begins when size promotion occur across type domains.
1042   // From H&S 6.3.4: When one operand is complex and the other is a real
1043   // floating-point type, the less precise type is converted, within it's
1044   // real or complex domain, to the precision of the other type. For example,
1045   // when combining a "long double" with a "double _Complex", the
1046   // "double _Complex" is promoted to "long double _Complex".
1047 
1048   // Compute the rank of the two types, regardless of whether they are complex.
1049   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1050 
1051   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1052   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1053   QualType LHSElementType =
1054       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1055   QualType RHSElementType =
1056       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1057 
1058   QualType ResultType = S.Context.getComplexType(LHSElementType);
1059   if (Order < 0) {
1060     // Promote the precision of the LHS if not an assignment.
1061     ResultType = S.Context.getComplexType(RHSElementType);
1062     if (!IsCompAssign) {
1063       if (LHSComplexType)
1064         LHS =
1065             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1066       else
1067         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1068     }
1069   } else if (Order > 0) {
1070     // Promote the precision of the RHS.
1071     if (RHSComplexType)
1072       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1073     else
1074       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1075   }
1076   return ResultType;
1077 }
1078 
1079 /// Handle arithmetic conversion from integer to float.  Helper function
1080 /// of UsualArithmeticConversions()
1081 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1082                                            ExprResult &IntExpr,
1083                                            QualType FloatTy, QualType IntTy,
1084                                            bool ConvertFloat, bool ConvertInt) {
1085   if (IntTy->isIntegerType()) {
1086     if (ConvertInt)
1087       // Convert intExpr to the lhs floating point type.
1088       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1089                                     CK_IntegralToFloating);
1090     return FloatTy;
1091   }
1092 
1093   // Convert both sides to the appropriate complex float.
1094   assert(IntTy->isComplexIntegerType());
1095   QualType result = S.Context.getComplexType(FloatTy);
1096 
1097   // _Complex int -> _Complex float
1098   if (ConvertInt)
1099     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1100                                   CK_IntegralComplexToFloatingComplex);
1101 
1102   // float -> _Complex float
1103   if (ConvertFloat)
1104     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1105                                     CK_FloatingRealToComplex);
1106 
1107   return result;
1108 }
1109 
1110 /// Handle arithmethic conversion with floating point types.  Helper
1111 /// function of UsualArithmeticConversions()
1112 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1113                                       ExprResult &RHS, QualType LHSType,
1114                                       QualType RHSType, bool IsCompAssign) {
1115   bool LHSFloat = LHSType->isRealFloatingType();
1116   bool RHSFloat = RHSType->isRealFloatingType();
1117 
1118   // If we have two real floating types, convert the smaller operand
1119   // to the bigger result.
1120   if (LHSFloat && RHSFloat) {
1121     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1122     if (order > 0) {
1123       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1124       return LHSType;
1125     }
1126 
1127     assert(order < 0 && "illegal float comparison");
1128     if (!IsCompAssign)
1129       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1130     return RHSType;
1131   }
1132 
1133   if (LHSFloat) {
1134     // Half FP has to be promoted to float unless it is natively supported
1135     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1136       LHSType = S.Context.FloatTy;
1137 
1138     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1139                                       /*ConvertFloat=*/!IsCompAssign,
1140                                       /*ConvertInt=*/ true);
1141   }
1142   assert(RHSFloat);
1143   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1144                                     /*convertInt=*/ true,
1145                                     /*convertFloat=*/!IsCompAssign);
1146 }
1147 
1148 /// Diagnose attempts to convert between __float128 and long double if
1149 /// there is no support for such conversion. Helper function of
1150 /// UsualArithmeticConversions().
1151 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1152                                       QualType RHSType) {
1153   /*  No issue converting if at least one of the types is not a floating point
1154       type or the two types have the same rank.
1155   */
1156   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1157       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1158     return false;
1159 
1160   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1161          "The remaining types must be floating point types.");
1162 
1163   auto *LHSComplex = LHSType->getAs<ComplexType>();
1164   auto *RHSComplex = RHSType->getAs<ComplexType>();
1165 
1166   QualType LHSElemType = LHSComplex ?
1167     LHSComplex->getElementType() : LHSType;
1168   QualType RHSElemType = RHSComplex ?
1169     RHSComplex->getElementType() : RHSType;
1170 
1171   // No issue if the two types have the same representation
1172   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1173       &S.Context.getFloatTypeSemantics(RHSElemType))
1174     return false;
1175 
1176   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1177                                 RHSElemType == S.Context.LongDoubleTy);
1178   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1179                             RHSElemType == S.Context.Float128Ty);
1180 
1181   // We've handled the situation where __float128 and long double have the same
1182   // representation. We allow all conversions for all possible long double types
1183   // except PPC's double double.
1184   return Float128AndLongDouble &&
1185     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1186      &llvm::APFloat::PPCDoubleDouble());
1187 }
1188 
1189 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1190 
1191 namespace {
1192 /// These helper callbacks are placed in an anonymous namespace to
1193 /// permit their use as function template parameters.
1194 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1195   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1196 }
1197 
1198 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1199   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1200                              CK_IntegralComplexCast);
1201 }
1202 }
1203 
1204 /// Handle integer arithmetic conversions.  Helper function of
1205 /// UsualArithmeticConversions()
1206 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1207 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1208                                         ExprResult &RHS, QualType LHSType,
1209                                         QualType RHSType, bool IsCompAssign) {
1210   // The rules for this case are in C99 6.3.1.8
1211   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1212   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1213   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1214   if (LHSSigned == RHSSigned) {
1215     // Same signedness; use the higher-ranked type
1216     if (order >= 0) {
1217       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1218       return LHSType;
1219     } else if (!IsCompAssign)
1220       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1221     return RHSType;
1222   } else if (order != (LHSSigned ? 1 : -1)) {
1223     // The unsigned type has greater than or equal rank to the
1224     // signed type, so use the unsigned type
1225     if (RHSSigned) {
1226       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1227       return LHSType;
1228     } else if (!IsCompAssign)
1229       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1230     return RHSType;
1231   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1232     // The two types are different widths; if we are here, that
1233     // means the signed type is larger than the unsigned type, so
1234     // use the signed type.
1235     if (LHSSigned) {
1236       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1237       return LHSType;
1238     } else if (!IsCompAssign)
1239       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1240     return RHSType;
1241   } else {
1242     // The signed type is higher-ranked than the unsigned type,
1243     // but isn't actually any bigger (like unsigned int and long
1244     // on most 32-bit systems).  Use the unsigned type corresponding
1245     // to the signed type.
1246     QualType result =
1247       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1248     RHS = (*doRHSCast)(S, RHS.get(), result);
1249     if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), result);
1251     return result;
1252   }
1253 }
1254 
1255 /// Handle conversions with GCC complex int extension.  Helper function
1256 /// of UsualArithmeticConversions()
1257 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1258                                            ExprResult &RHS, QualType LHSType,
1259                                            QualType RHSType,
1260                                            bool IsCompAssign) {
1261   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1262   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1263 
1264   if (LHSComplexInt && RHSComplexInt) {
1265     QualType LHSEltType = LHSComplexInt->getElementType();
1266     QualType RHSEltType = RHSComplexInt->getElementType();
1267     QualType ScalarType =
1268       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1269         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1270 
1271     return S.Context.getComplexType(ScalarType);
1272   }
1273 
1274   if (LHSComplexInt) {
1275     QualType LHSEltType = LHSComplexInt->getElementType();
1276     QualType ScalarType =
1277       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1278         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1279     QualType ComplexType = S.Context.getComplexType(ScalarType);
1280     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1281                               CK_IntegralRealToComplex);
1282 
1283     return ComplexType;
1284   }
1285 
1286   assert(RHSComplexInt);
1287 
1288   QualType RHSEltType = RHSComplexInt->getElementType();
1289   QualType ScalarType =
1290     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1291       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1292   QualType ComplexType = S.Context.getComplexType(ScalarType);
1293 
1294   if (!IsCompAssign)
1295     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297   return ComplexType;
1298 }
1299 
1300 /// Return the rank of a given fixed point or integer type. The value itself
1301 /// doesn't matter, but the values must be increasing with proper increasing
1302 /// rank as described in N1169 4.1.1.
1303 static unsigned GetFixedPointRank(QualType Ty) {
1304   const auto *BTy = Ty->getAs<BuiltinType>();
1305   assert(BTy && "Expected a builtin type.");
1306 
1307   switch (BTy->getKind()) {
1308   case BuiltinType::ShortFract:
1309   case BuiltinType::UShortFract:
1310   case BuiltinType::SatShortFract:
1311   case BuiltinType::SatUShortFract:
1312     return 1;
1313   case BuiltinType::Fract:
1314   case BuiltinType::UFract:
1315   case BuiltinType::SatFract:
1316   case BuiltinType::SatUFract:
1317     return 2;
1318   case BuiltinType::LongFract:
1319   case BuiltinType::ULongFract:
1320   case BuiltinType::SatLongFract:
1321   case BuiltinType::SatULongFract:
1322     return 3;
1323   case BuiltinType::ShortAccum:
1324   case BuiltinType::UShortAccum:
1325   case BuiltinType::SatShortAccum:
1326   case BuiltinType::SatUShortAccum:
1327     return 4;
1328   case BuiltinType::Accum:
1329   case BuiltinType::UAccum:
1330   case BuiltinType::SatAccum:
1331   case BuiltinType::SatUAccum:
1332     return 5;
1333   case BuiltinType::LongAccum:
1334   case BuiltinType::ULongAccum:
1335   case BuiltinType::SatLongAccum:
1336   case BuiltinType::SatULongAccum:
1337     return 6;
1338   default:
1339     if (BTy->isInteger())
1340       return 0;
1341     llvm_unreachable("Unexpected fixed point or integer type");
1342   }
1343 }
1344 
1345 /// handleFixedPointConversion - Fixed point operations between fixed
1346 /// point types and integers or other fixed point types do not fall under
1347 /// usual arithmetic conversion since these conversions could result in loss
1348 /// of precsision (N1169 4.1.4). These operations should be calculated with
1349 /// the full precision of their result type (N1169 4.1.6.2.1).
1350 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1351                                            QualType RHSTy) {
1352   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1353          "Expected at least one of the operands to be a fixed point type");
1354   assert((LHSTy->isFixedPointOrIntegerType() ||
1355           RHSTy->isFixedPointOrIntegerType()) &&
1356          "Special fixed point arithmetic operation conversions are only "
1357          "applied to ints or other fixed point types");
1358 
1359   // If one operand has signed fixed-point type and the other operand has
1360   // unsigned fixed-point type, then the unsigned fixed-point operand is
1361   // converted to its corresponding signed fixed-point type and the resulting
1362   // type is the type of the converted operand.
1363   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1364     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1365   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1366     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1367 
1368   // The result type is the type with the highest rank, whereby a fixed-point
1369   // conversion rank is always greater than an integer conversion rank; if the
1370   // type of either of the operands is a saturating fixedpoint type, the result
1371   // type shall be the saturating fixed-point type corresponding to the type
1372   // with the highest rank; the resulting value is converted (taking into
1373   // account rounding and overflow) to the precision of the resulting type.
1374   // Same ranks between signed and unsigned types are resolved earlier, so both
1375   // types are either signed or both unsigned at this point.
1376   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1377   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1378 
1379   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1380 
1381   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1382     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1383 
1384   return ResultTy;
1385 }
1386 
1387 /// Check that the usual arithmetic conversions can be performed on this pair of
1388 /// expressions that might be of enumeration type.
1389 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1390                                            SourceLocation Loc,
1391                                            Sema::ArithConvKind ACK) {
1392   // C++2a [expr.arith.conv]p1:
1393   //   If one operand is of enumeration type and the other operand is of a
1394   //   different enumeration type or a floating-point type, this behavior is
1395   //   deprecated ([depr.arith.conv.enum]).
1396   //
1397   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1398   // Eventually we will presumably reject these cases (in C++23 onwards?).
1399   QualType L = LHS->getType(), R = RHS->getType();
1400   bool LEnum = L->isUnscopedEnumerationType(),
1401        REnum = R->isUnscopedEnumerationType();
1402   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1403   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1404       (REnum && L->isFloatingType())) {
1405     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1406                     ? diag::warn_arith_conv_enum_float_cxx20
1407                     : diag::warn_arith_conv_enum_float)
1408         << LHS->getSourceRange() << RHS->getSourceRange()
1409         << (int)ACK << LEnum << L << R;
1410   } else if (!IsCompAssign && LEnum && REnum &&
1411              !S.Context.hasSameUnqualifiedType(L, R)) {
1412     unsigned DiagID;
1413     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1414         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1415       // If either enumeration type is unnamed, it's less likely that the
1416       // user cares about this, but this situation is still deprecated in
1417       // C++2a. Use a different warning group.
1418       DiagID = S.getLangOpts().CPlusPlus20
1419                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1420                     : diag::warn_arith_conv_mixed_anon_enum_types;
1421     } else if (ACK == Sema::ACK_Conditional) {
1422       // Conditional expressions are separated out because they have
1423       // historically had a different warning flag.
1424       DiagID = S.getLangOpts().CPlusPlus20
1425                    ? diag::warn_conditional_mixed_enum_types_cxx20
1426                    : diag::warn_conditional_mixed_enum_types;
1427     } else if (ACK == Sema::ACK_Comparison) {
1428       // Comparison expressions are separated out because they have
1429       // historically had a different warning flag.
1430       DiagID = S.getLangOpts().CPlusPlus20
1431                    ? diag::warn_comparison_mixed_enum_types_cxx20
1432                    : diag::warn_comparison_mixed_enum_types;
1433     } else {
1434       DiagID = S.getLangOpts().CPlusPlus20
1435                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1436                    : diag::warn_arith_conv_mixed_enum_types;
1437     }
1438     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1439                         << (int)ACK << L << R;
1440   }
1441 }
1442 
1443 /// UsualArithmeticConversions - Performs various conversions that are common to
1444 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1445 /// routine returns the first non-arithmetic type found. The client is
1446 /// responsible for emitting appropriate error diagnostics.
1447 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1448                                           SourceLocation Loc,
1449                                           ArithConvKind ACK) {
1450   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1451 
1452   if (ACK != ACK_CompAssign) {
1453     LHS = UsualUnaryConversions(LHS.get());
1454     if (LHS.isInvalid())
1455       return QualType();
1456   }
1457 
1458   RHS = UsualUnaryConversions(RHS.get());
1459   if (RHS.isInvalid())
1460     return QualType();
1461 
1462   // For conversion purposes, we ignore any qualifiers.
1463   // For example, "const float" and "float" are equivalent.
1464   QualType LHSType =
1465     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1466   QualType RHSType =
1467     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1468 
1469   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1470   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1471     LHSType = AtomicLHS->getValueType();
1472 
1473   // If both types are identical, no conversion is needed.
1474   if (LHSType == RHSType)
1475     return LHSType;
1476 
1477   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1478   // The caller can deal with this (e.g. pointer + int).
1479   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1480     return QualType();
1481 
1482   // Apply unary and bitfield promotions to the LHS's type.
1483   QualType LHSUnpromotedType = LHSType;
1484   if (LHSType->isPromotableIntegerType())
1485     LHSType = Context.getPromotedIntegerType(LHSType);
1486   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1487   if (!LHSBitfieldPromoteTy.isNull())
1488     LHSType = LHSBitfieldPromoteTy;
1489   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1490     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1491 
1492   // If both types are identical, no conversion is needed.
1493   if (LHSType == RHSType)
1494     return LHSType;
1495 
1496   // ExtInt types aren't subject to conversions between them or normal integers,
1497   // so this fails.
1498   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1499     return QualType();
1500 
1501   // At this point, we have two different arithmetic types.
1502 
1503   // Diagnose attempts to convert between __float128 and long double where
1504   // such conversions currently can't be handled.
1505   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1506     return QualType();
1507 
1508   // Handle complex types first (C99 6.3.1.8p1).
1509   if (LHSType->isComplexType() || RHSType->isComplexType())
1510     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1511                                         ACK == ACK_CompAssign);
1512 
1513   // Now handle "real" floating types (i.e. float, double, long double).
1514   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1515     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1516                                  ACK == ACK_CompAssign);
1517 
1518   // Handle GCC complex int extension.
1519   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1520     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1521                                       ACK == ACK_CompAssign);
1522 
1523   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1524     return handleFixedPointConversion(*this, LHSType, RHSType);
1525 
1526   // Finally, we have two differing integer types.
1527   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1528            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1529 }
1530 
1531 //===----------------------------------------------------------------------===//
1532 //  Semantic Analysis for various Expression Types
1533 //===----------------------------------------------------------------------===//
1534 
1535 
1536 ExprResult
1537 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1538                                 SourceLocation DefaultLoc,
1539                                 SourceLocation RParenLoc,
1540                                 Expr *ControllingExpr,
1541                                 ArrayRef<ParsedType> ArgTypes,
1542                                 ArrayRef<Expr *> ArgExprs) {
1543   unsigned NumAssocs = ArgTypes.size();
1544   assert(NumAssocs == ArgExprs.size());
1545 
1546   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1547   for (unsigned i = 0; i < NumAssocs; ++i) {
1548     if (ArgTypes[i])
1549       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1550     else
1551       Types[i] = nullptr;
1552   }
1553 
1554   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1555                                              ControllingExpr,
1556                                              llvm::makeArrayRef(Types, NumAssocs),
1557                                              ArgExprs);
1558   delete [] Types;
1559   return ER;
1560 }
1561 
1562 ExprResult
1563 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1564                                  SourceLocation DefaultLoc,
1565                                  SourceLocation RParenLoc,
1566                                  Expr *ControllingExpr,
1567                                  ArrayRef<TypeSourceInfo *> Types,
1568                                  ArrayRef<Expr *> Exprs) {
1569   unsigned NumAssocs = Types.size();
1570   assert(NumAssocs == Exprs.size());
1571 
1572   // Decay and strip qualifiers for the controlling expression type, and handle
1573   // placeholder type replacement. See committee discussion from WG14 DR423.
1574   {
1575     EnterExpressionEvaluationContext Unevaluated(
1576         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1577     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1578     if (R.isInvalid())
1579       return ExprError();
1580     ControllingExpr = R.get();
1581   }
1582 
1583   // The controlling expression is an unevaluated operand, so side effects are
1584   // likely unintended.
1585   if (!inTemplateInstantiation() &&
1586       ControllingExpr->HasSideEffects(Context, false))
1587     Diag(ControllingExpr->getExprLoc(),
1588          diag::warn_side_effects_unevaluated_context);
1589 
1590   bool TypeErrorFound = false,
1591        IsResultDependent = ControllingExpr->isTypeDependent(),
1592        ContainsUnexpandedParameterPack
1593          = ControllingExpr->containsUnexpandedParameterPack();
1594 
1595   for (unsigned i = 0; i < NumAssocs; ++i) {
1596     if (Exprs[i]->containsUnexpandedParameterPack())
1597       ContainsUnexpandedParameterPack = true;
1598 
1599     if (Types[i]) {
1600       if (Types[i]->getType()->containsUnexpandedParameterPack())
1601         ContainsUnexpandedParameterPack = true;
1602 
1603       if (Types[i]->getType()->isDependentType()) {
1604         IsResultDependent = true;
1605       } else {
1606         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1607         // complete object type other than a variably modified type."
1608         unsigned D = 0;
1609         if (Types[i]->getType()->isIncompleteType())
1610           D = diag::err_assoc_type_incomplete;
1611         else if (!Types[i]->getType()->isObjectType())
1612           D = diag::err_assoc_type_nonobject;
1613         else if (Types[i]->getType()->isVariablyModifiedType())
1614           D = diag::err_assoc_type_variably_modified;
1615 
1616         if (D != 0) {
1617           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1618             << Types[i]->getTypeLoc().getSourceRange()
1619             << Types[i]->getType();
1620           TypeErrorFound = true;
1621         }
1622 
1623         // C11 6.5.1.1p2 "No two generic associations in the same generic
1624         // selection shall specify compatible types."
1625         for (unsigned j = i+1; j < NumAssocs; ++j)
1626           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1627               Context.typesAreCompatible(Types[i]->getType(),
1628                                          Types[j]->getType())) {
1629             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1630                  diag::err_assoc_compatible_types)
1631               << Types[j]->getTypeLoc().getSourceRange()
1632               << Types[j]->getType()
1633               << Types[i]->getType();
1634             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1635                  diag::note_compat_assoc)
1636               << Types[i]->getTypeLoc().getSourceRange()
1637               << Types[i]->getType();
1638             TypeErrorFound = true;
1639           }
1640       }
1641     }
1642   }
1643   if (TypeErrorFound)
1644     return ExprError();
1645 
1646   // If we determined that the generic selection is result-dependent, don't
1647   // try to compute the result expression.
1648   if (IsResultDependent)
1649     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1650                                         Exprs, DefaultLoc, RParenLoc,
1651                                         ContainsUnexpandedParameterPack);
1652 
1653   SmallVector<unsigned, 1> CompatIndices;
1654   unsigned DefaultIndex = -1U;
1655   for (unsigned i = 0; i < NumAssocs; ++i) {
1656     if (!Types[i])
1657       DefaultIndex = i;
1658     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1659                                         Types[i]->getType()))
1660       CompatIndices.push_back(i);
1661   }
1662 
1663   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1664   // type compatible with at most one of the types named in its generic
1665   // association list."
1666   if (CompatIndices.size() > 1) {
1667     // We strip parens here because the controlling expression is typically
1668     // parenthesized in macro definitions.
1669     ControllingExpr = ControllingExpr->IgnoreParens();
1670     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1671         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1672         << (unsigned)CompatIndices.size();
1673     for (unsigned I : CompatIndices) {
1674       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1675            diag::note_compat_assoc)
1676         << Types[I]->getTypeLoc().getSourceRange()
1677         << Types[I]->getType();
1678     }
1679     return ExprError();
1680   }
1681 
1682   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1683   // its controlling expression shall have type compatible with exactly one of
1684   // the types named in its generic association list."
1685   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1686     // We strip parens here because the controlling expression is typically
1687     // parenthesized in macro definitions.
1688     ControllingExpr = ControllingExpr->IgnoreParens();
1689     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1690         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1691     return ExprError();
1692   }
1693 
1694   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1695   // type name that is compatible with the type of the controlling expression,
1696   // then the result expression of the generic selection is the expression
1697   // in that generic association. Otherwise, the result expression of the
1698   // generic selection is the expression in the default generic association."
1699   unsigned ResultIndex =
1700     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1701 
1702   return GenericSelectionExpr::Create(
1703       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1704       ContainsUnexpandedParameterPack, ResultIndex);
1705 }
1706 
1707 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1708 /// location of the token and the offset of the ud-suffix within it.
1709 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1710                                      unsigned Offset) {
1711   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1712                                         S.getLangOpts());
1713 }
1714 
1715 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1716 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1717 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1718                                                  IdentifierInfo *UDSuffix,
1719                                                  SourceLocation UDSuffixLoc,
1720                                                  ArrayRef<Expr*> Args,
1721                                                  SourceLocation LitEndLoc) {
1722   assert(Args.size() <= 2 && "too many arguments for literal operator");
1723 
1724   QualType ArgTy[2];
1725   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1726     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1727     if (ArgTy[ArgIdx]->isArrayType())
1728       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1729   }
1730 
1731   DeclarationName OpName =
1732     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1733   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1734   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1735 
1736   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1737   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1738                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1739                               /*AllowStringTemplate*/ false,
1740                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1741     return ExprError();
1742 
1743   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1744 }
1745 
1746 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1747 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1748 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1749 /// multiple tokens.  However, the common case is that StringToks points to one
1750 /// string.
1751 ///
1752 ExprResult
1753 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1754   assert(!StringToks.empty() && "Must have at least one string!");
1755 
1756   StringLiteralParser Literal(StringToks, PP);
1757   if (Literal.hadError)
1758     return ExprError();
1759 
1760   SmallVector<SourceLocation, 4> StringTokLocs;
1761   for (const Token &Tok : StringToks)
1762     StringTokLocs.push_back(Tok.getLocation());
1763 
1764   QualType CharTy = Context.CharTy;
1765   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1766   if (Literal.isWide()) {
1767     CharTy = Context.getWideCharType();
1768     Kind = StringLiteral::Wide;
1769   } else if (Literal.isUTF8()) {
1770     if (getLangOpts().Char8)
1771       CharTy = Context.Char8Ty;
1772     Kind = StringLiteral::UTF8;
1773   } else if (Literal.isUTF16()) {
1774     CharTy = Context.Char16Ty;
1775     Kind = StringLiteral::UTF16;
1776   } else if (Literal.isUTF32()) {
1777     CharTy = Context.Char32Ty;
1778     Kind = StringLiteral::UTF32;
1779   } else if (Literal.isPascal()) {
1780     CharTy = Context.UnsignedCharTy;
1781   }
1782 
1783   // Warn on initializing an array of char from a u8 string literal; this
1784   // becomes ill-formed in C++2a.
1785   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1786       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1787     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1788 
1789     // Create removals for all 'u8' prefixes in the string literal(s). This
1790     // ensures C++2a compatibility (but may change the program behavior when
1791     // built by non-Clang compilers for which the execution character set is
1792     // not always UTF-8).
1793     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1794     SourceLocation RemovalDiagLoc;
1795     for (const Token &Tok : StringToks) {
1796       if (Tok.getKind() == tok::utf8_string_literal) {
1797         if (RemovalDiagLoc.isInvalid())
1798           RemovalDiagLoc = Tok.getLocation();
1799         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1800             Tok.getLocation(),
1801             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1802                                            getSourceManager(), getLangOpts())));
1803       }
1804     }
1805     Diag(RemovalDiagLoc, RemovalDiag);
1806   }
1807 
1808   QualType StrTy =
1809       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1810 
1811   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1812   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1813                                              Kind, Literal.Pascal, StrTy,
1814                                              &StringTokLocs[0],
1815                                              StringTokLocs.size());
1816   if (Literal.getUDSuffix().empty())
1817     return Lit;
1818 
1819   // We're building a user-defined literal.
1820   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1821   SourceLocation UDSuffixLoc =
1822     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1823                    Literal.getUDSuffixOffset());
1824 
1825   // Make sure we're allowed user-defined literals here.
1826   if (!UDLScope)
1827     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1828 
1829   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1830   //   operator "" X (str, len)
1831   QualType SizeType = Context.getSizeType();
1832 
1833   DeclarationName OpName =
1834     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1835   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1836   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1837 
1838   QualType ArgTy[] = {
1839     Context.getArrayDecayedType(StrTy), SizeType
1840   };
1841 
1842   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1843   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1844                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1845                                 /*AllowStringTemplate*/ true,
1846                                 /*DiagnoseMissing*/ true)) {
1847 
1848   case LOLR_Cooked: {
1849     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1850     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1851                                                     StringTokLocs[0]);
1852     Expr *Args[] = { Lit, LenArg };
1853 
1854     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1855   }
1856 
1857   case LOLR_StringTemplate: {
1858     TemplateArgumentListInfo ExplicitArgs;
1859 
1860     unsigned CharBits = Context.getIntWidth(CharTy);
1861     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1862     llvm::APSInt Value(CharBits, CharIsUnsigned);
1863 
1864     TemplateArgument TypeArg(CharTy);
1865     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1866     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1867 
1868     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1869       Value = Lit->getCodeUnit(I);
1870       TemplateArgument Arg(Context, Value, CharTy);
1871       TemplateArgumentLocInfo ArgInfo;
1872       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1873     }
1874     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1875                                     &ExplicitArgs);
1876   }
1877   case LOLR_Raw:
1878   case LOLR_Template:
1879   case LOLR_ErrorNoDiagnostic:
1880     llvm_unreachable("unexpected literal operator lookup result");
1881   case LOLR_Error:
1882     return ExprError();
1883   }
1884   llvm_unreachable("unexpected literal operator lookup result");
1885 }
1886 
1887 DeclRefExpr *
1888 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1889                        SourceLocation Loc,
1890                        const CXXScopeSpec *SS) {
1891   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1892   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1893 }
1894 
1895 DeclRefExpr *
1896 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1897                        const DeclarationNameInfo &NameInfo,
1898                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1899                        SourceLocation TemplateKWLoc,
1900                        const TemplateArgumentListInfo *TemplateArgs) {
1901   NestedNameSpecifierLoc NNS =
1902       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1903   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1904                           TemplateArgs);
1905 }
1906 
1907 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1908   // A declaration named in an unevaluated operand never constitutes an odr-use.
1909   if (isUnevaluatedContext())
1910     return NOUR_Unevaluated;
1911 
1912   // C++2a [basic.def.odr]p4:
1913   //   A variable x whose name appears as a potentially-evaluated expression e
1914   //   is odr-used by e unless [...] x is a reference that is usable in
1915   //   constant expressions.
1916   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1917     if (VD->getType()->isReferenceType() &&
1918         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1919         VD->isUsableInConstantExpressions(Context))
1920       return NOUR_Constant;
1921   }
1922 
1923   // All remaining non-variable cases constitute an odr-use. For variables, we
1924   // need to wait and see how the expression is used.
1925   return NOUR_None;
1926 }
1927 
1928 /// BuildDeclRefExpr - Build an expression that references a
1929 /// declaration that does not require a closure capture.
1930 DeclRefExpr *
1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1932                        const DeclarationNameInfo &NameInfo,
1933                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1934                        SourceLocation TemplateKWLoc,
1935                        const TemplateArgumentListInfo *TemplateArgs) {
1936   bool RefersToCapturedVariable =
1937       isa<VarDecl>(D) &&
1938       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1939 
1940   DeclRefExpr *E = DeclRefExpr::Create(
1941       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1942       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1943   MarkDeclRefReferenced(E);
1944 
1945   // C++ [except.spec]p17:
1946   //   An exception-specification is considered to be needed when:
1947   //   - in an expression, the function is the unique lookup result or
1948   //     the selected member of a set of overloaded functions.
1949   //
1950   // We delay doing this until after we've built the function reference and
1951   // marked it as used so that:
1952   //  a) if the function is defaulted, we get errors from defining it before /
1953   //     instead of errors from computing its exception specification, and
1954   //  b) if the function is a defaulted comparison, we can use the body we
1955   //     build when defining it as input to the exception specification
1956   //     computation rather than computing a new body.
1957   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1958     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1959       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1960         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1961     }
1962   }
1963 
1964   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1965       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1966       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1967     getCurFunction()->recordUseOfWeak(E);
1968 
1969   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1970   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1971     FD = IFD->getAnonField();
1972   if (FD) {
1973     UnusedPrivateFields.remove(FD);
1974     // Just in case we're building an illegal pointer-to-member.
1975     if (FD->isBitField())
1976       E->setObjectKind(OK_BitField);
1977   }
1978 
1979   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1980   // designates a bit-field.
1981   if (auto *BD = dyn_cast<BindingDecl>(D))
1982     if (auto *BE = BD->getBinding())
1983       E->setObjectKind(BE->getObjectKind());
1984 
1985   return E;
1986 }
1987 
1988 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1989 /// possibly a list of template arguments.
1990 ///
1991 /// If this produces template arguments, it is permitted to call
1992 /// DecomposeTemplateName.
1993 ///
1994 /// This actually loses a lot of source location information for
1995 /// non-standard name kinds; we should consider preserving that in
1996 /// some way.
1997 void
1998 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1999                              TemplateArgumentListInfo &Buffer,
2000                              DeclarationNameInfo &NameInfo,
2001                              const TemplateArgumentListInfo *&TemplateArgs) {
2002   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2003     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2004     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2005 
2006     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2007                                        Id.TemplateId->NumArgs);
2008     translateTemplateArguments(TemplateArgsPtr, Buffer);
2009 
2010     TemplateName TName = Id.TemplateId->Template.get();
2011     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2012     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2013     TemplateArgs = &Buffer;
2014   } else {
2015     NameInfo = GetNameFromUnqualifiedId(Id);
2016     TemplateArgs = nullptr;
2017   }
2018 }
2019 
2020 static void emitEmptyLookupTypoDiagnostic(
2021     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2022     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2023     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2024   DeclContext *Ctx =
2025       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2026   if (!TC) {
2027     // Emit a special diagnostic for failed member lookups.
2028     // FIXME: computing the declaration context might fail here (?)
2029     if (Ctx)
2030       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2031                                                  << SS.getRange();
2032     else
2033       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2034     return;
2035   }
2036 
2037   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2038   bool DroppedSpecifier =
2039       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2040   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2041                         ? diag::note_implicit_param_decl
2042                         : diag::note_previous_decl;
2043   if (!Ctx)
2044     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2045                          SemaRef.PDiag(NoteID));
2046   else
2047     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2048                                  << Typo << Ctx << DroppedSpecifier
2049                                  << SS.getRange(),
2050                          SemaRef.PDiag(NoteID));
2051 }
2052 
2053 /// Diagnose an empty lookup.
2054 ///
2055 /// \return false if new lookup candidates were found
2056 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2057                                CorrectionCandidateCallback &CCC,
2058                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2059                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2060   DeclarationName Name = R.getLookupName();
2061 
2062   unsigned diagnostic = diag::err_undeclared_var_use;
2063   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2064   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2065       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2066       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2067     diagnostic = diag::err_undeclared_use;
2068     diagnostic_suggest = diag::err_undeclared_use_suggest;
2069   }
2070 
2071   // If the original lookup was an unqualified lookup, fake an
2072   // unqualified lookup.  This is useful when (for example) the
2073   // original lookup would not have found something because it was a
2074   // dependent name.
2075   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2076   while (DC) {
2077     if (isa<CXXRecordDecl>(DC)) {
2078       LookupQualifiedName(R, DC);
2079 
2080       if (!R.empty()) {
2081         // Don't give errors about ambiguities in this lookup.
2082         R.suppressDiagnostics();
2083 
2084         // During a default argument instantiation the CurContext points
2085         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2086         // function parameter list, hence add an explicit check.
2087         bool isDefaultArgument =
2088             !CodeSynthesisContexts.empty() &&
2089             CodeSynthesisContexts.back().Kind ==
2090                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2091         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2092         bool isInstance = CurMethod &&
2093                           CurMethod->isInstance() &&
2094                           DC == CurMethod->getParent() && !isDefaultArgument;
2095 
2096         // Give a code modification hint to insert 'this->'.
2097         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2098         // Actually quite difficult!
2099         if (getLangOpts().MSVCCompat)
2100           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2101         if (isInstance) {
2102           Diag(R.getNameLoc(), diagnostic) << Name
2103             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2104           CheckCXXThisCapture(R.getNameLoc());
2105         } else {
2106           Diag(R.getNameLoc(), diagnostic) << Name;
2107         }
2108 
2109         // Do we really want to note all of these?
2110         for (NamedDecl *D : R)
2111           Diag(D->getLocation(), diag::note_dependent_var_use);
2112 
2113         // Return true if we are inside a default argument instantiation
2114         // and the found name refers to an instance member function, otherwise
2115         // the function calling DiagnoseEmptyLookup will try to create an
2116         // implicit member call and this is wrong for default argument.
2117         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2118           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2119           return true;
2120         }
2121 
2122         // Tell the callee to try to recover.
2123         return false;
2124       }
2125 
2126       R.clear();
2127     }
2128 
2129     DC = DC->getLookupParent();
2130   }
2131 
2132   // We didn't find anything, so try to correct for a typo.
2133   TypoCorrection Corrected;
2134   if (S && Out) {
2135     SourceLocation TypoLoc = R.getNameLoc();
2136     assert(!ExplicitTemplateArgs &&
2137            "Diagnosing an empty lookup with explicit template args!");
2138     *Out = CorrectTypoDelayed(
2139         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2140         [=](const TypoCorrection &TC) {
2141           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2142                                         diagnostic, diagnostic_suggest);
2143         },
2144         nullptr, CTK_ErrorRecovery);
2145     if (*Out)
2146       return true;
2147   } else if (S &&
2148              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2149                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2150     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2151     bool DroppedSpecifier =
2152         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2153     R.setLookupName(Corrected.getCorrection());
2154 
2155     bool AcceptableWithRecovery = false;
2156     bool AcceptableWithoutRecovery = false;
2157     NamedDecl *ND = Corrected.getFoundDecl();
2158     if (ND) {
2159       if (Corrected.isOverloaded()) {
2160         OverloadCandidateSet OCS(R.getNameLoc(),
2161                                  OverloadCandidateSet::CSK_Normal);
2162         OverloadCandidateSet::iterator Best;
2163         for (NamedDecl *CD : Corrected) {
2164           if (FunctionTemplateDecl *FTD =
2165                    dyn_cast<FunctionTemplateDecl>(CD))
2166             AddTemplateOverloadCandidate(
2167                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2168                 Args, OCS);
2169           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2170             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2171               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2172                                    Args, OCS);
2173         }
2174         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2175         case OR_Success:
2176           ND = Best->FoundDecl;
2177           Corrected.setCorrectionDecl(ND);
2178           break;
2179         default:
2180           // FIXME: Arbitrarily pick the first declaration for the note.
2181           Corrected.setCorrectionDecl(ND);
2182           break;
2183         }
2184       }
2185       R.addDecl(ND);
2186       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2187         CXXRecordDecl *Record = nullptr;
2188         if (Corrected.getCorrectionSpecifier()) {
2189           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2190           Record = Ty->getAsCXXRecordDecl();
2191         }
2192         if (!Record)
2193           Record = cast<CXXRecordDecl>(
2194               ND->getDeclContext()->getRedeclContext());
2195         R.setNamingClass(Record);
2196       }
2197 
2198       auto *UnderlyingND = ND->getUnderlyingDecl();
2199       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2200                                isa<FunctionTemplateDecl>(UnderlyingND);
2201       // FIXME: If we ended up with a typo for a type name or
2202       // Objective-C class name, we're in trouble because the parser
2203       // is in the wrong place to recover. Suggest the typo
2204       // correction, but don't make it a fix-it since we're not going
2205       // to recover well anyway.
2206       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2207                                   getAsTypeTemplateDecl(UnderlyingND) ||
2208                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2209     } else {
2210       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2211       // because we aren't able to recover.
2212       AcceptableWithoutRecovery = true;
2213     }
2214 
2215     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2216       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2217                             ? diag::note_implicit_param_decl
2218                             : diag::note_previous_decl;
2219       if (SS.isEmpty())
2220         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2221                      PDiag(NoteID), AcceptableWithRecovery);
2222       else
2223         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2224                                   << Name << computeDeclContext(SS, false)
2225                                   << DroppedSpecifier << SS.getRange(),
2226                      PDiag(NoteID), AcceptableWithRecovery);
2227 
2228       // Tell the callee whether to try to recover.
2229       return !AcceptableWithRecovery;
2230     }
2231   }
2232   R.clear();
2233 
2234   // Emit a special diagnostic for failed member lookups.
2235   // FIXME: computing the declaration context might fail here (?)
2236   if (!SS.isEmpty()) {
2237     Diag(R.getNameLoc(), diag::err_no_member)
2238       << Name << computeDeclContext(SS, false)
2239       << SS.getRange();
2240     return true;
2241   }
2242 
2243   // Give up, we can't recover.
2244   Diag(R.getNameLoc(), diagnostic) << Name;
2245   return true;
2246 }
2247 
2248 /// In Microsoft mode, if we are inside a template class whose parent class has
2249 /// dependent base classes, and we can't resolve an unqualified identifier, then
2250 /// assume the identifier is a member of a dependent base class.  We can only
2251 /// recover successfully in static methods, instance methods, and other contexts
2252 /// where 'this' is available.  This doesn't precisely match MSVC's
2253 /// instantiation model, but it's close enough.
2254 static Expr *
2255 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2256                                DeclarationNameInfo &NameInfo,
2257                                SourceLocation TemplateKWLoc,
2258                                const TemplateArgumentListInfo *TemplateArgs) {
2259   // Only try to recover from lookup into dependent bases in static methods or
2260   // contexts where 'this' is available.
2261   QualType ThisType = S.getCurrentThisType();
2262   const CXXRecordDecl *RD = nullptr;
2263   if (!ThisType.isNull())
2264     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2265   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2266     RD = MD->getParent();
2267   if (!RD || !RD->hasAnyDependentBases())
2268     return nullptr;
2269 
2270   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2271   // is available, suggest inserting 'this->' as a fixit.
2272   SourceLocation Loc = NameInfo.getLoc();
2273   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2274   DB << NameInfo.getName() << RD;
2275 
2276   if (!ThisType.isNull()) {
2277     DB << FixItHint::CreateInsertion(Loc, "this->");
2278     return CXXDependentScopeMemberExpr::Create(
2279         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2280         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2281         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2282   }
2283 
2284   // Synthesize a fake NNS that points to the derived class.  This will
2285   // perform name lookup during template instantiation.
2286   CXXScopeSpec SS;
2287   auto *NNS =
2288       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2289   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2290   return DependentScopeDeclRefExpr::Create(
2291       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2292       TemplateArgs);
2293 }
2294 
2295 ExprResult
2296 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2297                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2298                         bool HasTrailingLParen, bool IsAddressOfOperand,
2299                         CorrectionCandidateCallback *CCC,
2300                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2301   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2302          "cannot be direct & operand and have a trailing lparen");
2303   if (SS.isInvalid())
2304     return ExprError();
2305 
2306   TemplateArgumentListInfo TemplateArgsBuffer;
2307 
2308   // Decompose the UnqualifiedId into the following data.
2309   DeclarationNameInfo NameInfo;
2310   const TemplateArgumentListInfo *TemplateArgs;
2311   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2312 
2313   DeclarationName Name = NameInfo.getName();
2314   IdentifierInfo *II = Name.getAsIdentifierInfo();
2315   SourceLocation NameLoc = NameInfo.getLoc();
2316 
2317   if (II && II->isEditorPlaceholder()) {
2318     // FIXME: When typed placeholders are supported we can create a typed
2319     // placeholder expression node.
2320     return ExprError();
2321   }
2322 
2323   // C++ [temp.dep.expr]p3:
2324   //   An id-expression is type-dependent if it contains:
2325   //     -- an identifier that was declared with a dependent type,
2326   //        (note: handled after lookup)
2327   //     -- a template-id that is dependent,
2328   //        (note: handled in BuildTemplateIdExpr)
2329   //     -- a conversion-function-id that specifies a dependent type,
2330   //     -- a nested-name-specifier that contains a class-name that
2331   //        names a dependent type.
2332   // Determine whether this is a member of an unknown specialization;
2333   // we need to handle these differently.
2334   bool DependentID = false;
2335   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2336       Name.getCXXNameType()->isDependentType()) {
2337     DependentID = true;
2338   } else if (SS.isSet()) {
2339     if (DeclContext *DC = computeDeclContext(SS, false)) {
2340       if (RequireCompleteDeclContext(SS, DC))
2341         return ExprError();
2342     } else {
2343       DependentID = true;
2344     }
2345   }
2346 
2347   if (DependentID)
2348     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2349                                       IsAddressOfOperand, TemplateArgs);
2350 
2351   // Perform the required lookup.
2352   LookupResult R(*this, NameInfo,
2353                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2354                      ? LookupObjCImplicitSelfParam
2355                      : LookupOrdinaryName);
2356   if (TemplateKWLoc.isValid() || TemplateArgs) {
2357     // Lookup the template name again to correctly establish the context in
2358     // which it was found. This is really unfortunate as we already did the
2359     // lookup to determine that it was a template name in the first place. If
2360     // this becomes a performance hit, we can work harder to preserve those
2361     // results until we get here but it's likely not worth it.
2362     bool MemberOfUnknownSpecialization;
2363     AssumedTemplateKind AssumedTemplate;
2364     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2365                            MemberOfUnknownSpecialization, TemplateKWLoc,
2366                            &AssumedTemplate))
2367       return ExprError();
2368 
2369     if (MemberOfUnknownSpecialization ||
2370         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2371       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2372                                         IsAddressOfOperand, TemplateArgs);
2373   } else {
2374     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2375     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2376 
2377     // If the result might be in a dependent base class, this is a dependent
2378     // id-expression.
2379     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2380       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2381                                         IsAddressOfOperand, TemplateArgs);
2382 
2383     // If this reference is in an Objective-C method, then we need to do
2384     // some special Objective-C lookup, too.
2385     if (IvarLookupFollowUp) {
2386       ExprResult E(LookupInObjCMethod(R, S, II, true));
2387       if (E.isInvalid())
2388         return ExprError();
2389 
2390       if (Expr *Ex = E.getAs<Expr>())
2391         return Ex;
2392     }
2393   }
2394 
2395   if (R.isAmbiguous())
2396     return ExprError();
2397 
2398   // This could be an implicitly declared function reference (legal in C90,
2399   // extension in C99, forbidden in C++).
2400   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2401     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2402     if (D) R.addDecl(D);
2403   }
2404 
2405   // Determine whether this name might be a candidate for
2406   // argument-dependent lookup.
2407   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2408 
2409   if (R.empty() && !ADL) {
2410     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2411       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2412                                                    TemplateKWLoc, TemplateArgs))
2413         return E;
2414     }
2415 
2416     // Don't diagnose an empty lookup for inline assembly.
2417     if (IsInlineAsmIdentifier)
2418       return ExprError();
2419 
2420     // If this name wasn't predeclared and if this is not a function
2421     // call, diagnose the problem.
2422     TypoExpr *TE = nullptr;
2423     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2424                                                        : nullptr);
2425     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2426     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2427            "Typo correction callback misconfigured");
2428     if (CCC) {
2429       // Make sure the callback knows what the typo being diagnosed is.
2430       CCC->setTypoName(II);
2431       if (SS.isValid())
2432         CCC->setTypoNNS(SS.getScopeRep());
2433     }
2434     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2435     // a template name, but we happen to have always already looked up the name
2436     // before we get here if it must be a template name.
2437     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2438                             None, &TE)) {
2439       if (TE && KeywordReplacement) {
2440         auto &State = getTypoExprState(TE);
2441         auto BestTC = State.Consumer->getNextCorrection();
2442         if (BestTC.isKeyword()) {
2443           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2444           if (State.DiagHandler)
2445             State.DiagHandler(BestTC);
2446           KeywordReplacement->startToken();
2447           KeywordReplacement->setKind(II->getTokenID());
2448           KeywordReplacement->setIdentifierInfo(II);
2449           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2450           // Clean up the state associated with the TypoExpr, since it has
2451           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2452           clearDelayedTypo(TE);
2453           // Signal that a correction to a keyword was performed by returning a
2454           // valid-but-null ExprResult.
2455           return (Expr*)nullptr;
2456         }
2457         State.Consumer->resetCorrectionStream();
2458       }
2459       return TE ? TE : ExprError();
2460     }
2461 
2462     assert(!R.empty() &&
2463            "DiagnoseEmptyLookup returned false but added no results");
2464 
2465     // If we found an Objective-C instance variable, let
2466     // LookupInObjCMethod build the appropriate expression to
2467     // reference the ivar.
2468     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2469       R.clear();
2470       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2471       // In a hopelessly buggy code, Objective-C instance variable
2472       // lookup fails and no expression will be built to reference it.
2473       if (!E.isInvalid() && !E.get())
2474         return ExprError();
2475       return E;
2476     }
2477   }
2478 
2479   // This is guaranteed from this point on.
2480   assert(!R.empty() || ADL);
2481 
2482   // Check whether this might be a C++ implicit instance member access.
2483   // C++ [class.mfct.non-static]p3:
2484   //   When an id-expression that is not part of a class member access
2485   //   syntax and not used to form a pointer to member is used in the
2486   //   body of a non-static member function of class X, if name lookup
2487   //   resolves the name in the id-expression to a non-static non-type
2488   //   member of some class C, the id-expression is transformed into a
2489   //   class member access expression using (*this) as the
2490   //   postfix-expression to the left of the . operator.
2491   //
2492   // But we don't actually need to do this for '&' operands if R
2493   // resolved to a function or overloaded function set, because the
2494   // expression is ill-formed if it actually works out to be a
2495   // non-static member function:
2496   //
2497   // C++ [expr.ref]p4:
2498   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2499   //   [t]he expression can be used only as the left-hand operand of a
2500   //   member function call.
2501   //
2502   // There are other safeguards against such uses, but it's important
2503   // to get this right here so that we don't end up making a
2504   // spuriously dependent expression if we're inside a dependent
2505   // instance method.
2506   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2507     bool MightBeImplicitMember;
2508     if (!IsAddressOfOperand)
2509       MightBeImplicitMember = true;
2510     else if (!SS.isEmpty())
2511       MightBeImplicitMember = false;
2512     else if (R.isOverloadedResult())
2513       MightBeImplicitMember = false;
2514     else if (R.isUnresolvableResult())
2515       MightBeImplicitMember = true;
2516     else
2517       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2518                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2519                               isa<MSPropertyDecl>(R.getFoundDecl());
2520 
2521     if (MightBeImplicitMember)
2522       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2523                                              R, TemplateArgs, S);
2524   }
2525 
2526   if (TemplateArgs || TemplateKWLoc.isValid()) {
2527 
2528     // In C++1y, if this is a variable template id, then check it
2529     // in BuildTemplateIdExpr().
2530     // The single lookup result must be a variable template declaration.
2531     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2532         Id.TemplateId->Kind == TNK_Var_template) {
2533       assert(R.getAsSingle<VarTemplateDecl>() &&
2534              "There should only be one declaration found.");
2535     }
2536 
2537     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2538   }
2539 
2540   return BuildDeclarationNameExpr(SS, R, ADL);
2541 }
2542 
2543 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2544 /// declaration name, generally during template instantiation.
2545 /// There's a large number of things which don't need to be done along
2546 /// this path.
2547 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2548     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2549     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2550   DeclContext *DC = computeDeclContext(SS, false);
2551   if (!DC)
2552     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2553                                      NameInfo, /*TemplateArgs=*/nullptr);
2554 
2555   if (RequireCompleteDeclContext(SS, DC))
2556     return ExprError();
2557 
2558   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2559   LookupQualifiedName(R, DC);
2560 
2561   if (R.isAmbiguous())
2562     return ExprError();
2563 
2564   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2565     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2566                                      NameInfo, /*TemplateArgs=*/nullptr);
2567 
2568   if (R.empty()) {
2569     Diag(NameInfo.getLoc(), diag::err_no_member)
2570       << NameInfo.getName() << DC << SS.getRange();
2571     return ExprError();
2572   }
2573 
2574   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2575     // Diagnose a missing typename if this resolved unambiguously to a type in
2576     // a dependent context.  If we can recover with a type, downgrade this to
2577     // a warning in Microsoft compatibility mode.
2578     unsigned DiagID = diag::err_typename_missing;
2579     if (RecoveryTSI && getLangOpts().MSVCCompat)
2580       DiagID = diag::ext_typename_missing;
2581     SourceLocation Loc = SS.getBeginLoc();
2582     auto D = Diag(Loc, DiagID);
2583     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2584       << SourceRange(Loc, NameInfo.getEndLoc());
2585 
2586     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2587     // context.
2588     if (!RecoveryTSI)
2589       return ExprError();
2590 
2591     // Only issue the fixit if we're prepared to recover.
2592     D << FixItHint::CreateInsertion(Loc, "typename ");
2593 
2594     // Recover by pretending this was an elaborated type.
2595     QualType Ty = Context.getTypeDeclType(TD);
2596     TypeLocBuilder TLB;
2597     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2598 
2599     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2600     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2601     QTL.setElaboratedKeywordLoc(SourceLocation());
2602     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2603 
2604     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2605 
2606     return ExprEmpty();
2607   }
2608 
2609   // Defend against this resolving to an implicit member access. We usually
2610   // won't get here if this might be a legitimate a class member (we end up in
2611   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2612   // a pointer-to-member or in an unevaluated context in C++11.
2613   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2614     return BuildPossibleImplicitMemberExpr(SS,
2615                                            /*TemplateKWLoc=*/SourceLocation(),
2616                                            R, /*TemplateArgs=*/nullptr, S);
2617 
2618   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2619 }
2620 
2621 /// The parser has read a name in, and Sema has detected that we're currently
2622 /// inside an ObjC method. Perform some additional checks and determine if we
2623 /// should form a reference to an ivar.
2624 ///
2625 /// Ideally, most of this would be done by lookup, but there's
2626 /// actually quite a lot of extra work involved.
2627 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2628                                         IdentifierInfo *II) {
2629   SourceLocation Loc = Lookup.getNameLoc();
2630   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2631 
2632   // Check for error condition which is already reported.
2633   if (!CurMethod)
2634     return DeclResult(true);
2635 
2636   // There are two cases to handle here.  1) scoped lookup could have failed,
2637   // in which case we should look for an ivar.  2) scoped lookup could have
2638   // found a decl, but that decl is outside the current instance method (i.e.
2639   // a global variable).  In these two cases, we do a lookup for an ivar with
2640   // this name, if the lookup sucedes, we replace it our current decl.
2641 
2642   // If we're in a class method, we don't normally want to look for
2643   // ivars.  But if we don't find anything else, and there's an
2644   // ivar, that's an error.
2645   bool IsClassMethod = CurMethod->isClassMethod();
2646 
2647   bool LookForIvars;
2648   if (Lookup.empty())
2649     LookForIvars = true;
2650   else if (IsClassMethod)
2651     LookForIvars = false;
2652   else
2653     LookForIvars = (Lookup.isSingleResult() &&
2654                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2655   ObjCInterfaceDecl *IFace = nullptr;
2656   if (LookForIvars) {
2657     IFace = CurMethod->getClassInterface();
2658     ObjCInterfaceDecl *ClassDeclared;
2659     ObjCIvarDecl *IV = nullptr;
2660     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2661       // Diagnose using an ivar in a class method.
2662       if (IsClassMethod) {
2663         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2664         return DeclResult(true);
2665       }
2666 
2667       // Diagnose the use of an ivar outside of the declaring class.
2668       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2669           !declaresSameEntity(ClassDeclared, IFace) &&
2670           !getLangOpts().DebuggerSupport)
2671         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2672 
2673       // Success.
2674       return IV;
2675     }
2676   } else if (CurMethod->isInstanceMethod()) {
2677     // We should warn if a local variable hides an ivar.
2678     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2679       ObjCInterfaceDecl *ClassDeclared;
2680       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2681         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2682             declaresSameEntity(IFace, ClassDeclared))
2683           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2684       }
2685     }
2686   } else if (Lookup.isSingleResult() &&
2687              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2688     // If accessing a stand-alone ivar in a class method, this is an error.
2689     if (const ObjCIvarDecl *IV =
2690             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2691       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2692       return DeclResult(true);
2693     }
2694   }
2695 
2696   // Didn't encounter an error, didn't find an ivar.
2697   return DeclResult(false);
2698 }
2699 
2700 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2701                                   ObjCIvarDecl *IV) {
2702   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2703   assert(CurMethod && CurMethod->isInstanceMethod() &&
2704          "should not reference ivar from this context");
2705 
2706   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2707   assert(IFace && "should not reference ivar from this context");
2708 
2709   // If we're referencing an invalid decl, just return this as a silent
2710   // error node.  The error diagnostic was already emitted on the decl.
2711   if (IV->isInvalidDecl())
2712     return ExprError();
2713 
2714   // Check if referencing a field with __attribute__((deprecated)).
2715   if (DiagnoseUseOfDecl(IV, Loc))
2716     return ExprError();
2717 
2718   // FIXME: This should use a new expr for a direct reference, don't
2719   // turn this into Self->ivar, just return a BareIVarExpr or something.
2720   IdentifierInfo &II = Context.Idents.get("self");
2721   UnqualifiedId SelfName;
2722   SelfName.setIdentifier(&II, SourceLocation());
2723   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2724   CXXScopeSpec SelfScopeSpec;
2725   SourceLocation TemplateKWLoc;
2726   ExprResult SelfExpr =
2727       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2728                         /*HasTrailingLParen=*/false,
2729                         /*IsAddressOfOperand=*/false);
2730   if (SelfExpr.isInvalid())
2731     return ExprError();
2732 
2733   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2734   if (SelfExpr.isInvalid())
2735     return ExprError();
2736 
2737   MarkAnyDeclReferenced(Loc, IV, true);
2738 
2739   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2740   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2741       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2742     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2743 
2744   ObjCIvarRefExpr *Result = new (Context)
2745       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2746                       IV->getLocation(), SelfExpr.get(), true, true);
2747 
2748   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2749     if (!isUnevaluatedContext() &&
2750         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2751       getCurFunction()->recordUseOfWeak(Result);
2752   }
2753   if (getLangOpts().ObjCAutoRefCount)
2754     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2755       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2756 
2757   return Result;
2758 }
2759 
2760 /// The parser has read a name in, and Sema has detected that we're currently
2761 /// inside an ObjC method. Perform some additional checks and determine if we
2762 /// should form a reference to an ivar. If so, build an expression referencing
2763 /// that ivar.
2764 ExprResult
2765 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2766                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2767   // FIXME: Integrate this lookup step into LookupParsedName.
2768   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2769   if (Ivar.isInvalid())
2770     return ExprError();
2771   if (Ivar.isUsable())
2772     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2773                             cast<ObjCIvarDecl>(Ivar.get()));
2774 
2775   if (Lookup.empty() && II && AllowBuiltinCreation)
2776     LookupBuiltin(Lookup);
2777 
2778   // Sentinel value saying that we didn't do anything special.
2779   return ExprResult(false);
2780 }
2781 
2782 /// Cast a base object to a member's actual type.
2783 ///
2784 /// Logically this happens in three phases:
2785 ///
2786 /// * First we cast from the base type to the naming class.
2787 ///   The naming class is the class into which we were looking
2788 ///   when we found the member;  it's the qualifier type if a
2789 ///   qualifier was provided, and otherwise it's the base type.
2790 ///
2791 /// * Next we cast from the naming class to the declaring class.
2792 ///   If the member we found was brought into a class's scope by
2793 ///   a using declaration, this is that class;  otherwise it's
2794 ///   the class declaring the member.
2795 ///
2796 /// * Finally we cast from the declaring class to the "true"
2797 ///   declaring class of the member.  This conversion does not
2798 ///   obey access control.
2799 ExprResult
2800 Sema::PerformObjectMemberConversion(Expr *From,
2801                                     NestedNameSpecifier *Qualifier,
2802                                     NamedDecl *FoundDecl,
2803                                     NamedDecl *Member) {
2804   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2805   if (!RD)
2806     return From;
2807 
2808   QualType DestRecordType;
2809   QualType DestType;
2810   QualType FromRecordType;
2811   QualType FromType = From->getType();
2812   bool PointerConversions = false;
2813   if (isa<FieldDecl>(Member)) {
2814     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2815     auto FromPtrType = FromType->getAs<PointerType>();
2816     DestRecordType = Context.getAddrSpaceQualType(
2817         DestRecordType, FromPtrType
2818                             ? FromType->getPointeeType().getAddressSpace()
2819                             : FromType.getAddressSpace());
2820 
2821     if (FromPtrType) {
2822       DestType = Context.getPointerType(DestRecordType);
2823       FromRecordType = FromPtrType->getPointeeType();
2824       PointerConversions = true;
2825     } else {
2826       DestType = DestRecordType;
2827       FromRecordType = FromType;
2828     }
2829   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2830     if (Method->isStatic())
2831       return From;
2832 
2833     DestType = Method->getThisType();
2834     DestRecordType = DestType->getPointeeType();
2835 
2836     if (FromType->getAs<PointerType>()) {
2837       FromRecordType = FromType->getPointeeType();
2838       PointerConversions = true;
2839     } else {
2840       FromRecordType = FromType;
2841       DestType = DestRecordType;
2842     }
2843 
2844     LangAS FromAS = FromRecordType.getAddressSpace();
2845     LangAS DestAS = DestRecordType.getAddressSpace();
2846     if (FromAS != DestAS) {
2847       QualType FromRecordTypeWithoutAS =
2848           Context.removeAddrSpaceQualType(FromRecordType);
2849       QualType FromTypeWithDestAS =
2850           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2851       if (PointerConversions)
2852         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2853       From = ImpCastExprToType(From, FromTypeWithDestAS,
2854                                CK_AddressSpaceConversion, From->getValueKind())
2855                  .get();
2856     }
2857   } else {
2858     // No conversion necessary.
2859     return From;
2860   }
2861 
2862   if (DestType->isDependentType() || FromType->isDependentType())
2863     return From;
2864 
2865   // If the unqualified types are the same, no conversion is necessary.
2866   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2867     return From;
2868 
2869   SourceRange FromRange = From->getSourceRange();
2870   SourceLocation FromLoc = FromRange.getBegin();
2871 
2872   ExprValueKind VK = From->getValueKind();
2873 
2874   // C++ [class.member.lookup]p8:
2875   //   [...] Ambiguities can often be resolved by qualifying a name with its
2876   //   class name.
2877   //
2878   // If the member was a qualified name and the qualified referred to a
2879   // specific base subobject type, we'll cast to that intermediate type
2880   // first and then to the object in which the member is declared. That allows
2881   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2882   //
2883   //   class Base { public: int x; };
2884   //   class Derived1 : public Base { };
2885   //   class Derived2 : public Base { };
2886   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2887   //
2888   //   void VeryDerived::f() {
2889   //     x = 17; // error: ambiguous base subobjects
2890   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2891   //   }
2892   if (Qualifier && Qualifier->getAsType()) {
2893     QualType QType = QualType(Qualifier->getAsType(), 0);
2894     assert(QType->isRecordType() && "lookup done with non-record type");
2895 
2896     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2897 
2898     // In C++98, the qualifier type doesn't actually have to be a base
2899     // type of the object type, in which case we just ignore it.
2900     // Otherwise build the appropriate casts.
2901     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2902       CXXCastPath BasePath;
2903       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2904                                        FromLoc, FromRange, &BasePath))
2905         return ExprError();
2906 
2907       if (PointerConversions)
2908         QType = Context.getPointerType(QType);
2909       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2910                                VK, &BasePath).get();
2911 
2912       FromType = QType;
2913       FromRecordType = QRecordType;
2914 
2915       // If the qualifier type was the same as the destination type,
2916       // we're done.
2917       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2918         return From;
2919     }
2920   }
2921 
2922   bool IgnoreAccess = false;
2923 
2924   // If we actually found the member through a using declaration, cast
2925   // down to the using declaration's type.
2926   //
2927   // Pointer equality is fine here because only one declaration of a
2928   // class ever has member declarations.
2929   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2930     assert(isa<UsingShadowDecl>(FoundDecl));
2931     QualType URecordType = Context.getTypeDeclType(
2932                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2933 
2934     // We only need to do this if the naming-class to declaring-class
2935     // conversion is non-trivial.
2936     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2937       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2938       CXXCastPath BasePath;
2939       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2940                                        FromLoc, FromRange, &BasePath))
2941         return ExprError();
2942 
2943       QualType UType = URecordType;
2944       if (PointerConversions)
2945         UType = Context.getPointerType(UType);
2946       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2947                                VK, &BasePath).get();
2948       FromType = UType;
2949       FromRecordType = URecordType;
2950     }
2951 
2952     // We don't do access control for the conversion from the
2953     // declaring class to the true declaring class.
2954     IgnoreAccess = true;
2955   }
2956 
2957   CXXCastPath BasePath;
2958   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2959                                    FromLoc, FromRange, &BasePath,
2960                                    IgnoreAccess))
2961     return ExprError();
2962 
2963   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2964                            VK, &BasePath);
2965 }
2966 
2967 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2968                                       const LookupResult &R,
2969                                       bool HasTrailingLParen) {
2970   // Only when used directly as the postfix-expression of a call.
2971   if (!HasTrailingLParen)
2972     return false;
2973 
2974   // Never if a scope specifier was provided.
2975   if (SS.isSet())
2976     return false;
2977 
2978   // Only in C++ or ObjC++.
2979   if (!getLangOpts().CPlusPlus)
2980     return false;
2981 
2982   // Turn off ADL when we find certain kinds of declarations during
2983   // normal lookup:
2984   for (NamedDecl *D : R) {
2985     // C++0x [basic.lookup.argdep]p3:
2986     //     -- a declaration of a class member
2987     // Since using decls preserve this property, we check this on the
2988     // original decl.
2989     if (D->isCXXClassMember())
2990       return false;
2991 
2992     // C++0x [basic.lookup.argdep]p3:
2993     //     -- a block-scope function declaration that is not a
2994     //        using-declaration
2995     // NOTE: we also trigger this for function templates (in fact, we
2996     // don't check the decl type at all, since all other decl types
2997     // turn off ADL anyway).
2998     if (isa<UsingShadowDecl>(D))
2999       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3000     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3001       return false;
3002 
3003     // C++0x [basic.lookup.argdep]p3:
3004     //     -- a declaration that is neither a function or a function
3005     //        template
3006     // And also for builtin functions.
3007     if (isa<FunctionDecl>(D)) {
3008       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3009 
3010       // But also builtin functions.
3011       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3012         return false;
3013     } else if (!isa<FunctionTemplateDecl>(D))
3014       return false;
3015   }
3016 
3017   return true;
3018 }
3019 
3020 
3021 /// Diagnoses obvious problems with the use of the given declaration
3022 /// as an expression.  This is only actually called for lookups that
3023 /// were not overloaded, and it doesn't promise that the declaration
3024 /// will in fact be used.
3025 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3026   if (D->isInvalidDecl())
3027     return true;
3028 
3029   if (isa<TypedefNameDecl>(D)) {
3030     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3031     return true;
3032   }
3033 
3034   if (isa<ObjCInterfaceDecl>(D)) {
3035     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3036     return true;
3037   }
3038 
3039   if (isa<NamespaceDecl>(D)) {
3040     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3041     return true;
3042   }
3043 
3044   return false;
3045 }
3046 
3047 // Certain multiversion types should be treated as overloaded even when there is
3048 // only one result.
3049 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3050   assert(R.isSingleResult() && "Expected only a single result");
3051   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3052   return FD &&
3053          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3054 }
3055 
3056 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3057                                           LookupResult &R, bool NeedsADL,
3058                                           bool AcceptInvalidDecl) {
3059   // If this is a single, fully-resolved result and we don't need ADL,
3060   // just build an ordinary singleton decl ref.
3061   if (!NeedsADL && R.isSingleResult() &&
3062       !R.getAsSingle<FunctionTemplateDecl>() &&
3063       !ShouldLookupResultBeMultiVersionOverload(R))
3064     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3065                                     R.getRepresentativeDecl(), nullptr,
3066                                     AcceptInvalidDecl);
3067 
3068   // We only need to check the declaration if there's exactly one
3069   // result, because in the overloaded case the results can only be
3070   // functions and function templates.
3071   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3072       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3073     return ExprError();
3074 
3075   // Otherwise, just build an unresolved lookup expression.  Suppress
3076   // any lookup-related diagnostics; we'll hash these out later, when
3077   // we've picked a target.
3078   R.suppressDiagnostics();
3079 
3080   UnresolvedLookupExpr *ULE
3081     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3082                                    SS.getWithLocInContext(Context),
3083                                    R.getLookupNameInfo(),
3084                                    NeedsADL, R.isOverloadedResult(),
3085                                    R.begin(), R.end());
3086 
3087   return ULE;
3088 }
3089 
3090 static void
3091 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3092                                    ValueDecl *var, DeclContext *DC);
3093 
3094 /// Complete semantic analysis for a reference to the given declaration.
3095 ExprResult Sema::BuildDeclarationNameExpr(
3096     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3097     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3098     bool AcceptInvalidDecl) {
3099   assert(D && "Cannot refer to a NULL declaration");
3100   assert(!isa<FunctionTemplateDecl>(D) &&
3101          "Cannot refer unambiguously to a function template");
3102 
3103   SourceLocation Loc = NameInfo.getLoc();
3104   if (CheckDeclInExpr(*this, Loc, D))
3105     return ExprError();
3106 
3107   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3108     // Specifically diagnose references to class templates that are missing
3109     // a template argument list.
3110     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3111     return ExprError();
3112   }
3113 
3114   // Make sure that we're referring to a value.
3115   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3116   if (!VD) {
3117     Diag(Loc, diag::err_ref_non_value)
3118       << D << SS.getRange();
3119     Diag(D->getLocation(), diag::note_declared_at);
3120     return ExprError();
3121   }
3122 
3123   // Check whether this declaration can be used. Note that we suppress
3124   // this check when we're going to perform argument-dependent lookup
3125   // on this function name, because this might not be the function
3126   // that overload resolution actually selects.
3127   if (DiagnoseUseOfDecl(VD, Loc))
3128     return ExprError();
3129 
3130   // Only create DeclRefExpr's for valid Decl's.
3131   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3132     return ExprError();
3133 
3134   // Handle members of anonymous structs and unions.  If we got here,
3135   // and the reference is to a class member indirect field, then this
3136   // must be the subject of a pointer-to-member expression.
3137   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3138     if (!indirectField->isCXXClassMember())
3139       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3140                                                       indirectField);
3141 
3142   {
3143     QualType type = VD->getType();
3144     if (type.isNull())
3145       return ExprError();
3146     ExprValueKind valueKind = VK_RValue;
3147 
3148     switch (D->getKind()) {
3149     // Ignore all the non-ValueDecl kinds.
3150 #define ABSTRACT_DECL(kind)
3151 #define VALUE(type, base)
3152 #define DECL(type, base) \
3153     case Decl::type:
3154 #include "clang/AST/DeclNodes.inc"
3155       llvm_unreachable("invalid value decl kind");
3156 
3157     // These shouldn't make it here.
3158     case Decl::ObjCAtDefsField:
3159       llvm_unreachable("forming non-member reference to ivar?");
3160 
3161     // Enum constants are always r-values and never references.
3162     // Unresolved using declarations are dependent.
3163     case Decl::EnumConstant:
3164     case Decl::UnresolvedUsingValue:
3165     case Decl::OMPDeclareReduction:
3166     case Decl::OMPDeclareMapper:
3167       valueKind = VK_RValue;
3168       break;
3169 
3170     // Fields and indirect fields that got here must be for
3171     // pointer-to-member expressions; we just call them l-values for
3172     // internal consistency, because this subexpression doesn't really
3173     // exist in the high-level semantics.
3174     case Decl::Field:
3175     case Decl::IndirectField:
3176     case Decl::ObjCIvar:
3177       assert(getLangOpts().CPlusPlus &&
3178              "building reference to field in C?");
3179 
3180       // These can't have reference type in well-formed programs, but
3181       // for internal consistency we do this anyway.
3182       type = type.getNonReferenceType();
3183       valueKind = VK_LValue;
3184       break;
3185 
3186     // Non-type template parameters are either l-values or r-values
3187     // depending on the type.
3188     case Decl::NonTypeTemplateParm: {
3189       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3190         type = reftype->getPointeeType();
3191         valueKind = VK_LValue; // even if the parameter is an r-value reference
3192         break;
3193       }
3194 
3195       // For non-references, we need to strip qualifiers just in case
3196       // the template parameter was declared as 'const int' or whatever.
3197       valueKind = VK_RValue;
3198       type = type.getUnqualifiedType();
3199       break;
3200     }
3201 
3202     case Decl::Var:
3203     case Decl::VarTemplateSpecialization:
3204     case Decl::VarTemplatePartialSpecialization:
3205     case Decl::Decomposition:
3206     case Decl::OMPCapturedExpr:
3207       // In C, "extern void blah;" is valid and is an r-value.
3208       if (!getLangOpts().CPlusPlus &&
3209           !type.hasQualifiers() &&
3210           type->isVoidType()) {
3211         valueKind = VK_RValue;
3212         break;
3213       }
3214       LLVM_FALLTHROUGH;
3215 
3216     case Decl::ImplicitParam:
3217     case Decl::ParmVar: {
3218       // These are always l-values.
3219       valueKind = VK_LValue;
3220       type = type.getNonReferenceType();
3221 
3222       // FIXME: Does the addition of const really only apply in
3223       // potentially-evaluated contexts? Since the variable isn't actually
3224       // captured in an unevaluated context, it seems that the answer is no.
3225       if (!isUnevaluatedContext()) {
3226         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3227         if (!CapturedType.isNull())
3228           type = CapturedType;
3229       }
3230 
3231       break;
3232     }
3233 
3234     case Decl::Binding: {
3235       // These are always lvalues.
3236       valueKind = VK_LValue;
3237       type = type.getNonReferenceType();
3238       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3239       // decides how that's supposed to work.
3240       auto *BD = cast<BindingDecl>(VD);
3241       if (BD->getDeclContext() != CurContext) {
3242         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3243         if (DD && DD->hasLocalStorage())
3244           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3245       }
3246       break;
3247     }
3248 
3249     case Decl::Function: {
3250       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3251         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3252           type = Context.BuiltinFnTy;
3253           valueKind = VK_RValue;
3254           break;
3255         }
3256       }
3257 
3258       const FunctionType *fty = type->castAs<FunctionType>();
3259 
3260       // If we're referring to a function with an __unknown_anytype
3261       // result type, make the entire expression __unknown_anytype.
3262       if (fty->getReturnType() == Context.UnknownAnyTy) {
3263         type = Context.UnknownAnyTy;
3264         valueKind = VK_RValue;
3265         break;
3266       }
3267 
3268       // Functions are l-values in C++.
3269       if (getLangOpts().CPlusPlus) {
3270         valueKind = VK_LValue;
3271         break;
3272       }
3273 
3274       // C99 DR 316 says that, if a function type comes from a
3275       // function definition (without a prototype), that type is only
3276       // used for checking compatibility. Therefore, when referencing
3277       // the function, we pretend that we don't have the full function
3278       // type.
3279       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3280           isa<FunctionProtoType>(fty))
3281         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3282                                               fty->getExtInfo());
3283 
3284       // Functions are r-values in C.
3285       valueKind = VK_RValue;
3286       break;
3287     }
3288 
3289     case Decl::CXXDeductionGuide:
3290       llvm_unreachable("building reference to deduction guide");
3291 
3292     case Decl::MSProperty:
3293     case Decl::MSGuid:
3294       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3295       // or duplicated between host and device?
3296       valueKind = VK_LValue;
3297       break;
3298 
3299     case Decl::CXXMethod:
3300       // If we're referring to a method with an __unknown_anytype
3301       // result type, make the entire expression __unknown_anytype.
3302       // This should only be possible with a type written directly.
3303       if (const FunctionProtoType *proto
3304             = dyn_cast<FunctionProtoType>(VD->getType()))
3305         if (proto->getReturnType() == Context.UnknownAnyTy) {
3306           type = Context.UnknownAnyTy;
3307           valueKind = VK_RValue;
3308           break;
3309         }
3310 
3311       // C++ methods are l-values if static, r-values if non-static.
3312       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3313         valueKind = VK_LValue;
3314         break;
3315       }
3316       LLVM_FALLTHROUGH;
3317 
3318     case Decl::CXXConversion:
3319     case Decl::CXXDestructor:
3320     case Decl::CXXConstructor:
3321       valueKind = VK_RValue;
3322       break;
3323     }
3324 
3325     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3326                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3327                             TemplateArgs);
3328   }
3329 }
3330 
3331 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3332                                     SmallString<32> &Target) {
3333   Target.resize(CharByteWidth * (Source.size() + 1));
3334   char *ResultPtr = &Target[0];
3335   const llvm::UTF8 *ErrorPtr;
3336   bool success =
3337       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3338   (void)success;
3339   assert(success);
3340   Target.resize(ResultPtr - &Target[0]);
3341 }
3342 
3343 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3344                                      PredefinedExpr::IdentKind IK) {
3345   // Pick the current block, lambda, captured statement or function.
3346   Decl *currentDecl = nullptr;
3347   if (const BlockScopeInfo *BSI = getCurBlock())
3348     currentDecl = BSI->TheDecl;
3349   else if (const LambdaScopeInfo *LSI = getCurLambda())
3350     currentDecl = LSI->CallOperator;
3351   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3352     currentDecl = CSI->TheCapturedDecl;
3353   else
3354     currentDecl = getCurFunctionOrMethodDecl();
3355 
3356   if (!currentDecl) {
3357     Diag(Loc, diag::ext_predef_outside_function);
3358     currentDecl = Context.getTranslationUnitDecl();
3359   }
3360 
3361   QualType ResTy;
3362   StringLiteral *SL = nullptr;
3363   if (cast<DeclContext>(currentDecl)->isDependentContext())
3364     ResTy = Context.DependentTy;
3365   else {
3366     // Pre-defined identifiers are of type char[x], where x is the length of
3367     // the string.
3368     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3369     unsigned Length = Str.length();
3370 
3371     llvm::APInt LengthI(32, Length + 1);
3372     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3373       ResTy =
3374           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3375       SmallString<32> RawChars;
3376       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3377                               Str, RawChars);
3378       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3379                                            ArrayType::Normal,
3380                                            /*IndexTypeQuals*/ 0);
3381       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3382                                  /*Pascal*/ false, ResTy, Loc);
3383     } else {
3384       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3385       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3386                                            ArrayType::Normal,
3387                                            /*IndexTypeQuals*/ 0);
3388       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3389                                  /*Pascal*/ false, ResTy, Loc);
3390     }
3391   }
3392 
3393   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3394 }
3395 
3396 static std::pair<QualType, StringLiteral *>
3397 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3398                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3399   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3400 
3401   if (OpType->isDependentType()) {
3402       Result.first = Context.DependentTy;
3403       return Result;
3404   }
3405 
3406   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3407   llvm::APInt Length(32, Str.length() + 1);
3408   Result.first =
3409       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3410   Result.first = Context.getConstantArrayType(
3411       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3412   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3413                                         /*Pascal*/ false, Result.first, OpLoc);
3414   return Result;
3415 }
3416 
3417 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3418                                        TypeSourceInfo *Operand) {
3419   QualType ResultTy;
3420   StringLiteral *SL;
3421   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3422       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3423 
3424   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3425                                 PredefinedExpr::UniqueStableNameType, SL,
3426                                 Operand);
3427 }
3428 
3429 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3430                                        Expr *E) {
3431   QualType ResultTy;
3432   StringLiteral *SL;
3433   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3434       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3435 
3436   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3437                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3438 }
3439 
3440 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3441                                            SourceLocation L, SourceLocation R,
3442                                            ParsedType Ty) {
3443   TypeSourceInfo *TInfo = nullptr;
3444   QualType T = GetTypeFromParser(Ty, &TInfo);
3445 
3446   if (T.isNull())
3447     return ExprError();
3448   if (!TInfo)
3449     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3450 
3451   return BuildUniqueStableName(OpLoc, TInfo);
3452 }
3453 
3454 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3455                                            SourceLocation L, SourceLocation R,
3456                                            Expr *E) {
3457   return BuildUniqueStableName(OpLoc, E);
3458 }
3459 
3460 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3461   PredefinedExpr::IdentKind IK;
3462 
3463   switch (Kind) {
3464   default: llvm_unreachable("Unknown simple primary expr!");
3465   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3466   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3467   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3468   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3469   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3470   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3471   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3472   }
3473 
3474   return BuildPredefinedExpr(Loc, IK);
3475 }
3476 
3477 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3478   SmallString<16> CharBuffer;
3479   bool Invalid = false;
3480   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3481   if (Invalid)
3482     return ExprError();
3483 
3484   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3485                             PP, Tok.getKind());
3486   if (Literal.hadError())
3487     return ExprError();
3488 
3489   QualType Ty;
3490   if (Literal.isWide())
3491     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3492   else if (Literal.isUTF8() && getLangOpts().Char8)
3493     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3494   else if (Literal.isUTF16())
3495     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3496   else if (Literal.isUTF32())
3497     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3498   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3499     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3500   else
3501     Ty = Context.CharTy;  // 'x' -> char in C++
3502 
3503   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3504   if (Literal.isWide())
3505     Kind = CharacterLiteral::Wide;
3506   else if (Literal.isUTF16())
3507     Kind = CharacterLiteral::UTF16;
3508   else if (Literal.isUTF32())
3509     Kind = CharacterLiteral::UTF32;
3510   else if (Literal.isUTF8())
3511     Kind = CharacterLiteral::UTF8;
3512 
3513   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3514                                              Tok.getLocation());
3515 
3516   if (Literal.getUDSuffix().empty())
3517     return Lit;
3518 
3519   // We're building a user-defined literal.
3520   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3521   SourceLocation UDSuffixLoc =
3522     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3523 
3524   // Make sure we're allowed user-defined literals here.
3525   if (!UDLScope)
3526     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3527 
3528   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3529   //   operator "" X (ch)
3530   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3531                                         Lit, Tok.getLocation());
3532 }
3533 
3534 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3535   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3536   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3537                                 Context.IntTy, Loc);
3538 }
3539 
3540 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3541                                   QualType Ty, SourceLocation Loc) {
3542   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3543 
3544   using llvm::APFloat;
3545   APFloat Val(Format);
3546 
3547   APFloat::opStatus result = Literal.GetFloatValue(Val);
3548 
3549   // Overflow is always an error, but underflow is only an error if
3550   // we underflowed to zero (APFloat reports denormals as underflow).
3551   if ((result & APFloat::opOverflow) ||
3552       ((result & APFloat::opUnderflow) && Val.isZero())) {
3553     unsigned diagnostic;
3554     SmallString<20> buffer;
3555     if (result & APFloat::opOverflow) {
3556       diagnostic = diag::warn_float_overflow;
3557       APFloat::getLargest(Format).toString(buffer);
3558     } else {
3559       diagnostic = diag::warn_float_underflow;
3560       APFloat::getSmallest(Format).toString(buffer);
3561     }
3562 
3563     S.Diag(Loc, diagnostic)
3564       << Ty
3565       << StringRef(buffer.data(), buffer.size());
3566   }
3567 
3568   bool isExact = (result == APFloat::opOK);
3569   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3570 }
3571 
3572 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3573   assert(E && "Invalid expression");
3574 
3575   if (E->isValueDependent())
3576     return false;
3577 
3578   QualType QT = E->getType();
3579   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3580     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3581     return true;
3582   }
3583 
3584   llvm::APSInt ValueAPS;
3585   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3586 
3587   if (R.isInvalid())
3588     return true;
3589 
3590   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3591   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3592     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3593         << ValueAPS.toString(10) << ValueIsPositive;
3594     return true;
3595   }
3596 
3597   return false;
3598 }
3599 
3600 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3601   // Fast path for a single digit (which is quite common).  A single digit
3602   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3603   if (Tok.getLength() == 1) {
3604     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3605     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3606   }
3607 
3608   SmallString<128> SpellingBuffer;
3609   // NumericLiteralParser wants to overread by one character.  Add padding to
3610   // the buffer in case the token is copied to the buffer.  If getSpelling()
3611   // returns a StringRef to the memory buffer, it should have a null char at
3612   // the EOF, so it is also safe.
3613   SpellingBuffer.resize(Tok.getLength() + 1);
3614 
3615   // Get the spelling of the token, which eliminates trigraphs, etc.
3616   bool Invalid = false;
3617   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3618   if (Invalid)
3619     return ExprError();
3620 
3621   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3622   if (Literal.hadError)
3623     return ExprError();
3624 
3625   if (Literal.hasUDSuffix()) {
3626     // We're building a user-defined literal.
3627     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3628     SourceLocation UDSuffixLoc =
3629       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3630 
3631     // Make sure we're allowed user-defined literals here.
3632     if (!UDLScope)
3633       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3634 
3635     QualType CookedTy;
3636     if (Literal.isFloatingLiteral()) {
3637       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3638       // long double, the literal is treated as a call of the form
3639       //   operator "" X (f L)
3640       CookedTy = Context.LongDoubleTy;
3641     } else {
3642       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3643       // unsigned long long, the literal is treated as a call of the form
3644       //   operator "" X (n ULL)
3645       CookedTy = Context.UnsignedLongLongTy;
3646     }
3647 
3648     DeclarationName OpName =
3649       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3650     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3651     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3652 
3653     SourceLocation TokLoc = Tok.getLocation();
3654 
3655     // Perform literal operator lookup to determine if we're building a raw
3656     // literal or a cooked one.
3657     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3658     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3659                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3660                                   /*AllowStringTemplate*/ false,
3661                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3662     case LOLR_ErrorNoDiagnostic:
3663       // Lookup failure for imaginary constants isn't fatal, there's still the
3664       // GNU extension producing _Complex types.
3665       break;
3666     case LOLR_Error:
3667       return ExprError();
3668     case LOLR_Cooked: {
3669       Expr *Lit;
3670       if (Literal.isFloatingLiteral()) {
3671         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3672       } else {
3673         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3674         if (Literal.GetIntegerValue(ResultVal))
3675           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3676               << /* Unsigned */ 1;
3677         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3678                                      Tok.getLocation());
3679       }
3680       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3681     }
3682 
3683     case LOLR_Raw: {
3684       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3685       // literal is treated as a call of the form
3686       //   operator "" X ("n")
3687       unsigned Length = Literal.getUDSuffixOffset();
3688       QualType StrTy = Context.getConstantArrayType(
3689           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3690           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3691       Expr *Lit = StringLiteral::Create(
3692           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3693           /*Pascal*/false, StrTy, &TokLoc, 1);
3694       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3695     }
3696 
3697     case LOLR_Template: {
3698       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3699       // template), L is treated as a call fo the form
3700       //   operator "" X <'c1', 'c2', ... 'ck'>()
3701       // where n is the source character sequence c1 c2 ... ck.
3702       TemplateArgumentListInfo ExplicitArgs;
3703       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3704       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3705       llvm::APSInt Value(CharBits, CharIsUnsigned);
3706       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3707         Value = TokSpelling[I];
3708         TemplateArgument Arg(Context, Value, Context.CharTy);
3709         TemplateArgumentLocInfo ArgInfo;
3710         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3711       }
3712       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3713                                       &ExplicitArgs);
3714     }
3715     case LOLR_StringTemplate:
3716       llvm_unreachable("unexpected literal operator lookup result");
3717     }
3718   }
3719 
3720   Expr *Res;
3721 
3722   if (Literal.isFixedPointLiteral()) {
3723     QualType Ty;
3724 
3725     if (Literal.isAccum) {
3726       if (Literal.isHalf) {
3727         Ty = Context.ShortAccumTy;
3728       } else if (Literal.isLong) {
3729         Ty = Context.LongAccumTy;
3730       } else {
3731         Ty = Context.AccumTy;
3732       }
3733     } else if (Literal.isFract) {
3734       if (Literal.isHalf) {
3735         Ty = Context.ShortFractTy;
3736       } else if (Literal.isLong) {
3737         Ty = Context.LongFractTy;
3738       } else {
3739         Ty = Context.FractTy;
3740       }
3741     }
3742 
3743     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3744 
3745     bool isSigned = !Literal.isUnsigned;
3746     unsigned scale = Context.getFixedPointScale(Ty);
3747     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3748 
3749     llvm::APInt Val(bit_width, 0, isSigned);
3750     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3751     bool ValIsZero = Val.isNullValue() && !Overflowed;
3752 
3753     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3754     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3755       // Clause 6.4.4 - The value of a constant shall be in the range of
3756       // representable values for its type, with exception for constants of a
3757       // fract type with a value of exactly 1; such a constant shall denote
3758       // the maximal value for the type.
3759       --Val;
3760     else if (Val.ugt(MaxVal) || Overflowed)
3761       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3762 
3763     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3764                                               Tok.getLocation(), scale);
3765   } else if (Literal.isFloatingLiteral()) {
3766     QualType Ty;
3767     if (Literal.isHalf){
3768       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3769         Ty = Context.HalfTy;
3770       else {
3771         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3772         return ExprError();
3773       }
3774     } else if (Literal.isFloat)
3775       Ty = Context.FloatTy;
3776     else if (Literal.isLong)
3777       Ty = Context.LongDoubleTy;
3778     else if (Literal.isFloat16)
3779       Ty = Context.Float16Ty;
3780     else if (Literal.isFloat128)
3781       Ty = Context.Float128Ty;
3782     else
3783       Ty = Context.DoubleTy;
3784 
3785     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3786 
3787     if (Ty == Context.DoubleTy) {
3788       if (getLangOpts().SinglePrecisionConstants) {
3789         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3790         if (BTy->getKind() != BuiltinType::Float) {
3791           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3792         }
3793       } else if (getLangOpts().OpenCL &&
3794                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3795         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3796         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3797         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3798       }
3799     }
3800   } else if (!Literal.isIntegerLiteral()) {
3801     return ExprError();
3802   } else {
3803     QualType Ty;
3804 
3805     // 'long long' is a C99 or C++11 feature.
3806     if (!getLangOpts().C99 && Literal.isLongLong) {
3807       if (getLangOpts().CPlusPlus)
3808         Diag(Tok.getLocation(),
3809              getLangOpts().CPlusPlus11 ?
3810              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3811       else
3812         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3813     }
3814 
3815     // Get the value in the widest-possible width.
3816     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3817     llvm::APInt ResultVal(MaxWidth, 0);
3818 
3819     if (Literal.GetIntegerValue(ResultVal)) {
3820       // If this value didn't fit into uintmax_t, error and force to ull.
3821       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3822           << /* Unsigned */ 1;
3823       Ty = Context.UnsignedLongLongTy;
3824       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3825              "long long is not intmax_t?");
3826     } else {
3827       // If this value fits into a ULL, try to figure out what else it fits into
3828       // according to the rules of C99 6.4.4.1p5.
3829 
3830       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3831       // be an unsigned int.
3832       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3833 
3834       // Check from smallest to largest, picking the smallest type we can.
3835       unsigned Width = 0;
3836 
3837       // Microsoft specific integer suffixes are explicitly sized.
3838       if (Literal.MicrosoftInteger) {
3839         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3840           Width = 8;
3841           Ty = Context.CharTy;
3842         } else {
3843           Width = Literal.MicrosoftInteger;
3844           Ty = Context.getIntTypeForBitwidth(Width,
3845                                              /*Signed=*/!Literal.isUnsigned);
3846         }
3847       }
3848 
3849       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3850         // Are int/unsigned possibilities?
3851         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3852 
3853         // Does it fit in a unsigned int?
3854         if (ResultVal.isIntN(IntSize)) {
3855           // Does it fit in a signed int?
3856           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3857             Ty = Context.IntTy;
3858           else if (AllowUnsigned)
3859             Ty = Context.UnsignedIntTy;
3860           Width = IntSize;
3861         }
3862       }
3863 
3864       // Are long/unsigned long possibilities?
3865       if (Ty.isNull() && !Literal.isLongLong) {
3866         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3867 
3868         // Does it fit in a unsigned long?
3869         if (ResultVal.isIntN(LongSize)) {
3870           // Does it fit in a signed long?
3871           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3872             Ty = Context.LongTy;
3873           else if (AllowUnsigned)
3874             Ty = Context.UnsignedLongTy;
3875           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3876           // is compatible.
3877           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3878             const unsigned LongLongSize =
3879                 Context.getTargetInfo().getLongLongWidth();
3880             Diag(Tok.getLocation(),
3881                  getLangOpts().CPlusPlus
3882                      ? Literal.isLong
3883                            ? diag::warn_old_implicitly_unsigned_long_cxx
3884                            : /*C++98 UB*/ diag::
3885                                  ext_old_implicitly_unsigned_long_cxx
3886                      : diag::warn_old_implicitly_unsigned_long)
3887                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3888                                             : /*will be ill-formed*/ 1);
3889             Ty = Context.UnsignedLongTy;
3890           }
3891           Width = LongSize;
3892         }
3893       }
3894 
3895       // Check long long if needed.
3896       if (Ty.isNull()) {
3897         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3898 
3899         // Does it fit in a unsigned long long?
3900         if (ResultVal.isIntN(LongLongSize)) {
3901           // Does it fit in a signed long long?
3902           // To be compatible with MSVC, hex integer literals ending with the
3903           // LL or i64 suffix are always signed in Microsoft mode.
3904           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3905               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3906             Ty = Context.LongLongTy;
3907           else if (AllowUnsigned)
3908             Ty = Context.UnsignedLongLongTy;
3909           Width = LongLongSize;
3910         }
3911       }
3912 
3913       // If we still couldn't decide a type, we probably have something that
3914       // does not fit in a signed long long, but has no U suffix.
3915       if (Ty.isNull()) {
3916         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3917         Ty = Context.UnsignedLongLongTy;
3918         Width = Context.getTargetInfo().getLongLongWidth();
3919       }
3920 
3921       if (ResultVal.getBitWidth() != Width)
3922         ResultVal = ResultVal.trunc(Width);
3923     }
3924     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3925   }
3926 
3927   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3928   if (Literal.isImaginary) {
3929     Res = new (Context) ImaginaryLiteral(Res,
3930                                         Context.getComplexType(Res->getType()));
3931 
3932     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3933   }
3934   return Res;
3935 }
3936 
3937 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3938   assert(E && "ActOnParenExpr() missing expr");
3939   return new (Context) ParenExpr(L, R, E);
3940 }
3941 
3942 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3943                                          SourceLocation Loc,
3944                                          SourceRange ArgRange) {
3945   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3946   // scalar or vector data type argument..."
3947   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3948   // type (C99 6.2.5p18) or void.
3949   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3950     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3951       << T << ArgRange;
3952     return true;
3953   }
3954 
3955   assert((T->isVoidType() || !T->isIncompleteType()) &&
3956          "Scalar types should always be complete");
3957   return false;
3958 }
3959 
3960 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3961                                            SourceLocation Loc,
3962                                            SourceRange ArgRange,
3963                                            UnaryExprOrTypeTrait TraitKind) {
3964   // Invalid types must be hard errors for SFINAE in C++.
3965   if (S.LangOpts.CPlusPlus)
3966     return true;
3967 
3968   // C99 6.5.3.4p1:
3969   if (T->isFunctionType() &&
3970       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3971        TraitKind == UETT_PreferredAlignOf)) {
3972     // sizeof(function)/alignof(function) is allowed as an extension.
3973     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3974         << getTraitSpelling(TraitKind) << ArgRange;
3975     return false;
3976   }
3977 
3978   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3979   // this is an error (OpenCL v1.1 s6.3.k)
3980   if (T->isVoidType()) {
3981     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3982                                         : diag::ext_sizeof_alignof_void_type;
3983     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
3984     return false;
3985   }
3986 
3987   return true;
3988 }
3989 
3990 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3991                                              SourceLocation Loc,
3992                                              SourceRange ArgRange,
3993                                              UnaryExprOrTypeTrait TraitKind) {
3994   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3995   // runtime doesn't allow it.
3996   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3997     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3998       << T << (TraitKind == UETT_SizeOf)
3999       << ArgRange;
4000     return true;
4001   }
4002 
4003   return false;
4004 }
4005 
4006 /// Check whether E is a pointer from a decayed array type (the decayed
4007 /// pointer type is equal to T) and emit a warning if it is.
4008 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4009                                      Expr *E) {
4010   // Don't warn if the operation changed the type.
4011   if (T != E->getType())
4012     return;
4013 
4014   // Now look for array decays.
4015   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4016   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4017     return;
4018 
4019   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4020                                              << ICE->getType()
4021                                              << ICE->getSubExpr()->getType();
4022 }
4023 
4024 /// Check the constraints on expression operands to unary type expression
4025 /// and type traits.
4026 ///
4027 /// Completes any types necessary and validates the constraints on the operand
4028 /// expression. The logic mostly mirrors the type-based overload, but may modify
4029 /// the expression as it completes the type for that expression through template
4030 /// instantiation, etc.
4031 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4032                                             UnaryExprOrTypeTrait ExprKind) {
4033   QualType ExprTy = E->getType();
4034   assert(!ExprTy->isReferenceType());
4035 
4036   bool IsUnevaluatedOperand =
4037       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4038        ExprKind == UETT_PreferredAlignOf);
4039   if (IsUnevaluatedOperand) {
4040     ExprResult Result = CheckUnevaluatedOperand(E);
4041     if (Result.isInvalid())
4042       return true;
4043     E = Result.get();
4044   }
4045 
4046   if (ExprKind == UETT_VecStep)
4047     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4048                                         E->getSourceRange());
4049 
4050   // Whitelist some types as extensions
4051   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4052                                       E->getSourceRange(), ExprKind))
4053     return false;
4054 
4055   // 'alignof' applied to an expression only requires the base element type of
4056   // the expression to be complete. 'sizeof' requires the expression's type to
4057   // be complete (and will attempt to complete it if it's an array of unknown
4058   // bound).
4059   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4060     if (RequireCompleteSizedType(
4061             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4062             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4063             getTraitSpelling(ExprKind), E->getSourceRange()))
4064       return true;
4065   } else {
4066     if (RequireCompleteSizedExprType(
4067             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4068             getTraitSpelling(ExprKind), E->getSourceRange()))
4069       return true;
4070   }
4071 
4072   // Completing the expression's type may have changed it.
4073   ExprTy = E->getType();
4074   assert(!ExprTy->isReferenceType());
4075 
4076   if (ExprTy->isFunctionType()) {
4077     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4078         << getTraitSpelling(ExprKind) << E->getSourceRange();
4079     return true;
4080   }
4081 
4082   // The operand for sizeof and alignof is in an unevaluated expression context,
4083   // so side effects could result in unintended consequences.
4084   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4085       E->HasSideEffects(Context, false))
4086     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4087 
4088   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4089                                        E->getSourceRange(), ExprKind))
4090     return true;
4091 
4092   if (ExprKind == UETT_SizeOf) {
4093     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4094       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4095         QualType OType = PVD->getOriginalType();
4096         QualType Type = PVD->getType();
4097         if (Type->isPointerType() && OType->isArrayType()) {
4098           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4099             << Type << OType;
4100           Diag(PVD->getLocation(), diag::note_declared_at);
4101         }
4102       }
4103     }
4104 
4105     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4106     // decays into a pointer and returns an unintended result. This is most
4107     // likely a typo for "sizeof(array) op x".
4108     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4109       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4110                                BO->getLHS());
4111       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4112                                BO->getRHS());
4113     }
4114   }
4115 
4116   return false;
4117 }
4118 
4119 /// Check the constraints on operands to unary expression and type
4120 /// traits.
4121 ///
4122 /// This will complete any types necessary, and validate the various constraints
4123 /// on those operands.
4124 ///
4125 /// The UsualUnaryConversions() function is *not* called by this routine.
4126 /// C99 6.3.2.1p[2-4] all state:
4127 ///   Except when it is the operand of the sizeof operator ...
4128 ///
4129 /// C++ [expr.sizeof]p4
4130 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4131 ///   standard conversions are not applied to the operand of sizeof.
4132 ///
4133 /// This policy is followed for all of the unary trait expressions.
4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4135                                             SourceLocation OpLoc,
4136                                             SourceRange ExprRange,
4137                                             UnaryExprOrTypeTrait ExprKind) {
4138   if (ExprType->isDependentType())
4139     return false;
4140 
4141   // C++ [expr.sizeof]p2:
4142   //     When applied to a reference or a reference type, the result
4143   //     is the size of the referenced type.
4144   // C++11 [expr.alignof]p3:
4145   //     When alignof is applied to a reference type, the result
4146   //     shall be the alignment of the referenced type.
4147   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4148     ExprType = Ref->getPointeeType();
4149 
4150   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4151   //   When alignof or _Alignof is applied to an array type, the result
4152   //   is the alignment of the element type.
4153   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4154       ExprKind == UETT_OpenMPRequiredSimdAlign)
4155     ExprType = Context.getBaseElementType(ExprType);
4156 
4157   if (ExprKind == UETT_VecStep)
4158     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4159 
4160   // Whitelist some types as extensions
4161   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4162                                       ExprKind))
4163     return false;
4164 
4165   if (RequireCompleteSizedType(
4166           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4167           getTraitSpelling(ExprKind), ExprRange))
4168     return true;
4169 
4170   if (ExprType->isFunctionType()) {
4171     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4172         << getTraitSpelling(ExprKind) << ExprRange;
4173     return true;
4174   }
4175 
4176   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4177                                        ExprKind))
4178     return true;
4179 
4180   return false;
4181 }
4182 
4183 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4184   // Cannot know anything else if the expression is dependent.
4185   if (E->isTypeDependent())
4186     return false;
4187 
4188   if (E->getObjectKind() == OK_BitField) {
4189     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4190        << 1 << E->getSourceRange();
4191     return true;
4192   }
4193 
4194   ValueDecl *D = nullptr;
4195   Expr *Inner = E->IgnoreParens();
4196   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4197     D = DRE->getDecl();
4198   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4199     D = ME->getMemberDecl();
4200   }
4201 
4202   // If it's a field, require the containing struct to have a
4203   // complete definition so that we can compute the layout.
4204   //
4205   // This can happen in C++11 onwards, either by naming the member
4206   // in a way that is not transformed into a member access expression
4207   // (in an unevaluated operand, for instance), or by naming the member
4208   // in a trailing-return-type.
4209   //
4210   // For the record, since __alignof__ on expressions is a GCC
4211   // extension, GCC seems to permit this but always gives the
4212   // nonsensical answer 0.
4213   //
4214   // We don't really need the layout here --- we could instead just
4215   // directly check for all the appropriate alignment-lowing
4216   // attributes --- but that would require duplicating a lot of
4217   // logic that just isn't worth duplicating for such a marginal
4218   // use-case.
4219   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4220     // Fast path this check, since we at least know the record has a
4221     // definition if we can find a member of it.
4222     if (!FD->getParent()->isCompleteDefinition()) {
4223       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4224         << E->getSourceRange();
4225       return true;
4226     }
4227 
4228     // Otherwise, if it's a field, and the field doesn't have
4229     // reference type, then it must have a complete type (or be a
4230     // flexible array member, which we explicitly want to
4231     // white-list anyway), which makes the following checks trivial.
4232     if (!FD->getType()->isReferenceType())
4233       return false;
4234   }
4235 
4236   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4237 }
4238 
4239 bool Sema::CheckVecStepExpr(Expr *E) {
4240   E = E->IgnoreParens();
4241 
4242   // Cannot know anything else if the expression is dependent.
4243   if (E->isTypeDependent())
4244     return false;
4245 
4246   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4247 }
4248 
4249 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4250                                         CapturingScopeInfo *CSI) {
4251   assert(T->isVariablyModifiedType());
4252   assert(CSI != nullptr);
4253 
4254   // We're going to walk down into the type and look for VLA expressions.
4255   do {
4256     const Type *Ty = T.getTypePtr();
4257     switch (Ty->getTypeClass()) {
4258 #define TYPE(Class, Base)
4259 #define ABSTRACT_TYPE(Class, Base)
4260 #define NON_CANONICAL_TYPE(Class, Base)
4261 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4262 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4263 #include "clang/AST/TypeNodes.inc"
4264       T = QualType();
4265       break;
4266     // These types are never variably-modified.
4267     case Type::Builtin:
4268     case Type::Complex:
4269     case Type::Vector:
4270     case Type::ExtVector:
4271     case Type::ConstantMatrix:
4272     case Type::Record:
4273     case Type::Enum:
4274     case Type::Elaborated:
4275     case Type::TemplateSpecialization:
4276     case Type::ObjCObject:
4277     case Type::ObjCInterface:
4278     case Type::ObjCObjectPointer:
4279     case Type::ObjCTypeParam:
4280     case Type::Pipe:
4281     case Type::ExtInt:
4282       llvm_unreachable("type class is never variably-modified!");
4283     case Type::Adjusted:
4284       T = cast<AdjustedType>(Ty)->getOriginalType();
4285       break;
4286     case Type::Decayed:
4287       T = cast<DecayedType>(Ty)->getPointeeType();
4288       break;
4289     case Type::Pointer:
4290       T = cast<PointerType>(Ty)->getPointeeType();
4291       break;
4292     case Type::BlockPointer:
4293       T = cast<BlockPointerType>(Ty)->getPointeeType();
4294       break;
4295     case Type::LValueReference:
4296     case Type::RValueReference:
4297       T = cast<ReferenceType>(Ty)->getPointeeType();
4298       break;
4299     case Type::MemberPointer:
4300       T = cast<MemberPointerType>(Ty)->getPointeeType();
4301       break;
4302     case Type::ConstantArray:
4303     case Type::IncompleteArray:
4304       // Losing element qualification here is fine.
4305       T = cast<ArrayType>(Ty)->getElementType();
4306       break;
4307     case Type::VariableArray: {
4308       // Losing element qualification here is fine.
4309       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4310 
4311       // Unknown size indication requires no size computation.
4312       // Otherwise, evaluate and record it.
4313       auto Size = VAT->getSizeExpr();
4314       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4315           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4316         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4317 
4318       T = VAT->getElementType();
4319       break;
4320     }
4321     case Type::FunctionProto:
4322     case Type::FunctionNoProto:
4323       T = cast<FunctionType>(Ty)->getReturnType();
4324       break;
4325     case Type::Paren:
4326     case Type::TypeOf:
4327     case Type::UnaryTransform:
4328     case Type::Attributed:
4329     case Type::SubstTemplateTypeParm:
4330     case Type::PackExpansion:
4331     case Type::MacroQualified:
4332       // Keep walking after single level desugaring.
4333       T = T.getSingleStepDesugaredType(Context);
4334       break;
4335     case Type::Typedef:
4336       T = cast<TypedefType>(Ty)->desugar();
4337       break;
4338     case Type::Decltype:
4339       T = cast<DecltypeType>(Ty)->desugar();
4340       break;
4341     case Type::Auto:
4342     case Type::DeducedTemplateSpecialization:
4343       T = cast<DeducedType>(Ty)->getDeducedType();
4344       break;
4345     case Type::TypeOfExpr:
4346       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4347       break;
4348     case Type::Atomic:
4349       T = cast<AtomicType>(Ty)->getValueType();
4350       break;
4351     }
4352   } while (!T.isNull() && T->isVariablyModifiedType());
4353 }
4354 
4355 /// Build a sizeof or alignof expression given a type operand.
4356 ExprResult
4357 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4358                                      SourceLocation OpLoc,
4359                                      UnaryExprOrTypeTrait ExprKind,
4360                                      SourceRange R) {
4361   if (!TInfo)
4362     return ExprError();
4363 
4364   QualType T = TInfo->getType();
4365 
4366   if (!T->isDependentType() &&
4367       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4368     return ExprError();
4369 
4370   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4371     if (auto *TT = T->getAs<TypedefType>()) {
4372       for (auto I = FunctionScopes.rbegin(),
4373                 E = std::prev(FunctionScopes.rend());
4374            I != E; ++I) {
4375         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4376         if (CSI == nullptr)
4377           break;
4378         DeclContext *DC = nullptr;
4379         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4380           DC = LSI->CallOperator;
4381         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4382           DC = CRSI->TheCapturedDecl;
4383         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4384           DC = BSI->TheDecl;
4385         if (DC) {
4386           if (DC->containsDecl(TT->getDecl()))
4387             break;
4388           captureVariablyModifiedType(Context, T, CSI);
4389         }
4390       }
4391     }
4392   }
4393 
4394   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4395   return new (Context) UnaryExprOrTypeTraitExpr(
4396       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4397 }
4398 
4399 /// Build a sizeof or alignof expression given an expression
4400 /// operand.
4401 ExprResult
4402 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4403                                      UnaryExprOrTypeTrait ExprKind) {
4404   ExprResult PE = CheckPlaceholderExpr(E);
4405   if (PE.isInvalid())
4406     return ExprError();
4407 
4408   E = PE.get();
4409 
4410   // Verify that the operand is valid.
4411   bool isInvalid = false;
4412   if (E->isTypeDependent()) {
4413     // Delay type-checking for type-dependent expressions.
4414   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4415     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4416   } else if (ExprKind == UETT_VecStep) {
4417     isInvalid = CheckVecStepExpr(E);
4418   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4419       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4420       isInvalid = true;
4421   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4422     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4423     isInvalid = true;
4424   } else {
4425     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4426   }
4427 
4428   if (isInvalid)
4429     return ExprError();
4430 
4431   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4432     PE = TransformToPotentiallyEvaluated(E);
4433     if (PE.isInvalid()) return ExprError();
4434     E = PE.get();
4435   }
4436 
4437   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4438   return new (Context) UnaryExprOrTypeTraitExpr(
4439       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4440 }
4441 
4442 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4443 /// expr and the same for @c alignof and @c __alignof
4444 /// Note that the ArgRange is invalid if isType is false.
4445 ExprResult
4446 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4447                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4448                                     void *TyOrEx, SourceRange ArgRange) {
4449   // If error parsing type, ignore.
4450   if (!TyOrEx) return ExprError();
4451 
4452   if (IsType) {
4453     TypeSourceInfo *TInfo;
4454     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4455     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4456   }
4457 
4458   Expr *ArgEx = (Expr *)TyOrEx;
4459   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4460   return Result;
4461 }
4462 
4463 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4464                                      bool IsReal) {
4465   if (V.get()->isTypeDependent())
4466     return S.Context.DependentTy;
4467 
4468   // _Real and _Imag are only l-values for normal l-values.
4469   if (V.get()->getObjectKind() != OK_Ordinary) {
4470     V = S.DefaultLvalueConversion(V.get());
4471     if (V.isInvalid())
4472       return QualType();
4473   }
4474 
4475   // These operators return the element type of a complex type.
4476   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4477     return CT->getElementType();
4478 
4479   // Otherwise they pass through real integer and floating point types here.
4480   if (V.get()->getType()->isArithmeticType())
4481     return V.get()->getType();
4482 
4483   // Test for placeholders.
4484   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4485   if (PR.isInvalid()) return QualType();
4486   if (PR.get() != V.get()) {
4487     V = PR;
4488     return CheckRealImagOperand(S, V, Loc, IsReal);
4489   }
4490 
4491   // Reject anything else.
4492   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4493     << (IsReal ? "__real" : "__imag");
4494   return QualType();
4495 }
4496 
4497 
4498 
4499 ExprResult
4500 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4501                           tok::TokenKind Kind, Expr *Input) {
4502   UnaryOperatorKind Opc;
4503   switch (Kind) {
4504   default: llvm_unreachable("Unknown unary op!");
4505   case tok::plusplus:   Opc = UO_PostInc; break;
4506   case tok::minusminus: Opc = UO_PostDec; break;
4507   }
4508 
4509   // Since this might is a postfix expression, get rid of ParenListExprs.
4510   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4511   if (Result.isInvalid()) return ExprError();
4512   Input = Result.get();
4513 
4514   return BuildUnaryOp(S, OpLoc, Opc, Input);
4515 }
4516 
4517 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4518 ///
4519 /// \return true on error
4520 static bool checkArithmeticOnObjCPointer(Sema &S,
4521                                          SourceLocation opLoc,
4522                                          Expr *op) {
4523   assert(op->getType()->isObjCObjectPointerType());
4524   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4525       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4526     return false;
4527 
4528   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4529     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4530     << op->getSourceRange();
4531   return true;
4532 }
4533 
4534 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4535   auto *BaseNoParens = Base->IgnoreParens();
4536   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4537     return MSProp->getPropertyDecl()->getType()->isArrayType();
4538   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4539 }
4540 
4541 ExprResult
4542 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4543                               Expr *idx, SourceLocation rbLoc) {
4544   if (base && !base->getType().isNull() &&
4545       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4546     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4547                                     /*Length=*/nullptr, rbLoc);
4548 
4549   // Since this might be a postfix expression, get rid of ParenListExprs.
4550   if (isa<ParenListExpr>(base)) {
4551     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4552     if (result.isInvalid()) return ExprError();
4553     base = result.get();
4554   }
4555 
4556   // Check if base and idx form a MatrixSubscriptExpr.
4557   //
4558   // Helper to check for comma expressions, which are not allowed as indices for
4559   // matrix subscript expressions.
4560   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4561     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4562       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4563           << SourceRange(base->getBeginLoc(), rbLoc);
4564       return true;
4565     }
4566     return false;
4567   };
4568   // The matrix subscript operator ([][])is considered a single operator.
4569   // Separating the index expressions by parenthesis is not allowed.
4570   if (base->getType()->isSpecificPlaceholderType(
4571           BuiltinType::IncompleteMatrixIdx) &&
4572       !isa<MatrixSubscriptExpr>(base)) {
4573     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4574         << SourceRange(base->getBeginLoc(), rbLoc);
4575     return ExprError();
4576   }
4577   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4578   // a new MatrixSubscriptExpr.
4579   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4580   if (matSubscriptE) {
4581     if (CheckAndReportCommaError(idx))
4582       return ExprError();
4583 
4584     assert(matSubscriptE->isIncomplete() &&
4585            "base has to be an incomplete matrix subscript");
4586     return CreateBuiltinMatrixSubscriptExpr(
4587         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4588   }
4589   Expr *matrixBase = base;
4590   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4591   if (!IsMSPropertySubscript) {
4592     ExprResult result = CheckPlaceholderExpr(base);
4593     if (!result.isInvalid())
4594       matrixBase = result.get();
4595   }
4596   if (matrixBase->getType()->isMatrixType()) {
4597     if (CheckAndReportCommaError(idx))
4598       return ExprError();
4599 
4600     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4601   }
4602 
4603   // A comma-expression as the index is deprecated in C++2a onwards.
4604   if (getLangOpts().CPlusPlus20 &&
4605       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4606        (isa<CXXOperatorCallExpr>(idx) &&
4607         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4608     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4609       << SourceRange(base->getBeginLoc(), rbLoc);
4610   }
4611 
4612   // Handle any non-overload placeholder types in the base and index
4613   // expressions.  We can't handle overloads here because the other
4614   // operand might be an overloadable type, in which case the overload
4615   // resolution for the operator overload should get the first crack
4616   // at the overload.
4617   if (base->getType()->isNonOverloadPlaceholderType()) {
4618     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4619     if (!IsMSPropertySubscript) {
4620       ExprResult result = CheckPlaceholderExpr(base);
4621       if (result.isInvalid())
4622         return ExprError();
4623       base = result.get();
4624     }
4625   }
4626   if (idx->getType()->isNonOverloadPlaceholderType()) {
4627     ExprResult result = CheckPlaceholderExpr(idx);
4628     if (result.isInvalid()) return ExprError();
4629     idx = result.get();
4630   }
4631 
4632   // Build an unanalyzed expression if either operand is type-dependent.
4633   if (getLangOpts().CPlusPlus &&
4634       (base->isTypeDependent() || idx->isTypeDependent())) {
4635     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4636                                             VK_LValue, OK_Ordinary, rbLoc);
4637   }
4638 
4639   // MSDN, property (C++)
4640   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4641   // This attribute can also be used in the declaration of an empty array in a
4642   // class or structure definition. For example:
4643   // __declspec(property(get=GetX, put=PutX)) int x[];
4644   // The above statement indicates that x[] can be used with one or more array
4645   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4646   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4647   if (IsMSPropertySubscript) {
4648     // Build MS property subscript expression if base is MS property reference
4649     // or MS property subscript.
4650     return new (Context) MSPropertySubscriptExpr(
4651         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4652   }
4653 
4654   // Use C++ overloaded-operator rules if either operand has record
4655   // type.  The spec says to do this if either type is *overloadable*,
4656   // but enum types can't declare subscript operators or conversion
4657   // operators, so there's nothing interesting for overload resolution
4658   // to do if there aren't any record types involved.
4659   //
4660   // ObjC pointers have their own subscripting logic that is not tied
4661   // to overload resolution and so should not take this path.
4662   if (getLangOpts().CPlusPlus &&
4663       (base->getType()->isRecordType() ||
4664        (!base->getType()->isObjCObjectPointerType() &&
4665         idx->getType()->isRecordType()))) {
4666     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4667   }
4668 
4669   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4670 
4671   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4672     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4673 
4674   return Res;
4675 }
4676 
4677 static bool tryConvertToTy(Sema &S, QualType ElementType, ExprResult *Scalar) {
4678   InitializedEntity Entity =
4679       InitializedEntity::InitializeTemporary(ElementType);
4680   InitializationKind Kind = InitializationKind::CreateCopy(
4681       Scalar->get()->getBeginLoc(), SourceLocation());
4682   Expr *Arg = Scalar->get();
4683   InitializationSequence InitSeq(S, Entity, Kind, Arg);
4684   *Scalar = InitSeq.Perform(S, Entity, Kind, Arg);
4685   return !Scalar->isInvalid();
4686 }
4687 
4688 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4689                                                   Expr *ColumnIdx,
4690                                                   SourceLocation RBLoc) {
4691   ExprResult BaseR = CheckPlaceholderExpr(Base);
4692   if (BaseR.isInvalid())
4693     return BaseR;
4694   Base = BaseR.get();
4695 
4696   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4697   if (RowR.isInvalid())
4698     return RowR;
4699   RowIdx = RowR.get();
4700 
4701   if (!ColumnIdx)
4702     return new (Context) MatrixSubscriptExpr(
4703         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4704 
4705   // Build an unanalyzed expression if any of the operands is type-dependent.
4706   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4707       ColumnIdx->isTypeDependent())
4708     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4709                                              Context.DependentTy, RBLoc);
4710 
4711   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4712   if (ColumnR.isInvalid())
4713     return ColumnR;
4714   ColumnIdx = ColumnR.get();
4715 
4716   // Check that IndexExpr is an integer expression. If it is a constant
4717   // expression, check that it is less than Dim (= the number of elements in the
4718   // corresponding dimension).
4719   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4720                           bool IsColumnIdx) -> Expr * {
4721     if (!IndexExpr->getType()->isIntegerType() &&
4722         !IndexExpr->isTypeDependent()) {
4723       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4724           << IsColumnIdx;
4725       return nullptr;
4726     }
4727 
4728     llvm::APSInt Idx;
4729     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4730         (Idx < 0 || Idx >= Dim)) {
4731       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4732           << IsColumnIdx << Dim;
4733       return nullptr;
4734     }
4735 
4736     ExprResult ConvExpr = IndexExpr;
4737     bool ConversionOk = tryConvertToTy(*this, Context.getSizeType(), &ConvExpr);
4738     assert(ConversionOk &&
4739            "should be able to convert any integer type to size type");
4740     (void)ConversionOk;
4741     return ConvExpr.get();
4742   };
4743 
4744   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4745   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4746   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4747   if (!RowIdx || !ColumnIdx)
4748     return ExprError();
4749 
4750   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4751                                            MTy->getElementType(), RBLoc);
4752 }
4753 
4754 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4755   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4756   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4757 
4758   // For expressions like `&(*s).b`, the base is recorded and what should be
4759   // checked.
4760   const MemberExpr *Member = nullptr;
4761   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4762     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4763 
4764   LastRecord.PossibleDerefs.erase(StrippedExpr);
4765 }
4766 
4767 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4768   QualType ResultTy = E->getType();
4769   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4770 
4771   // Bail if the element is an array since it is not memory access.
4772   if (isa<ArrayType>(ResultTy))
4773     return;
4774 
4775   if (ResultTy->hasAttr(attr::NoDeref)) {
4776     LastRecord.PossibleDerefs.insert(E);
4777     return;
4778   }
4779 
4780   // Check if the base type is a pointer to a member access of a struct
4781   // marked with noderef.
4782   const Expr *Base = E->getBase();
4783   QualType BaseTy = Base->getType();
4784   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4785     // Not a pointer access
4786     return;
4787 
4788   const MemberExpr *Member = nullptr;
4789   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4790          Member->isArrow())
4791     Base = Member->getBase();
4792 
4793   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4794     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4795       LastRecord.PossibleDerefs.insert(E);
4796   }
4797 }
4798 
4799 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4800                                           Expr *LowerBound,
4801                                           SourceLocation ColonLoc, Expr *Length,
4802                                           SourceLocation RBLoc) {
4803   if (Base->getType()->isPlaceholderType() &&
4804       !Base->getType()->isSpecificPlaceholderType(
4805           BuiltinType::OMPArraySection)) {
4806     ExprResult Result = CheckPlaceholderExpr(Base);
4807     if (Result.isInvalid())
4808       return ExprError();
4809     Base = Result.get();
4810   }
4811   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4812     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4813     if (Result.isInvalid())
4814       return ExprError();
4815     Result = DefaultLvalueConversion(Result.get());
4816     if (Result.isInvalid())
4817       return ExprError();
4818     LowerBound = Result.get();
4819   }
4820   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4821     ExprResult Result = CheckPlaceholderExpr(Length);
4822     if (Result.isInvalid())
4823       return ExprError();
4824     Result = DefaultLvalueConversion(Result.get());
4825     if (Result.isInvalid())
4826       return ExprError();
4827     Length = Result.get();
4828   }
4829 
4830   // Build an unanalyzed expression if either operand is type-dependent.
4831   if (Base->isTypeDependent() ||
4832       (LowerBound &&
4833        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4834       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4835     return new (Context)
4836         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4837                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4838   }
4839 
4840   // Perform default conversions.
4841   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4842   QualType ResultTy;
4843   if (OriginalTy->isAnyPointerType()) {
4844     ResultTy = OriginalTy->getPointeeType();
4845   } else if (OriginalTy->isArrayType()) {
4846     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4847   } else {
4848     return ExprError(
4849         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4850         << Base->getSourceRange());
4851   }
4852   // C99 6.5.2.1p1
4853   if (LowerBound) {
4854     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4855                                                       LowerBound);
4856     if (Res.isInvalid())
4857       return ExprError(Diag(LowerBound->getExprLoc(),
4858                             diag::err_omp_typecheck_section_not_integer)
4859                        << 0 << LowerBound->getSourceRange());
4860     LowerBound = Res.get();
4861 
4862     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4863         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4864       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4865           << 0 << LowerBound->getSourceRange();
4866   }
4867   if (Length) {
4868     auto Res =
4869         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4870     if (Res.isInvalid())
4871       return ExprError(Diag(Length->getExprLoc(),
4872                             diag::err_omp_typecheck_section_not_integer)
4873                        << 1 << Length->getSourceRange());
4874     Length = Res.get();
4875 
4876     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4877         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4878       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4879           << 1 << Length->getSourceRange();
4880   }
4881 
4882   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4883   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4884   // type. Note that functions are not objects, and that (in C99 parlance)
4885   // incomplete types are not object types.
4886   if (ResultTy->isFunctionType()) {
4887     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4888         << ResultTy << Base->getSourceRange();
4889     return ExprError();
4890   }
4891 
4892   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4893                           diag::err_omp_section_incomplete_type, Base))
4894     return ExprError();
4895 
4896   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4897     Expr::EvalResult Result;
4898     if (LowerBound->EvaluateAsInt(Result, Context)) {
4899       // OpenMP 4.5, [2.4 Array Sections]
4900       // The array section must be a subset of the original array.
4901       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4902       if (LowerBoundValue.isNegative()) {
4903         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4904             << LowerBound->getSourceRange();
4905         return ExprError();
4906       }
4907     }
4908   }
4909 
4910   if (Length) {
4911     Expr::EvalResult Result;
4912     if (Length->EvaluateAsInt(Result, Context)) {
4913       // OpenMP 4.5, [2.4 Array Sections]
4914       // The length must evaluate to non-negative integers.
4915       llvm::APSInt LengthValue = Result.Val.getInt();
4916       if (LengthValue.isNegative()) {
4917         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4918             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4919             << Length->getSourceRange();
4920         return ExprError();
4921       }
4922     }
4923   } else if (ColonLoc.isValid() &&
4924              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4925                                       !OriginalTy->isVariableArrayType()))) {
4926     // OpenMP 4.5, [2.4 Array Sections]
4927     // When the size of the array dimension is not known, the length must be
4928     // specified explicitly.
4929     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4930         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4931     return ExprError();
4932   }
4933 
4934   if (!Base->getType()->isSpecificPlaceholderType(
4935           BuiltinType::OMPArraySection)) {
4936     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4937     if (Result.isInvalid())
4938       return ExprError();
4939     Base = Result.get();
4940   }
4941   return new (Context)
4942       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4943                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4944 }
4945 
4946 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4947                                           SourceLocation RParenLoc,
4948                                           ArrayRef<Expr *> Dims,
4949                                           ArrayRef<SourceRange> Brackets) {
4950   if (Base->getType()->isPlaceholderType()) {
4951     ExprResult Result = CheckPlaceholderExpr(Base);
4952     if (Result.isInvalid())
4953       return ExprError();
4954     Result = DefaultLvalueConversion(Result.get());
4955     if (Result.isInvalid())
4956       return ExprError();
4957     Base = Result.get();
4958   }
4959   QualType BaseTy = Base->getType();
4960   // Delay analysis of the types/expressions if instantiation/specialization is
4961   // required.
4962   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4963     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4964                                        LParenLoc, RParenLoc, Dims, Brackets);
4965   if (!BaseTy->isPointerType() ||
4966       (!Base->isTypeDependent() &&
4967        BaseTy->getPointeeType()->isIncompleteType()))
4968     return ExprError(Diag(Base->getExprLoc(),
4969                           diag::err_omp_non_pointer_type_array_shaping_base)
4970                      << Base->getSourceRange());
4971 
4972   SmallVector<Expr *, 4> NewDims;
4973   bool ErrorFound = false;
4974   for (Expr *Dim : Dims) {
4975     if (Dim->getType()->isPlaceholderType()) {
4976       ExprResult Result = CheckPlaceholderExpr(Dim);
4977       if (Result.isInvalid()) {
4978         ErrorFound = true;
4979         continue;
4980       }
4981       Result = DefaultLvalueConversion(Result.get());
4982       if (Result.isInvalid()) {
4983         ErrorFound = true;
4984         continue;
4985       }
4986       Dim = Result.get();
4987     }
4988     if (!Dim->isTypeDependent()) {
4989       ExprResult Result =
4990           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4991       if (Result.isInvalid()) {
4992         ErrorFound = true;
4993         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4994             << Dim->getSourceRange();
4995         continue;
4996       }
4997       Dim = Result.get();
4998       Expr::EvalResult EvResult;
4999       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5000         // OpenMP 5.0, [2.1.4 Array Shaping]
5001         // Each si is an integral type expression that must evaluate to a
5002         // positive integer.
5003         llvm::APSInt Value = EvResult.Val.getInt();
5004         if (!Value.isStrictlyPositive()) {
5005           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5006               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5007               << Dim->getSourceRange();
5008           ErrorFound = true;
5009           continue;
5010         }
5011       }
5012     }
5013     NewDims.push_back(Dim);
5014   }
5015   if (ErrorFound)
5016     return ExprError();
5017   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5018                                      LParenLoc, RParenLoc, NewDims, Brackets);
5019 }
5020 
5021 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5022                                       SourceLocation LLoc, SourceLocation RLoc,
5023                                       ArrayRef<OMPIteratorData> Data) {
5024   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5025   bool IsCorrect = true;
5026   for (const OMPIteratorData &D : Data) {
5027     TypeSourceInfo *TInfo = nullptr;
5028     SourceLocation StartLoc;
5029     QualType DeclTy;
5030     if (!D.Type.getAsOpaquePtr()) {
5031       // OpenMP 5.0, 2.1.6 Iterators
5032       // In an iterator-specifier, if the iterator-type is not specified then
5033       // the type of that iterator is of int type.
5034       DeclTy = Context.IntTy;
5035       StartLoc = D.DeclIdentLoc;
5036     } else {
5037       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5038       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5039     }
5040 
5041     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5042                              DeclTy->containsUnexpandedParameterPack() ||
5043                              DeclTy->isInstantiationDependentType();
5044     if (!IsDeclTyDependent) {
5045       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5046         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5047         // The iterator-type must be an integral or pointer type.
5048         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5049             << DeclTy;
5050         IsCorrect = false;
5051         continue;
5052       }
5053       if (DeclTy.isConstant(Context)) {
5054         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5055         // The iterator-type must not be const qualified.
5056         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5057             << DeclTy;
5058         IsCorrect = false;
5059         continue;
5060       }
5061     }
5062 
5063     // Iterator declaration.
5064     assert(D.DeclIdent && "Identifier expected.");
5065     // Always try to create iterator declarator to avoid extra error messages
5066     // about unknown declarations use.
5067     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5068                                D.DeclIdent, DeclTy, TInfo, SC_None);
5069     VD->setImplicit();
5070     if (S) {
5071       // Check for conflicting previous declaration.
5072       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5073       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5074                             ForVisibleRedeclaration);
5075       Previous.suppressDiagnostics();
5076       LookupName(Previous, S);
5077 
5078       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5079                            /*AllowInlineNamespace=*/false);
5080       if (!Previous.empty()) {
5081         NamedDecl *Old = Previous.getRepresentativeDecl();
5082         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5083         Diag(Old->getLocation(), diag::note_previous_definition);
5084       } else {
5085         PushOnScopeChains(VD, S);
5086       }
5087     } else {
5088       CurContext->addDecl(VD);
5089     }
5090     Expr *Begin = D.Range.Begin;
5091     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5092       ExprResult BeginRes =
5093           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5094       Begin = BeginRes.get();
5095     }
5096     Expr *End = D.Range.End;
5097     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5098       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5099       End = EndRes.get();
5100     }
5101     Expr *Step = D.Range.Step;
5102     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5103       if (!Step->getType()->isIntegralType(Context)) {
5104         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5105             << Step << Step->getSourceRange();
5106         IsCorrect = false;
5107         continue;
5108       }
5109       llvm::APSInt Result;
5110       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5111       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5112       // If the step expression of a range-specification equals zero, the
5113       // behavior is unspecified.
5114       if (IsConstant && Result.isNullValue()) {
5115         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5116             << Step << Step->getSourceRange();
5117         IsCorrect = false;
5118         continue;
5119       }
5120     }
5121     if (!Begin || !End || !IsCorrect) {
5122       IsCorrect = false;
5123       continue;
5124     }
5125     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5126     IDElem.IteratorDecl = VD;
5127     IDElem.AssignmentLoc = D.AssignLoc;
5128     IDElem.Range.Begin = Begin;
5129     IDElem.Range.End = End;
5130     IDElem.Range.Step = Step;
5131     IDElem.ColonLoc = D.ColonLoc;
5132     IDElem.SecondColonLoc = D.SecColonLoc;
5133   }
5134   if (!IsCorrect) {
5135     // Invalidate all created iterator declarations if error is found.
5136     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5137       if (Decl *ID = D.IteratorDecl)
5138         ID->setInvalidDecl();
5139     }
5140     return ExprError();
5141   }
5142   SmallVector<OMPIteratorHelperData, 4> Helpers;
5143   if (!CurContext->isDependentContext()) {
5144     // Build number of ityeration for each iteration range.
5145     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5146     // ((Begini-Stepi-1-Endi) / -Stepi);
5147     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5148       // (Endi - Begini)
5149       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5150                                           D.Range.Begin);
5151       if(!Res.isUsable()) {
5152         IsCorrect = false;
5153         continue;
5154       }
5155       ExprResult St, St1;
5156       if (D.Range.Step) {
5157         St = D.Range.Step;
5158         // (Endi - Begini) + Stepi
5159         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5160         if (!Res.isUsable()) {
5161           IsCorrect = false;
5162           continue;
5163         }
5164         // (Endi - Begini) + Stepi - 1
5165         Res =
5166             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5167                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5168         if (!Res.isUsable()) {
5169           IsCorrect = false;
5170           continue;
5171         }
5172         // ((Endi - Begini) + Stepi - 1) / Stepi
5173         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5174         if (!Res.isUsable()) {
5175           IsCorrect = false;
5176           continue;
5177         }
5178         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5179         // (Begini - Endi)
5180         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5181                                              D.Range.Begin, D.Range.End);
5182         if (!Res1.isUsable()) {
5183           IsCorrect = false;
5184           continue;
5185         }
5186         // (Begini - Endi) - Stepi
5187         Res1 =
5188             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5189         if (!Res1.isUsable()) {
5190           IsCorrect = false;
5191           continue;
5192         }
5193         // (Begini - Endi) - Stepi - 1
5194         Res1 =
5195             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5196                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5197         if (!Res1.isUsable()) {
5198           IsCorrect = false;
5199           continue;
5200         }
5201         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5202         Res1 =
5203             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5204         if (!Res1.isUsable()) {
5205           IsCorrect = false;
5206           continue;
5207         }
5208         // Stepi > 0.
5209         ExprResult CmpRes =
5210             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5211                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5212         if (!CmpRes.isUsable()) {
5213           IsCorrect = false;
5214           continue;
5215         }
5216         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5217                                  Res.get(), Res1.get());
5218         if (!Res.isUsable()) {
5219           IsCorrect = false;
5220           continue;
5221         }
5222       }
5223       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5224       if (!Res.isUsable()) {
5225         IsCorrect = false;
5226         continue;
5227       }
5228 
5229       // Build counter update.
5230       // Build counter.
5231       auto *CounterVD =
5232           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5233                           D.IteratorDecl->getBeginLoc(), nullptr,
5234                           Res.get()->getType(), nullptr, SC_None);
5235       CounterVD->setImplicit();
5236       ExprResult RefRes =
5237           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5238                            D.IteratorDecl->getBeginLoc());
5239       // Build counter update.
5240       // I = Begini + counter * Stepi;
5241       ExprResult UpdateRes;
5242       if (D.Range.Step) {
5243         UpdateRes = CreateBuiltinBinOp(
5244             D.AssignmentLoc, BO_Mul,
5245             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5246       } else {
5247         UpdateRes = DefaultLvalueConversion(RefRes.get());
5248       }
5249       if (!UpdateRes.isUsable()) {
5250         IsCorrect = false;
5251         continue;
5252       }
5253       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5254                                      UpdateRes.get());
5255       if (!UpdateRes.isUsable()) {
5256         IsCorrect = false;
5257         continue;
5258       }
5259       ExprResult VDRes =
5260           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5261                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5262                            D.IteratorDecl->getBeginLoc());
5263       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5264                                      UpdateRes.get());
5265       if (!UpdateRes.isUsable()) {
5266         IsCorrect = false;
5267         continue;
5268       }
5269       UpdateRes =
5270           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5271       if (!UpdateRes.isUsable()) {
5272         IsCorrect = false;
5273         continue;
5274       }
5275       ExprResult CounterUpdateRes =
5276           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5277       if (!CounterUpdateRes.isUsable()) {
5278         IsCorrect = false;
5279         continue;
5280       }
5281       CounterUpdateRes =
5282           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5283       if (!CounterUpdateRes.isUsable()) {
5284         IsCorrect = false;
5285         continue;
5286       }
5287       OMPIteratorHelperData &HD = Helpers.emplace_back();
5288       HD.CounterVD = CounterVD;
5289       HD.Upper = Res.get();
5290       HD.Update = UpdateRes.get();
5291       HD.CounterUpdate = CounterUpdateRes.get();
5292     }
5293   } else {
5294     Helpers.assign(ID.size(), {});
5295   }
5296   if (!IsCorrect) {
5297     // Invalidate all created iterator declarations if error is found.
5298     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5299       if (Decl *ID = D.IteratorDecl)
5300         ID->setInvalidDecl();
5301     }
5302     return ExprError();
5303   }
5304   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5305                                  LLoc, RLoc, ID, Helpers);
5306 }
5307 
5308 ExprResult
5309 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5310                                       Expr *Idx, SourceLocation RLoc) {
5311   Expr *LHSExp = Base;
5312   Expr *RHSExp = Idx;
5313 
5314   ExprValueKind VK = VK_LValue;
5315   ExprObjectKind OK = OK_Ordinary;
5316 
5317   // Per C++ core issue 1213, the result is an xvalue if either operand is
5318   // a non-lvalue array, and an lvalue otherwise.
5319   if (getLangOpts().CPlusPlus11) {
5320     for (auto *Op : {LHSExp, RHSExp}) {
5321       Op = Op->IgnoreImplicit();
5322       if (Op->getType()->isArrayType() && !Op->isLValue())
5323         VK = VK_XValue;
5324     }
5325   }
5326 
5327   // Perform default conversions.
5328   if (!LHSExp->getType()->getAs<VectorType>()) {
5329     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5330     if (Result.isInvalid())
5331       return ExprError();
5332     LHSExp = Result.get();
5333   }
5334   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5335   if (Result.isInvalid())
5336     return ExprError();
5337   RHSExp = Result.get();
5338 
5339   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5340 
5341   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5342   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5343   // in the subscript position. As a result, we need to derive the array base
5344   // and index from the expression types.
5345   Expr *BaseExpr, *IndexExpr;
5346   QualType ResultType;
5347   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5348     BaseExpr = LHSExp;
5349     IndexExpr = RHSExp;
5350     ResultType = Context.DependentTy;
5351   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5352     BaseExpr = LHSExp;
5353     IndexExpr = RHSExp;
5354     ResultType = PTy->getPointeeType();
5355   } else if (const ObjCObjectPointerType *PTy =
5356                LHSTy->getAs<ObjCObjectPointerType>()) {
5357     BaseExpr = LHSExp;
5358     IndexExpr = RHSExp;
5359 
5360     // Use custom logic if this should be the pseudo-object subscript
5361     // expression.
5362     if (!LangOpts.isSubscriptPointerArithmetic())
5363       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5364                                           nullptr);
5365 
5366     ResultType = PTy->getPointeeType();
5367   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5368      // Handle the uncommon case of "123[Ptr]".
5369     BaseExpr = RHSExp;
5370     IndexExpr = LHSExp;
5371     ResultType = PTy->getPointeeType();
5372   } else if (const ObjCObjectPointerType *PTy =
5373                RHSTy->getAs<ObjCObjectPointerType>()) {
5374      // Handle the uncommon case of "123[Ptr]".
5375     BaseExpr = RHSExp;
5376     IndexExpr = LHSExp;
5377     ResultType = PTy->getPointeeType();
5378     if (!LangOpts.isSubscriptPointerArithmetic()) {
5379       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5380         << ResultType << BaseExpr->getSourceRange();
5381       return ExprError();
5382     }
5383   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5384     BaseExpr = LHSExp;    // vectors: V[123]
5385     IndexExpr = RHSExp;
5386     // We apply C++ DR1213 to vector subscripting too.
5387     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5388       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5389       if (Materialized.isInvalid())
5390         return ExprError();
5391       LHSExp = Materialized.get();
5392     }
5393     VK = LHSExp->getValueKind();
5394     if (VK != VK_RValue)
5395       OK = OK_VectorComponent;
5396 
5397     ResultType = VTy->getElementType();
5398     QualType BaseType = BaseExpr->getType();
5399     Qualifiers BaseQuals = BaseType.getQualifiers();
5400     Qualifiers MemberQuals = ResultType.getQualifiers();
5401     Qualifiers Combined = BaseQuals + MemberQuals;
5402     if (Combined != MemberQuals)
5403       ResultType = Context.getQualifiedType(ResultType, Combined);
5404   } else if (LHSTy->isArrayType()) {
5405     // If we see an array that wasn't promoted by
5406     // DefaultFunctionArrayLvalueConversion, it must be an array that
5407     // wasn't promoted because of the C90 rule that doesn't
5408     // allow promoting non-lvalue arrays.  Warn, then
5409     // force the promotion here.
5410     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5411         << LHSExp->getSourceRange();
5412     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5413                                CK_ArrayToPointerDecay).get();
5414     LHSTy = LHSExp->getType();
5415 
5416     BaseExpr = LHSExp;
5417     IndexExpr = RHSExp;
5418     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5419   } else if (RHSTy->isArrayType()) {
5420     // Same as previous, except for 123[f().a] case
5421     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5422         << RHSExp->getSourceRange();
5423     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5424                                CK_ArrayToPointerDecay).get();
5425     RHSTy = RHSExp->getType();
5426 
5427     BaseExpr = RHSExp;
5428     IndexExpr = LHSExp;
5429     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5430   } else {
5431     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5432        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5433   }
5434   // C99 6.5.2.1p1
5435   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5436     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5437                      << IndexExpr->getSourceRange());
5438 
5439   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5440        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5441          && !IndexExpr->isTypeDependent())
5442     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5443 
5444   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5445   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5446   // type. Note that Functions are not objects, and that (in C99 parlance)
5447   // incomplete types are not object types.
5448   if (ResultType->isFunctionType()) {
5449     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5450         << ResultType << BaseExpr->getSourceRange();
5451     return ExprError();
5452   }
5453 
5454   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5455     // GNU extension: subscripting on pointer to void
5456     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5457       << BaseExpr->getSourceRange();
5458 
5459     // C forbids expressions of unqualified void type from being l-values.
5460     // See IsCForbiddenLValueType.
5461     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5462   } else if (!ResultType->isDependentType() &&
5463              RequireCompleteSizedType(
5464                  LLoc, ResultType,
5465                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5466     return ExprError();
5467 
5468   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5469          !ResultType.isCForbiddenLValueType());
5470 
5471   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5472       FunctionScopes.size() > 1) {
5473     if (auto *TT =
5474             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5475       for (auto I = FunctionScopes.rbegin(),
5476                 E = std::prev(FunctionScopes.rend());
5477            I != E; ++I) {
5478         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5479         if (CSI == nullptr)
5480           break;
5481         DeclContext *DC = nullptr;
5482         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5483           DC = LSI->CallOperator;
5484         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5485           DC = CRSI->TheCapturedDecl;
5486         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5487           DC = BSI->TheDecl;
5488         if (DC) {
5489           if (DC->containsDecl(TT->getDecl()))
5490             break;
5491           captureVariablyModifiedType(
5492               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5493         }
5494       }
5495     }
5496   }
5497 
5498   return new (Context)
5499       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5500 }
5501 
5502 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5503                                   ParmVarDecl *Param) {
5504   if (Param->hasUnparsedDefaultArg()) {
5505     // If we've already cleared out the location for the default argument,
5506     // that means we're parsing it right now.
5507     if (!UnparsedDefaultArgLocs.count(Param)) {
5508       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5509       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5510       Param->setInvalidDecl();
5511       return true;
5512     }
5513 
5514     Diag(CallLoc,
5515          diag::err_use_of_default_argument_to_function_declared_later) <<
5516       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5517     Diag(UnparsedDefaultArgLocs[Param],
5518          diag::note_default_argument_declared_here);
5519     return true;
5520   }
5521 
5522   if (Param->hasUninstantiatedDefaultArg()) {
5523     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5524 
5525     EnterExpressionEvaluationContext EvalContext(
5526         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5527 
5528     // Instantiate the expression.
5529     //
5530     // FIXME: Pass in a correct Pattern argument, otherwise
5531     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5532     //
5533     // template<typename T>
5534     // struct A {
5535     //   static int FooImpl();
5536     //
5537     //   template<typename Tp>
5538     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5539     //   // template argument list [[T], [Tp]], should be [[Tp]].
5540     //   friend A<Tp> Foo(int a);
5541     // };
5542     //
5543     // template<typename T>
5544     // A<T> Foo(int a = A<T>::FooImpl());
5545     MultiLevelTemplateArgumentList MutiLevelArgList
5546       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5547 
5548     InstantiatingTemplate Inst(*this, CallLoc, Param,
5549                                MutiLevelArgList.getInnermost());
5550     if (Inst.isInvalid())
5551       return true;
5552     if (Inst.isAlreadyInstantiating()) {
5553       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5554       Param->setInvalidDecl();
5555       return true;
5556     }
5557 
5558     ExprResult Result;
5559     {
5560       // C++ [dcl.fct.default]p5:
5561       //   The names in the [default argument] expression are bound, and
5562       //   the semantic constraints are checked, at the point where the
5563       //   default argument expression appears.
5564       ContextRAII SavedContext(*this, FD);
5565       LocalInstantiationScope Local(*this);
5566       runWithSufficientStackSpace(CallLoc, [&] {
5567         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5568                                   /*DirectInit*/false);
5569       });
5570     }
5571     if (Result.isInvalid())
5572       return true;
5573 
5574     // Check the expression as an initializer for the parameter.
5575     InitializedEntity Entity
5576       = InitializedEntity::InitializeParameter(Context, Param);
5577     InitializationKind Kind = InitializationKind::CreateCopy(
5578         Param->getLocation(),
5579         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5580     Expr *ResultE = Result.getAs<Expr>();
5581 
5582     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5583     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5584     if (Result.isInvalid())
5585       return true;
5586 
5587     Result =
5588         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5589                             /*DiscardedValue*/ false);
5590     if (Result.isInvalid())
5591       return true;
5592 
5593     // Remember the instantiated default argument.
5594     Param->setDefaultArg(Result.getAs<Expr>());
5595     if (ASTMutationListener *L = getASTMutationListener()) {
5596       L->DefaultArgumentInstantiated(Param);
5597     }
5598   }
5599 
5600   assert(Param->hasInit() && "default argument but no initializer?");
5601 
5602   // If the default expression creates temporaries, we need to
5603   // push them to the current stack of expression temporaries so they'll
5604   // be properly destroyed.
5605   // FIXME: We should really be rebuilding the default argument with new
5606   // bound temporaries; see the comment in PR5810.
5607   // We don't need to do that with block decls, though, because
5608   // blocks in default argument expression can never capture anything.
5609   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5610     // Set the "needs cleanups" bit regardless of whether there are
5611     // any explicit objects.
5612     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5613 
5614     // Append all the objects to the cleanup list.  Right now, this
5615     // should always be a no-op, because blocks in default argument
5616     // expressions should never be able to capture anything.
5617     assert(!Init->getNumObjects() &&
5618            "default argument expression has capturing blocks?");
5619   }
5620 
5621   // We already type-checked the argument, so we know it works.
5622   // Just mark all of the declarations in this potentially-evaluated expression
5623   // as being "referenced".
5624   EnterExpressionEvaluationContext EvalContext(
5625       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5626   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5627                                    /*SkipLocalVariables=*/true);
5628   return false;
5629 }
5630 
5631 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5632                                         FunctionDecl *FD, ParmVarDecl *Param) {
5633   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5634   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5635     return ExprError();
5636   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5637 }
5638 
5639 Sema::VariadicCallType
5640 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5641                           Expr *Fn) {
5642   if (Proto && Proto->isVariadic()) {
5643     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5644       return VariadicConstructor;
5645     else if (Fn && Fn->getType()->isBlockPointerType())
5646       return VariadicBlock;
5647     else if (FDecl) {
5648       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5649         if (Method->isInstance())
5650           return VariadicMethod;
5651     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5652       return VariadicMethod;
5653     return VariadicFunction;
5654   }
5655   return VariadicDoesNotApply;
5656 }
5657 
5658 namespace {
5659 class FunctionCallCCC final : public FunctionCallFilterCCC {
5660 public:
5661   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5662                   unsigned NumArgs, MemberExpr *ME)
5663       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5664         FunctionName(FuncName) {}
5665 
5666   bool ValidateCandidate(const TypoCorrection &candidate) override {
5667     if (!candidate.getCorrectionSpecifier() ||
5668         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5669       return false;
5670     }
5671 
5672     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5673   }
5674 
5675   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5676     return std::make_unique<FunctionCallCCC>(*this);
5677   }
5678 
5679 private:
5680   const IdentifierInfo *const FunctionName;
5681 };
5682 }
5683 
5684 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5685                                                FunctionDecl *FDecl,
5686                                                ArrayRef<Expr *> Args) {
5687   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5688   DeclarationName FuncName = FDecl->getDeclName();
5689   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5690 
5691   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5692   if (TypoCorrection Corrected = S.CorrectTypo(
5693           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5694           S.getScopeForContext(S.CurContext), nullptr, CCC,
5695           Sema::CTK_ErrorRecovery)) {
5696     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5697       if (Corrected.isOverloaded()) {
5698         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5699         OverloadCandidateSet::iterator Best;
5700         for (NamedDecl *CD : Corrected) {
5701           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5702             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5703                                    OCS);
5704         }
5705         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5706         case OR_Success:
5707           ND = Best->FoundDecl;
5708           Corrected.setCorrectionDecl(ND);
5709           break;
5710         default:
5711           break;
5712         }
5713       }
5714       ND = ND->getUnderlyingDecl();
5715       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5716         return Corrected;
5717     }
5718   }
5719   return TypoCorrection();
5720 }
5721 
5722 /// ConvertArgumentsForCall - Converts the arguments specified in
5723 /// Args/NumArgs to the parameter types of the function FDecl with
5724 /// function prototype Proto. Call is the call expression itself, and
5725 /// Fn is the function expression. For a C++ member function, this
5726 /// routine does not attempt to convert the object argument. Returns
5727 /// true if the call is ill-formed.
5728 bool
5729 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5730                               FunctionDecl *FDecl,
5731                               const FunctionProtoType *Proto,
5732                               ArrayRef<Expr *> Args,
5733                               SourceLocation RParenLoc,
5734                               bool IsExecConfig) {
5735   // Bail out early if calling a builtin with custom typechecking.
5736   if (FDecl)
5737     if (unsigned ID = FDecl->getBuiltinID())
5738       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5739         return false;
5740 
5741   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5742   // assignment, to the types of the corresponding parameter, ...
5743   unsigned NumParams = Proto->getNumParams();
5744   bool Invalid = false;
5745   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5746   unsigned FnKind = Fn->getType()->isBlockPointerType()
5747                        ? 1 /* block */
5748                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5749                                        : 0 /* function */);
5750 
5751   // If too few arguments are available (and we don't have default
5752   // arguments for the remaining parameters), don't make the call.
5753   if (Args.size() < NumParams) {
5754     if (Args.size() < MinArgs) {
5755       TypoCorrection TC;
5756       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5757         unsigned diag_id =
5758             MinArgs == NumParams && !Proto->isVariadic()
5759                 ? diag::err_typecheck_call_too_few_args_suggest
5760                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5761         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5762                                         << static_cast<unsigned>(Args.size())
5763                                         << TC.getCorrectionRange());
5764       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5765         Diag(RParenLoc,
5766              MinArgs == NumParams && !Proto->isVariadic()
5767                  ? diag::err_typecheck_call_too_few_args_one
5768                  : diag::err_typecheck_call_too_few_args_at_least_one)
5769             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5770       else
5771         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5772                             ? diag::err_typecheck_call_too_few_args
5773                             : diag::err_typecheck_call_too_few_args_at_least)
5774             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5775             << Fn->getSourceRange();
5776 
5777       // Emit the location of the prototype.
5778       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5779         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5780 
5781       return true;
5782     }
5783     // We reserve space for the default arguments when we create
5784     // the call expression, before calling ConvertArgumentsForCall.
5785     assert((Call->getNumArgs() == NumParams) &&
5786            "We should have reserved space for the default arguments before!");
5787   }
5788 
5789   // If too many are passed and not variadic, error on the extras and drop
5790   // them.
5791   if (Args.size() > NumParams) {
5792     if (!Proto->isVariadic()) {
5793       TypoCorrection TC;
5794       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5795         unsigned diag_id =
5796             MinArgs == NumParams && !Proto->isVariadic()
5797                 ? diag::err_typecheck_call_too_many_args_suggest
5798                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5799         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5800                                         << static_cast<unsigned>(Args.size())
5801                                         << TC.getCorrectionRange());
5802       } else if (NumParams == 1 && FDecl &&
5803                  FDecl->getParamDecl(0)->getDeclName())
5804         Diag(Args[NumParams]->getBeginLoc(),
5805              MinArgs == NumParams
5806                  ? diag::err_typecheck_call_too_many_args_one
5807                  : diag::err_typecheck_call_too_many_args_at_most_one)
5808             << FnKind << FDecl->getParamDecl(0)
5809             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5810             << SourceRange(Args[NumParams]->getBeginLoc(),
5811                            Args.back()->getEndLoc());
5812       else
5813         Diag(Args[NumParams]->getBeginLoc(),
5814              MinArgs == NumParams
5815                  ? diag::err_typecheck_call_too_many_args
5816                  : diag::err_typecheck_call_too_many_args_at_most)
5817             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5818             << Fn->getSourceRange()
5819             << SourceRange(Args[NumParams]->getBeginLoc(),
5820                            Args.back()->getEndLoc());
5821 
5822       // Emit the location of the prototype.
5823       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5824         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5825 
5826       // This deletes the extra arguments.
5827       Call->shrinkNumArgs(NumParams);
5828       return true;
5829     }
5830   }
5831   SmallVector<Expr *, 8> AllArgs;
5832   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5833 
5834   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5835                                    AllArgs, CallType);
5836   if (Invalid)
5837     return true;
5838   unsigned TotalNumArgs = AllArgs.size();
5839   for (unsigned i = 0; i < TotalNumArgs; ++i)
5840     Call->setArg(i, AllArgs[i]);
5841 
5842   return false;
5843 }
5844 
5845 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5846                                   const FunctionProtoType *Proto,
5847                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5848                                   SmallVectorImpl<Expr *> &AllArgs,
5849                                   VariadicCallType CallType, bool AllowExplicit,
5850                                   bool IsListInitialization) {
5851   unsigned NumParams = Proto->getNumParams();
5852   bool Invalid = false;
5853   size_t ArgIx = 0;
5854   // Continue to check argument types (even if we have too few/many args).
5855   for (unsigned i = FirstParam; i < NumParams; i++) {
5856     QualType ProtoArgType = Proto->getParamType(i);
5857 
5858     Expr *Arg;
5859     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5860     if (ArgIx < Args.size()) {
5861       Arg = Args[ArgIx++];
5862 
5863       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5864                               diag::err_call_incomplete_argument, Arg))
5865         return true;
5866 
5867       // Strip the unbridged-cast placeholder expression off, if applicable.
5868       bool CFAudited = false;
5869       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5870           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5871           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5872         Arg = stripARCUnbridgedCast(Arg);
5873       else if (getLangOpts().ObjCAutoRefCount &&
5874                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5875                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5876         CFAudited = true;
5877 
5878       if (Proto->getExtParameterInfo(i).isNoEscape())
5879         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5880           BE->getBlockDecl()->setDoesNotEscape();
5881 
5882       InitializedEntity Entity =
5883           Param ? InitializedEntity::InitializeParameter(Context, Param,
5884                                                          ProtoArgType)
5885                 : InitializedEntity::InitializeParameter(
5886                       Context, ProtoArgType, Proto->isParamConsumed(i));
5887 
5888       // Remember that parameter belongs to a CF audited API.
5889       if (CFAudited)
5890         Entity.setParameterCFAudited();
5891 
5892       ExprResult ArgE = PerformCopyInitialization(
5893           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5894       if (ArgE.isInvalid())
5895         return true;
5896 
5897       Arg = ArgE.getAs<Expr>();
5898     } else {
5899       assert(Param && "can't use default arguments without a known callee");
5900 
5901       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5902       if (ArgExpr.isInvalid())
5903         return true;
5904 
5905       Arg = ArgExpr.getAs<Expr>();
5906     }
5907 
5908     // Check for array bounds violations for each argument to the call. This
5909     // check only triggers warnings when the argument isn't a more complex Expr
5910     // with its own checking, such as a BinaryOperator.
5911     CheckArrayAccess(Arg);
5912 
5913     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5914     CheckStaticArrayArgument(CallLoc, Param, Arg);
5915 
5916     AllArgs.push_back(Arg);
5917   }
5918 
5919   // If this is a variadic call, handle args passed through "...".
5920   if (CallType != VariadicDoesNotApply) {
5921     // Assume that extern "C" functions with variadic arguments that
5922     // return __unknown_anytype aren't *really* variadic.
5923     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5924         FDecl->isExternC()) {
5925       for (Expr *A : Args.slice(ArgIx)) {
5926         QualType paramType; // ignored
5927         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5928         Invalid |= arg.isInvalid();
5929         AllArgs.push_back(arg.get());
5930       }
5931 
5932     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5933     } else {
5934       for (Expr *A : Args.slice(ArgIx)) {
5935         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5936         Invalid |= Arg.isInvalid();
5937         // Copy blocks to the heap.
5938         if (A->getType()->isBlockPointerType())
5939           maybeExtendBlockObject(Arg);
5940         AllArgs.push_back(Arg.get());
5941       }
5942     }
5943 
5944     // Check for array bounds violations.
5945     for (Expr *A : Args.slice(ArgIx))
5946       CheckArrayAccess(A);
5947   }
5948   return Invalid;
5949 }
5950 
5951 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5952   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5953   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5954     TL = DTL.getOriginalLoc();
5955   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5956     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5957       << ATL.getLocalSourceRange();
5958 }
5959 
5960 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5961 /// array parameter, check that it is non-null, and that if it is formed by
5962 /// array-to-pointer decay, the underlying array is sufficiently large.
5963 ///
5964 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5965 /// array type derivation, then for each call to the function, the value of the
5966 /// corresponding actual argument shall provide access to the first element of
5967 /// an array with at least as many elements as specified by the size expression.
5968 void
5969 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5970                                ParmVarDecl *Param,
5971                                const Expr *ArgExpr) {
5972   // Static array parameters are not supported in C++.
5973   if (!Param || getLangOpts().CPlusPlus)
5974     return;
5975 
5976   QualType OrigTy = Param->getOriginalType();
5977 
5978   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5979   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5980     return;
5981 
5982   if (ArgExpr->isNullPointerConstant(Context,
5983                                      Expr::NPC_NeverValueDependent)) {
5984     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5985     DiagnoseCalleeStaticArrayParam(*this, Param);
5986     return;
5987   }
5988 
5989   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5990   if (!CAT)
5991     return;
5992 
5993   const ConstantArrayType *ArgCAT =
5994     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5995   if (!ArgCAT)
5996     return;
5997 
5998   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5999                                              ArgCAT->getElementType())) {
6000     if (ArgCAT->getSize().ult(CAT->getSize())) {
6001       Diag(CallLoc, diag::warn_static_array_too_small)
6002           << ArgExpr->getSourceRange()
6003           << (unsigned)ArgCAT->getSize().getZExtValue()
6004           << (unsigned)CAT->getSize().getZExtValue() << 0;
6005       DiagnoseCalleeStaticArrayParam(*this, Param);
6006     }
6007     return;
6008   }
6009 
6010   Optional<CharUnits> ArgSize =
6011       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6012   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6013   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6014     Diag(CallLoc, diag::warn_static_array_too_small)
6015         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6016         << (unsigned)ParmSize->getQuantity() << 1;
6017     DiagnoseCalleeStaticArrayParam(*this, Param);
6018   }
6019 }
6020 
6021 /// Given a function expression of unknown-any type, try to rebuild it
6022 /// to have a function type.
6023 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6024 
6025 /// Is the given type a placeholder that we need to lower out
6026 /// immediately during argument processing?
6027 static bool isPlaceholderToRemoveAsArg(QualType type) {
6028   // Placeholders are never sugared.
6029   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6030   if (!placeholder) return false;
6031 
6032   switch (placeholder->getKind()) {
6033   // Ignore all the non-placeholder types.
6034 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6035   case BuiltinType::Id:
6036 #include "clang/Basic/OpenCLImageTypes.def"
6037 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6038   case BuiltinType::Id:
6039 #include "clang/Basic/OpenCLExtensionTypes.def"
6040   // In practice we'll never use this, since all SVE types are sugared
6041   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6042 #define SVE_TYPE(Name, Id, SingletonId) \
6043   case BuiltinType::Id:
6044 #include "clang/Basic/AArch64SVEACLETypes.def"
6045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6047 #include "clang/AST/BuiltinTypes.def"
6048     return false;
6049 
6050   // We cannot lower out overload sets; they might validly be resolved
6051   // by the call machinery.
6052   case BuiltinType::Overload:
6053     return false;
6054 
6055   // Unbridged casts in ARC can be handled in some call positions and
6056   // should be left in place.
6057   case BuiltinType::ARCUnbridgedCast:
6058     return false;
6059 
6060   // Pseudo-objects should be converted as soon as possible.
6061   case BuiltinType::PseudoObject:
6062     return true;
6063 
6064   // The debugger mode could theoretically but currently does not try
6065   // to resolve unknown-typed arguments based on known parameter types.
6066   case BuiltinType::UnknownAny:
6067     return true;
6068 
6069   // These are always invalid as call arguments and should be reported.
6070   case BuiltinType::BoundMember:
6071   case BuiltinType::BuiltinFn:
6072   case BuiltinType::IncompleteMatrixIdx:
6073   case BuiltinType::OMPArraySection:
6074   case BuiltinType::OMPArrayShaping:
6075   case BuiltinType::OMPIterator:
6076     return true;
6077 
6078   }
6079   llvm_unreachable("bad builtin type kind");
6080 }
6081 
6082 /// Check an argument list for placeholders that we won't try to
6083 /// handle later.
6084 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6085   // Apply this processing to all the arguments at once instead of
6086   // dying at the first failure.
6087   bool hasInvalid = false;
6088   for (size_t i = 0, e = args.size(); i != e; i++) {
6089     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6090       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6091       if (result.isInvalid()) hasInvalid = true;
6092       else args[i] = result.get();
6093     } else if (hasInvalid) {
6094       (void)S.CorrectDelayedTyposInExpr(args[i]);
6095     }
6096   }
6097   return hasInvalid;
6098 }
6099 
6100 /// If a builtin function has a pointer argument with no explicit address
6101 /// space, then it should be able to accept a pointer to any address
6102 /// space as input.  In order to do this, we need to replace the
6103 /// standard builtin declaration with one that uses the same address space
6104 /// as the call.
6105 ///
6106 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6107 ///                  it does not contain any pointer arguments without
6108 ///                  an address space qualifer.  Otherwise the rewritten
6109 ///                  FunctionDecl is returned.
6110 /// TODO: Handle pointer return types.
6111 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6112                                                 FunctionDecl *FDecl,
6113                                                 MultiExprArg ArgExprs) {
6114 
6115   QualType DeclType = FDecl->getType();
6116   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6117 
6118   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6119       ArgExprs.size() < FT->getNumParams())
6120     return nullptr;
6121 
6122   bool NeedsNewDecl = false;
6123   unsigned i = 0;
6124   SmallVector<QualType, 8> OverloadParams;
6125 
6126   for (QualType ParamType : FT->param_types()) {
6127 
6128     // Convert array arguments to pointer to simplify type lookup.
6129     ExprResult ArgRes =
6130         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6131     if (ArgRes.isInvalid())
6132       return nullptr;
6133     Expr *Arg = ArgRes.get();
6134     QualType ArgType = Arg->getType();
6135     if (!ParamType->isPointerType() ||
6136         ParamType.hasAddressSpace() ||
6137         !ArgType->isPointerType() ||
6138         !ArgType->getPointeeType().hasAddressSpace()) {
6139       OverloadParams.push_back(ParamType);
6140       continue;
6141     }
6142 
6143     QualType PointeeType = ParamType->getPointeeType();
6144     if (PointeeType.hasAddressSpace())
6145       continue;
6146 
6147     NeedsNewDecl = true;
6148     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6149 
6150     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6151     OverloadParams.push_back(Context.getPointerType(PointeeType));
6152   }
6153 
6154   if (!NeedsNewDecl)
6155     return nullptr;
6156 
6157   FunctionProtoType::ExtProtoInfo EPI;
6158   EPI.Variadic = FT->isVariadic();
6159   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6160                                                 OverloadParams, EPI);
6161   DeclContext *Parent = FDecl->getParent();
6162   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6163                                                     FDecl->getLocation(),
6164                                                     FDecl->getLocation(),
6165                                                     FDecl->getIdentifier(),
6166                                                     OverloadTy,
6167                                                     /*TInfo=*/nullptr,
6168                                                     SC_Extern, false,
6169                                                     /*hasPrototype=*/true);
6170   SmallVector<ParmVarDecl*, 16> Params;
6171   FT = cast<FunctionProtoType>(OverloadTy);
6172   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6173     QualType ParamType = FT->getParamType(i);
6174     ParmVarDecl *Parm =
6175         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6176                                 SourceLocation(), nullptr, ParamType,
6177                                 /*TInfo=*/nullptr, SC_None, nullptr);
6178     Parm->setScopeInfo(0, i);
6179     Params.push_back(Parm);
6180   }
6181   OverloadDecl->setParams(Params);
6182   return OverloadDecl;
6183 }
6184 
6185 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6186                                     FunctionDecl *Callee,
6187                                     MultiExprArg ArgExprs) {
6188   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6189   // similar attributes) really don't like it when functions are called with an
6190   // invalid number of args.
6191   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6192                          /*PartialOverloading=*/false) &&
6193       !Callee->isVariadic())
6194     return;
6195   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6196     return;
6197 
6198   if (const EnableIfAttr *Attr =
6199           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6200     S.Diag(Fn->getBeginLoc(),
6201            isa<CXXMethodDecl>(Callee)
6202                ? diag::err_ovl_no_viable_member_function_in_call
6203                : diag::err_ovl_no_viable_function_in_call)
6204         << Callee << Callee->getSourceRange();
6205     S.Diag(Callee->getLocation(),
6206            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6207         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6208     return;
6209   }
6210 }
6211 
6212 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6213     const UnresolvedMemberExpr *const UME, Sema &S) {
6214 
6215   const auto GetFunctionLevelDCIfCXXClass =
6216       [](Sema &S) -> const CXXRecordDecl * {
6217     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6218     if (!DC || !DC->getParent())
6219       return nullptr;
6220 
6221     // If the call to some member function was made from within a member
6222     // function body 'M' return return 'M's parent.
6223     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6224       return MD->getParent()->getCanonicalDecl();
6225     // else the call was made from within a default member initializer of a
6226     // class, so return the class.
6227     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6228       return RD->getCanonicalDecl();
6229     return nullptr;
6230   };
6231   // If our DeclContext is neither a member function nor a class (in the
6232   // case of a lambda in a default member initializer), we can't have an
6233   // enclosing 'this'.
6234 
6235   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6236   if (!CurParentClass)
6237     return false;
6238 
6239   // The naming class for implicit member functions call is the class in which
6240   // name lookup starts.
6241   const CXXRecordDecl *const NamingClass =
6242       UME->getNamingClass()->getCanonicalDecl();
6243   assert(NamingClass && "Must have naming class even for implicit access");
6244 
6245   // If the unresolved member functions were found in a 'naming class' that is
6246   // related (either the same or derived from) to the class that contains the
6247   // member function that itself contained the implicit member access.
6248 
6249   return CurParentClass == NamingClass ||
6250          CurParentClass->isDerivedFrom(NamingClass);
6251 }
6252 
6253 static void
6254 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6255     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6256 
6257   if (!UME)
6258     return;
6259 
6260   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6261   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6262   // already been captured, or if this is an implicit member function call (if
6263   // it isn't, an attempt to capture 'this' should already have been made).
6264   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6265       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6266     return;
6267 
6268   // Check if the naming class in which the unresolved members were found is
6269   // related (same as or is a base of) to the enclosing class.
6270 
6271   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6272     return;
6273 
6274 
6275   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6276   // If the enclosing function is not dependent, then this lambda is
6277   // capture ready, so if we can capture this, do so.
6278   if (!EnclosingFunctionCtx->isDependentContext()) {
6279     // If the current lambda and all enclosing lambdas can capture 'this' -
6280     // then go ahead and capture 'this' (since our unresolved overload set
6281     // contains at least one non-static member function).
6282     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6283       S.CheckCXXThisCapture(CallLoc);
6284   } else if (S.CurContext->isDependentContext()) {
6285     // ... since this is an implicit member reference, that might potentially
6286     // involve a 'this' capture, mark 'this' for potential capture in
6287     // enclosing lambdas.
6288     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6289       CurLSI->addPotentialThisCapture(CallLoc);
6290   }
6291 }
6292 
6293 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6294                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6295                                Expr *ExecConfig) {
6296   ExprResult Call =
6297       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6298   if (Call.isInvalid())
6299     return Call;
6300 
6301   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6302   // language modes.
6303   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6304     if (ULE->hasExplicitTemplateArgs() &&
6305         ULE->decls_begin() == ULE->decls_end()) {
6306       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6307                                  ? diag::warn_cxx17_compat_adl_only_template_id
6308                                  : diag::ext_adl_only_template_id)
6309           << ULE->getName();
6310     }
6311   }
6312 
6313   if (LangOpts.OpenMP)
6314     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6315                            ExecConfig);
6316 
6317   return Call;
6318 }
6319 
6320 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6321 /// This provides the location of the left/right parens and a list of comma
6322 /// locations.
6323 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6324                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6325                                Expr *ExecConfig, bool IsExecConfig) {
6326   // Since this might be a postfix expression, get rid of ParenListExprs.
6327   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6328   if (Result.isInvalid()) return ExprError();
6329   Fn = Result.get();
6330 
6331   if (checkArgsForPlaceholders(*this, ArgExprs))
6332     return ExprError();
6333 
6334   if (getLangOpts().CPlusPlus) {
6335     // If this is a pseudo-destructor expression, build the call immediately.
6336     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6337       if (!ArgExprs.empty()) {
6338         // Pseudo-destructor calls should not have any arguments.
6339         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6340             << FixItHint::CreateRemoval(
6341                    SourceRange(ArgExprs.front()->getBeginLoc(),
6342                                ArgExprs.back()->getEndLoc()));
6343       }
6344 
6345       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6346                               VK_RValue, RParenLoc);
6347     }
6348     if (Fn->getType() == Context.PseudoObjectTy) {
6349       ExprResult result = CheckPlaceholderExpr(Fn);
6350       if (result.isInvalid()) return ExprError();
6351       Fn = result.get();
6352     }
6353 
6354     // Determine whether this is a dependent call inside a C++ template,
6355     // in which case we won't do any semantic analysis now.
6356     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6357       if (ExecConfig) {
6358         return CUDAKernelCallExpr::Create(
6359             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6360             Context.DependentTy, VK_RValue, RParenLoc);
6361       } else {
6362 
6363         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6364             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6365             Fn->getBeginLoc());
6366 
6367         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6368                                 VK_RValue, RParenLoc);
6369       }
6370     }
6371 
6372     // Determine whether this is a call to an object (C++ [over.call.object]).
6373     if (Fn->getType()->isRecordType())
6374       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6375                                           RParenLoc);
6376 
6377     if (Fn->getType() == Context.UnknownAnyTy) {
6378       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6379       if (result.isInvalid()) return ExprError();
6380       Fn = result.get();
6381     }
6382 
6383     if (Fn->getType() == Context.BoundMemberTy) {
6384       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6385                                        RParenLoc);
6386     }
6387   }
6388 
6389   // Check for overloaded calls.  This can happen even in C due to extensions.
6390   if (Fn->getType() == Context.OverloadTy) {
6391     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6392 
6393     // We aren't supposed to apply this logic if there's an '&' involved.
6394     if (!find.HasFormOfMemberPointer) {
6395       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6396         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6397                                 VK_RValue, RParenLoc);
6398       OverloadExpr *ovl = find.Expression;
6399       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6400         return BuildOverloadedCallExpr(
6401             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6402             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6403       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6404                                        RParenLoc);
6405     }
6406   }
6407 
6408   // If we're directly calling a function, get the appropriate declaration.
6409   if (Fn->getType() == Context.UnknownAnyTy) {
6410     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6411     if (result.isInvalid()) return ExprError();
6412     Fn = result.get();
6413   }
6414 
6415   Expr *NakedFn = Fn->IgnoreParens();
6416 
6417   bool CallingNDeclIndirectly = false;
6418   NamedDecl *NDecl = nullptr;
6419   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6420     if (UnOp->getOpcode() == UO_AddrOf) {
6421       CallingNDeclIndirectly = true;
6422       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6423     }
6424   }
6425 
6426   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6427     NDecl = DRE->getDecl();
6428 
6429     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6430     if (FDecl && FDecl->getBuiltinID()) {
6431       // Rewrite the function decl for this builtin by replacing parameters
6432       // with no explicit address space with the address space of the arguments
6433       // in ArgExprs.
6434       if ((FDecl =
6435                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6436         NDecl = FDecl;
6437         Fn = DeclRefExpr::Create(
6438             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6439             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6440             nullptr, DRE->isNonOdrUse());
6441       }
6442     }
6443   } else if (isa<MemberExpr>(NakedFn))
6444     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6445 
6446   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6447     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6448                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6449       return ExprError();
6450 
6451     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6452       return ExprError();
6453 
6454     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6455   }
6456 
6457   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6458                                ExecConfig, IsExecConfig);
6459 }
6460 
6461 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6462 ///
6463 /// __builtin_astype( value, dst type )
6464 ///
6465 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6466                                  SourceLocation BuiltinLoc,
6467                                  SourceLocation RParenLoc) {
6468   ExprValueKind VK = VK_RValue;
6469   ExprObjectKind OK = OK_Ordinary;
6470   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6471   QualType SrcTy = E->getType();
6472   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6473     return ExprError(Diag(BuiltinLoc,
6474                           diag::err_invalid_astype_of_different_size)
6475                      << DstTy
6476                      << SrcTy
6477                      << E->getSourceRange());
6478   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6479 }
6480 
6481 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6482 /// provided arguments.
6483 ///
6484 /// __builtin_convertvector( value, dst type )
6485 ///
6486 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6487                                         SourceLocation BuiltinLoc,
6488                                         SourceLocation RParenLoc) {
6489   TypeSourceInfo *TInfo;
6490   GetTypeFromParser(ParsedDestTy, &TInfo);
6491   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6492 }
6493 
6494 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6495 /// i.e. an expression not of \p OverloadTy.  The expression should
6496 /// unary-convert to an expression of function-pointer or
6497 /// block-pointer type.
6498 ///
6499 /// \param NDecl the declaration being called, if available
6500 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6501                                        SourceLocation LParenLoc,
6502                                        ArrayRef<Expr *> Args,
6503                                        SourceLocation RParenLoc, Expr *Config,
6504                                        bool IsExecConfig, ADLCallKind UsesADL) {
6505   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6506   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6507 
6508   // Functions with 'interrupt' attribute cannot be called directly.
6509   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6510     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6511     return ExprError();
6512   }
6513 
6514   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6515   // so there's some risk when calling out to non-interrupt handler functions
6516   // that the callee might not preserve them. This is easy to diagnose here,
6517   // but can be very challenging to debug.
6518   if (auto *Caller = getCurFunctionDecl())
6519     if (Caller->hasAttr<ARMInterruptAttr>()) {
6520       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6521       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6522         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6523     }
6524 
6525   // Promote the function operand.
6526   // We special-case function promotion here because we only allow promoting
6527   // builtin functions to function pointers in the callee of a call.
6528   ExprResult Result;
6529   QualType ResultTy;
6530   if (BuiltinID &&
6531       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6532     // Extract the return type from the (builtin) function pointer type.
6533     // FIXME Several builtins still have setType in
6534     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6535     // Builtins.def to ensure they are correct before removing setType calls.
6536     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6537     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6538     ResultTy = FDecl->getCallResultType();
6539   } else {
6540     Result = CallExprUnaryConversions(Fn);
6541     ResultTy = Context.BoolTy;
6542   }
6543   if (Result.isInvalid())
6544     return ExprError();
6545   Fn = Result.get();
6546 
6547   // Check for a valid function type, but only if it is not a builtin which
6548   // requires custom type checking. These will be handled by
6549   // CheckBuiltinFunctionCall below just after creation of the call expression.
6550   const FunctionType *FuncT = nullptr;
6551   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6552   retry:
6553     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6554       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6555       // have type pointer to function".
6556       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6557       if (!FuncT)
6558         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6559                          << Fn->getType() << Fn->getSourceRange());
6560     } else if (const BlockPointerType *BPT =
6561                    Fn->getType()->getAs<BlockPointerType>()) {
6562       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6563     } else {
6564       // Handle calls to expressions of unknown-any type.
6565       if (Fn->getType() == Context.UnknownAnyTy) {
6566         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6567         if (rewrite.isInvalid())
6568           return ExprError();
6569         Fn = rewrite.get();
6570         goto retry;
6571       }
6572 
6573       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6574                        << Fn->getType() << Fn->getSourceRange());
6575     }
6576   }
6577 
6578   // Get the number of parameters in the function prototype, if any.
6579   // We will allocate space for max(Args.size(), NumParams) arguments
6580   // in the call expression.
6581   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6582   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6583 
6584   CallExpr *TheCall;
6585   if (Config) {
6586     assert(UsesADL == ADLCallKind::NotADL &&
6587            "CUDAKernelCallExpr should not use ADL");
6588     TheCall =
6589         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6590                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6591   } else {
6592     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6593                                RParenLoc, NumParams, UsesADL);
6594   }
6595 
6596   if (!getLangOpts().CPlusPlus) {
6597     // Forget about the nulled arguments since typo correction
6598     // do not handle them well.
6599     TheCall->shrinkNumArgs(Args.size());
6600     // C cannot always handle TypoExpr nodes in builtin calls and direct
6601     // function calls as their argument checking don't necessarily handle
6602     // dependent types properly, so make sure any TypoExprs have been
6603     // dealt with.
6604     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6605     if (!Result.isUsable()) return ExprError();
6606     CallExpr *TheOldCall = TheCall;
6607     TheCall = dyn_cast<CallExpr>(Result.get());
6608     bool CorrectedTypos = TheCall != TheOldCall;
6609     if (!TheCall) return Result;
6610     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6611 
6612     // A new call expression node was created if some typos were corrected.
6613     // However it may not have been constructed with enough storage. In this
6614     // case, rebuild the node with enough storage. The waste of space is
6615     // immaterial since this only happens when some typos were corrected.
6616     if (CorrectedTypos && Args.size() < NumParams) {
6617       if (Config)
6618         TheCall = CUDAKernelCallExpr::Create(
6619             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6620             RParenLoc, NumParams);
6621       else
6622         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6623                                    RParenLoc, NumParams, UsesADL);
6624     }
6625     // We can now handle the nulled arguments for the default arguments.
6626     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6627   }
6628 
6629   // Bail out early if calling a builtin with custom type checking.
6630   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6631     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6632 
6633   if (getLangOpts().CUDA) {
6634     if (Config) {
6635       // CUDA: Kernel calls must be to global functions
6636       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6637         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6638             << FDecl << Fn->getSourceRange());
6639 
6640       // CUDA: Kernel function must have 'void' return type
6641       if (!FuncT->getReturnType()->isVoidType() &&
6642           !FuncT->getReturnType()->getAs<AutoType>() &&
6643           !FuncT->getReturnType()->isInstantiationDependentType())
6644         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6645             << Fn->getType() << Fn->getSourceRange());
6646     } else {
6647       // CUDA: Calls to global functions must be configured
6648       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6649         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6650             << FDecl << Fn->getSourceRange());
6651     }
6652   }
6653 
6654   // Check for a valid return type
6655   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6656                           FDecl))
6657     return ExprError();
6658 
6659   // We know the result type of the call, set it.
6660   TheCall->setType(FuncT->getCallResultType(Context));
6661   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6662 
6663   if (Proto) {
6664     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6665                                 IsExecConfig))
6666       return ExprError();
6667   } else {
6668     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6669 
6670     if (FDecl) {
6671       // Check if we have too few/too many template arguments, based
6672       // on our knowledge of the function definition.
6673       const FunctionDecl *Def = nullptr;
6674       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6675         Proto = Def->getType()->getAs<FunctionProtoType>();
6676        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6677           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6678           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6679       }
6680 
6681       // If the function we're calling isn't a function prototype, but we have
6682       // a function prototype from a prior declaratiom, use that prototype.
6683       if (!FDecl->hasPrototype())
6684         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6685     }
6686 
6687     // Promote the arguments (C99 6.5.2.2p6).
6688     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6689       Expr *Arg = Args[i];
6690 
6691       if (Proto && i < Proto->getNumParams()) {
6692         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6693             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6694         ExprResult ArgE =
6695             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6696         if (ArgE.isInvalid())
6697           return true;
6698 
6699         Arg = ArgE.getAs<Expr>();
6700 
6701       } else {
6702         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6703 
6704         if (ArgE.isInvalid())
6705           return true;
6706 
6707         Arg = ArgE.getAs<Expr>();
6708       }
6709 
6710       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6711                               diag::err_call_incomplete_argument, Arg))
6712         return ExprError();
6713 
6714       TheCall->setArg(i, Arg);
6715     }
6716   }
6717 
6718   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6719     if (!Method->isStatic())
6720       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6721         << Fn->getSourceRange());
6722 
6723   // Check for sentinels
6724   if (NDecl)
6725     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6726 
6727   // Warn for unions passing across security boundary (CMSE).
6728   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6729     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6730       if (const auto *RT =
6731               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6732         if (RT->getDecl()->isOrContainsUnion())
6733           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6734               << 0 << i;
6735       }
6736     }
6737   }
6738 
6739   // Do special checking on direct calls to functions.
6740   if (FDecl) {
6741     if (CheckFunctionCall(FDecl, TheCall, Proto))
6742       return ExprError();
6743 
6744     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6745 
6746     if (BuiltinID)
6747       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6748   } else if (NDecl) {
6749     if (CheckPointerCall(NDecl, TheCall, Proto))
6750       return ExprError();
6751   } else {
6752     if (CheckOtherCall(TheCall, Proto))
6753       return ExprError();
6754   }
6755 
6756   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6757 }
6758 
6759 ExprResult
6760 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6761                            SourceLocation RParenLoc, Expr *InitExpr) {
6762   assert(Ty && "ActOnCompoundLiteral(): missing type");
6763   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6764 
6765   TypeSourceInfo *TInfo;
6766   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6767   if (!TInfo)
6768     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6769 
6770   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6771 }
6772 
6773 ExprResult
6774 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6775                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6776   QualType literalType = TInfo->getType();
6777 
6778   if (literalType->isArrayType()) {
6779     if (RequireCompleteSizedType(
6780             LParenLoc, Context.getBaseElementType(literalType),
6781             diag::err_array_incomplete_or_sizeless_type,
6782             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6783       return ExprError();
6784     if (literalType->isVariableArrayType())
6785       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6786         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6787   } else if (!literalType->isDependentType() &&
6788              RequireCompleteType(LParenLoc, literalType,
6789                diag::err_typecheck_decl_incomplete_type,
6790                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6791     return ExprError();
6792 
6793   InitializedEntity Entity
6794     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6795   InitializationKind Kind
6796     = InitializationKind::CreateCStyleCast(LParenLoc,
6797                                            SourceRange(LParenLoc, RParenLoc),
6798                                            /*InitList=*/true);
6799   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6800   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6801                                       &literalType);
6802   if (Result.isInvalid())
6803     return ExprError();
6804   LiteralExpr = Result.get();
6805 
6806   bool isFileScope = !CurContext->isFunctionOrMethod();
6807 
6808   // In C, compound literals are l-values for some reason.
6809   // For GCC compatibility, in C++, file-scope array compound literals with
6810   // constant initializers are also l-values, and compound literals are
6811   // otherwise prvalues.
6812   //
6813   // (GCC also treats C++ list-initialized file-scope array prvalues with
6814   // constant initializers as l-values, but that's non-conforming, so we don't
6815   // follow it there.)
6816   //
6817   // FIXME: It would be better to handle the lvalue cases as materializing and
6818   // lifetime-extending a temporary object, but our materialized temporaries
6819   // representation only supports lifetime extension from a variable, not "out
6820   // of thin air".
6821   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6822   // is bound to the result of applying array-to-pointer decay to the compound
6823   // literal.
6824   // FIXME: GCC supports compound literals of reference type, which should
6825   // obviously have a value kind derived from the kind of reference involved.
6826   ExprValueKind VK =
6827       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6828           ? VK_RValue
6829           : VK_LValue;
6830 
6831   if (isFileScope)
6832     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6833       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6834         Expr *Init = ILE->getInit(i);
6835         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6836       }
6837 
6838   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6839                                               VK, LiteralExpr, isFileScope);
6840   if (isFileScope) {
6841     if (!LiteralExpr->isTypeDependent() &&
6842         !LiteralExpr->isValueDependent() &&
6843         !literalType->isDependentType()) // C99 6.5.2.5p3
6844       if (CheckForConstantInitializer(LiteralExpr, literalType))
6845         return ExprError();
6846   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6847              literalType.getAddressSpace() != LangAS::Default) {
6848     // Embedded-C extensions to C99 6.5.2.5:
6849     //   "If the compound literal occurs inside the body of a function, the
6850     //   type name shall not be qualified by an address-space qualifier."
6851     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6852       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6853     return ExprError();
6854   }
6855 
6856   if (!isFileScope && !getLangOpts().CPlusPlus) {
6857     // Compound literals that have automatic storage duration are destroyed at
6858     // the end of the scope in C; in C++, they're just temporaries.
6859 
6860     // Emit diagnostics if it is or contains a C union type that is non-trivial
6861     // to destruct.
6862     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6863       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6864                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6865 
6866     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6867     if (literalType.isDestructedType()) {
6868       Cleanup.setExprNeedsCleanups(true);
6869       ExprCleanupObjects.push_back(E);
6870       getCurFunction()->setHasBranchProtectedScope();
6871     }
6872   }
6873 
6874   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6875       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6876     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6877                                        E->getInitializer()->getExprLoc());
6878 
6879   return MaybeBindToTemporary(E);
6880 }
6881 
6882 ExprResult
6883 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6884                     SourceLocation RBraceLoc) {
6885   // Only produce each kind of designated initialization diagnostic once.
6886   SourceLocation FirstDesignator;
6887   bool DiagnosedArrayDesignator = false;
6888   bool DiagnosedNestedDesignator = false;
6889   bool DiagnosedMixedDesignator = false;
6890 
6891   // Check that any designated initializers are syntactically valid in the
6892   // current language mode.
6893   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6894     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6895       if (FirstDesignator.isInvalid())
6896         FirstDesignator = DIE->getBeginLoc();
6897 
6898       if (!getLangOpts().CPlusPlus)
6899         break;
6900 
6901       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6902         DiagnosedNestedDesignator = true;
6903         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6904           << DIE->getDesignatorsSourceRange();
6905       }
6906 
6907       for (auto &Desig : DIE->designators()) {
6908         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6909           DiagnosedArrayDesignator = true;
6910           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6911             << Desig.getSourceRange();
6912         }
6913       }
6914 
6915       if (!DiagnosedMixedDesignator &&
6916           !isa<DesignatedInitExpr>(InitArgList[0])) {
6917         DiagnosedMixedDesignator = true;
6918         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6919           << DIE->getSourceRange();
6920         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6921           << InitArgList[0]->getSourceRange();
6922       }
6923     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6924                isa<DesignatedInitExpr>(InitArgList[0])) {
6925       DiagnosedMixedDesignator = true;
6926       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6927       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6928         << DIE->getSourceRange();
6929       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6930         << InitArgList[I]->getSourceRange();
6931     }
6932   }
6933 
6934   if (FirstDesignator.isValid()) {
6935     // Only diagnose designated initiaization as a C++20 extension if we didn't
6936     // already diagnose use of (non-C++20) C99 designator syntax.
6937     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6938         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6939       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6940                                 ? diag::warn_cxx17_compat_designated_init
6941                                 : diag::ext_cxx_designated_init);
6942     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6943       Diag(FirstDesignator, diag::ext_designated_init);
6944     }
6945   }
6946 
6947   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6948 }
6949 
6950 ExprResult
6951 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6952                     SourceLocation RBraceLoc) {
6953   // Semantic analysis for initializers is done by ActOnDeclarator() and
6954   // CheckInitializer() - it requires knowledge of the object being initialized.
6955 
6956   // Immediately handle non-overload placeholders.  Overloads can be
6957   // resolved contextually, but everything else here can't.
6958   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6959     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6960       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6961 
6962       // Ignore failures; dropping the entire initializer list because
6963       // of one failure would be terrible for indexing/etc.
6964       if (result.isInvalid()) continue;
6965 
6966       InitArgList[I] = result.get();
6967     }
6968   }
6969 
6970   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6971                                                RBraceLoc);
6972   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6973   return E;
6974 }
6975 
6976 /// Do an explicit extend of the given block pointer if we're in ARC.
6977 void Sema::maybeExtendBlockObject(ExprResult &E) {
6978   assert(E.get()->getType()->isBlockPointerType());
6979   assert(E.get()->isRValue());
6980 
6981   // Only do this in an r-value context.
6982   if (!getLangOpts().ObjCAutoRefCount) return;
6983 
6984   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6985                                CK_ARCExtendBlockObject, E.get(),
6986                                /*base path*/ nullptr, VK_RValue);
6987   Cleanup.setExprNeedsCleanups(true);
6988 }
6989 
6990 /// Prepare a conversion of the given expression to an ObjC object
6991 /// pointer type.
6992 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6993   QualType type = E.get()->getType();
6994   if (type->isObjCObjectPointerType()) {
6995     return CK_BitCast;
6996   } else if (type->isBlockPointerType()) {
6997     maybeExtendBlockObject(E);
6998     return CK_BlockPointerToObjCPointerCast;
6999   } else {
7000     assert(type->isPointerType());
7001     return CK_CPointerToObjCPointerCast;
7002   }
7003 }
7004 
7005 /// Prepares for a scalar cast, performing all the necessary stages
7006 /// except the final cast and returning the kind required.
7007 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7008   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7009   // Also, callers should have filtered out the invalid cases with
7010   // pointers.  Everything else should be possible.
7011 
7012   QualType SrcTy = Src.get()->getType();
7013   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7014     return CK_NoOp;
7015 
7016   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7017   case Type::STK_MemberPointer:
7018     llvm_unreachable("member pointer type in C");
7019 
7020   case Type::STK_CPointer:
7021   case Type::STK_BlockPointer:
7022   case Type::STK_ObjCObjectPointer:
7023     switch (DestTy->getScalarTypeKind()) {
7024     case Type::STK_CPointer: {
7025       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7026       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7027       if (SrcAS != DestAS)
7028         return CK_AddressSpaceConversion;
7029       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7030         return CK_NoOp;
7031       return CK_BitCast;
7032     }
7033     case Type::STK_BlockPointer:
7034       return (SrcKind == Type::STK_BlockPointer
7035                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7036     case Type::STK_ObjCObjectPointer:
7037       if (SrcKind == Type::STK_ObjCObjectPointer)
7038         return CK_BitCast;
7039       if (SrcKind == Type::STK_CPointer)
7040         return CK_CPointerToObjCPointerCast;
7041       maybeExtendBlockObject(Src);
7042       return CK_BlockPointerToObjCPointerCast;
7043     case Type::STK_Bool:
7044       return CK_PointerToBoolean;
7045     case Type::STK_Integral:
7046       return CK_PointerToIntegral;
7047     case Type::STK_Floating:
7048     case Type::STK_FloatingComplex:
7049     case Type::STK_IntegralComplex:
7050     case Type::STK_MemberPointer:
7051     case Type::STK_FixedPoint:
7052       llvm_unreachable("illegal cast from pointer");
7053     }
7054     llvm_unreachable("Should have returned before this");
7055 
7056   case Type::STK_FixedPoint:
7057     switch (DestTy->getScalarTypeKind()) {
7058     case Type::STK_FixedPoint:
7059       return CK_FixedPointCast;
7060     case Type::STK_Bool:
7061       return CK_FixedPointToBoolean;
7062     case Type::STK_Integral:
7063       return CK_FixedPointToIntegral;
7064     case Type::STK_Floating:
7065     case Type::STK_IntegralComplex:
7066     case Type::STK_FloatingComplex:
7067       Diag(Src.get()->getExprLoc(),
7068            diag::err_unimplemented_conversion_with_fixed_point_type)
7069           << DestTy;
7070       return CK_IntegralCast;
7071     case Type::STK_CPointer:
7072     case Type::STK_ObjCObjectPointer:
7073     case Type::STK_BlockPointer:
7074     case Type::STK_MemberPointer:
7075       llvm_unreachable("illegal cast to pointer type");
7076     }
7077     llvm_unreachable("Should have returned before this");
7078 
7079   case Type::STK_Bool: // casting from bool is like casting from an integer
7080   case Type::STK_Integral:
7081     switch (DestTy->getScalarTypeKind()) {
7082     case Type::STK_CPointer:
7083     case Type::STK_ObjCObjectPointer:
7084     case Type::STK_BlockPointer:
7085       if (Src.get()->isNullPointerConstant(Context,
7086                                            Expr::NPC_ValueDependentIsNull))
7087         return CK_NullToPointer;
7088       return CK_IntegralToPointer;
7089     case Type::STK_Bool:
7090       return CK_IntegralToBoolean;
7091     case Type::STK_Integral:
7092       return CK_IntegralCast;
7093     case Type::STK_Floating:
7094       return CK_IntegralToFloating;
7095     case Type::STK_IntegralComplex:
7096       Src = ImpCastExprToType(Src.get(),
7097                       DestTy->castAs<ComplexType>()->getElementType(),
7098                       CK_IntegralCast);
7099       return CK_IntegralRealToComplex;
7100     case Type::STK_FloatingComplex:
7101       Src = ImpCastExprToType(Src.get(),
7102                       DestTy->castAs<ComplexType>()->getElementType(),
7103                       CK_IntegralToFloating);
7104       return CK_FloatingRealToComplex;
7105     case Type::STK_MemberPointer:
7106       llvm_unreachable("member pointer type in C");
7107     case Type::STK_FixedPoint:
7108       return CK_IntegralToFixedPoint;
7109     }
7110     llvm_unreachable("Should have returned before this");
7111 
7112   case Type::STK_Floating:
7113     switch (DestTy->getScalarTypeKind()) {
7114     case Type::STK_Floating:
7115       return CK_FloatingCast;
7116     case Type::STK_Bool:
7117       return CK_FloatingToBoolean;
7118     case Type::STK_Integral:
7119       return CK_FloatingToIntegral;
7120     case Type::STK_FloatingComplex:
7121       Src = ImpCastExprToType(Src.get(),
7122                               DestTy->castAs<ComplexType>()->getElementType(),
7123                               CK_FloatingCast);
7124       return CK_FloatingRealToComplex;
7125     case Type::STK_IntegralComplex:
7126       Src = ImpCastExprToType(Src.get(),
7127                               DestTy->castAs<ComplexType>()->getElementType(),
7128                               CK_FloatingToIntegral);
7129       return CK_IntegralRealToComplex;
7130     case Type::STK_CPointer:
7131     case Type::STK_ObjCObjectPointer:
7132     case Type::STK_BlockPointer:
7133       llvm_unreachable("valid float->pointer cast?");
7134     case Type::STK_MemberPointer:
7135       llvm_unreachable("member pointer type in C");
7136     case Type::STK_FixedPoint:
7137       Diag(Src.get()->getExprLoc(),
7138            diag::err_unimplemented_conversion_with_fixed_point_type)
7139           << SrcTy;
7140       return CK_IntegralCast;
7141     }
7142     llvm_unreachable("Should have returned before this");
7143 
7144   case Type::STK_FloatingComplex:
7145     switch (DestTy->getScalarTypeKind()) {
7146     case Type::STK_FloatingComplex:
7147       return CK_FloatingComplexCast;
7148     case Type::STK_IntegralComplex:
7149       return CK_FloatingComplexToIntegralComplex;
7150     case Type::STK_Floating: {
7151       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7152       if (Context.hasSameType(ET, DestTy))
7153         return CK_FloatingComplexToReal;
7154       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7155       return CK_FloatingCast;
7156     }
7157     case Type::STK_Bool:
7158       return CK_FloatingComplexToBoolean;
7159     case Type::STK_Integral:
7160       Src = ImpCastExprToType(Src.get(),
7161                               SrcTy->castAs<ComplexType>()->getElementType(),
7162                               CK_FloatingComplexToReal);
7163       return CK_FloatingToIntegral;
7164     case Type::STK_CPointer:
7165     case Type::STK_ObjCObjectPointer:
7166     case Type::STK_BlockPointer:
7167       llvm_unreachable("valid complex float->pointer cast?");
7168     case Type::STK_MemberPointer:
7169       llvm_unreachable("member pointer type in C");
7170     case Type::STK_FixedPoint:
7171       Diag(Src.get()->getExprLoc(),
7172            diag::err_unimplemented_conversion_with_fixed_point_type)
7173           << SrcTy;
7174       return CK_IntegralCast;
7175     }
7176     llvm_unreachable("Should have returned before this");
7177 
7178   case Type::STK_IntegralComplex:
7179     switch (DestTy->getScalarTypeKind()) {
7180     case Type::STK_FloatingComplex:
7181       return CK_IntegralComplexToFloatingComplex;
7182     case Type::STK_IntegralComplex:
7183       return CK_IntegralComplexCast;
7184     case Type::STK_Integral: {
7185       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7186       if (Context.hasSameType(ET, DestTy))
7187         return CK_IntegralComplexToReal;
7188       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7189       return CK_IntegralCast;
7190     }
7191     case Type::STK_Bool:
7192       return CK_IntegralComplexToBoolean;
7193     case Type::STK_Floating:
7194       Src = ImpCastExprToType(Src.get(),
7195                               SrcTy->castAs<ComplexType>()->getElementType(),
7196                               CK_IntegralComplexToReal);
7197       return CK_IntegralToFloating;
7198     case Type::STK_CPointer:
7199     case Type::STK_ObjCObjectPointer:
7200     case Type::STK_BlockPointer:
7201       llvm_unreachable("valid complex int->pointer cast?");
7202     case Type::STK_MemberPointer:
7203       llvm_unreachable("member pointer type in C");
7204     case Type::STK_FixedPoint:
7205       Diag(Src.get()->getExprLoc(),
7206            diag::err_unimplemented_conversion_with_fixed_point_type)
7207           << SrcTy;
7208       return CK_IntegralCast;
7209     }
7210     llvm_unreachable("Should have returned before this");
7211   }
7212 
7213   llvm_unreachable("Unhandled scalar cast");
7214 }
7215 
7216 static bool breakDownVectorType(QualType type, uint64_t &len,
7217                                 QualType &eltType) {
7218   // Vectors are simple.
7219   if (const VectorType *vecType = type->getAs<VectorType>()) {
7220     len = vecType->getNumElements();
7221     eltType = vecType->getElementType();
7222     assert(eltType->isScalarType());
7223     return true;
7224   }
7225 
7226   // We allow lax conversion to and from non-vector types, but only if
7227   // they're real types (i.e. non-complex, non-pointer scalar types).
7228   if (!type->isRealType()) return false;
7229 
7230   len = 1;
7231   eltType = type;
7232   return true;
7233 }
7234 
7235 /// Are the two types lax-compatible vector types?  That is, given
7236 /// that one of them is a vector, do they have equal storage sizes,
7237 /// where the storage size is the number of elements times the element
7238 /// size?
7239 ///
7240 /// This will also return false if either of the types is neither a
7241 /// vector nor a real type.
7242 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7243   assert(destTy->isVectorType() || srcTy->isVectorType());
7244 
7245   // Disallow lax conversions between scalars and ExtVectors (these
7246   // conversions are allowed for other vector types because common headers
7247   // depend on them).  Most scalar OP ExtVector cases are handled by the
7248   // splat path anyway, which does what we want (convert, not bitcast).
7249   // What this rules out for ExtVectors is crazy things like char4*float.
7250   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7251   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7252 
7253   uint64_t srcLen, destLen;
7254   QualType srcEltTy, destEltTy;
7255   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7256   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7257 
7258   // ASTContext::getTypeSize will return the size rounded up to a
7259   // power of 2, so instead of using that, we need to use the raw
7260   // element size multiplied by the element count.
7261   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7262   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7263 
7264   return (srcLen * srcEltSize == destLen * destEltSize);
7265 }
7266 
7267 /// Is this a legal conversion between two types, one of which is
7268 /// known to be a vector type?
7269 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7270   assert(destTy->isVectorType() || srcTy->isVectorType());
7271 
7272   switch (Context.getLangOpts().getLaxVectorConversions()) {
7273   case LangOptions::LaxVectorConversionKind::None:
7274     return false;
7275 
7276   case LangOptions::LaxVectorConversionKind::Integer:
7277     if (!srcTy->isIntegralOrEnumerationType()) {
7278       auto *Vec = srcTy->getAs<VectorType>();
7279       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7280         return false;
7281     }
7282     if (!destTy->isIntegralOrEnumerationType()) {
7283       auto *Vec = destTy->getAs<VectorType>();
7284       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7285         return false;
7286     }
7287     // OK, integer (vector) -> integer (vector) bitcast.
7288     break;
7289 
7290     case LangOptions::LaxVectorConversionKind::All:
7291     break;
7292   }
7293 
7294   return areLaxCompatibleVectorTypes(srcTy, destTy);
7295 }
7296 
7297 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7298                            CastKind &Kind) {
7299   assert(VectorTy->isVectorType() && "Not a vector type!");
7300 
7301   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7302     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7303       return Diag(R.getBegin(),
7304                   Ty->isVectorType() ?
7305                   diag::err_invalid_conversion_between_vectors :
7306                   diag::err_invalid_conversion_between_vector_and_integer)
7307         << VectorTy << Ty << R;
7308   } else
7309     return Diag(R.getBegin(),
7310                 diag::err_invalid_conversion_between_vector_and_scalar)
7311       << VectorTy << Ty << R;
7312 
7313   Kind = CK_BitCast;
7314   return false;
7315 }
7316 
7317 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7318   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7319 
7320   if (DestElemTy == SplattedExpr->getType())
7321     return SplattedExpr;
7322 
7323   assert(DestElemTy->isFloatingType() ||
7324          DestElemTy->isIntegralOrEnumerationType());
7325 
7326   CastKind CK;
7327   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7328     // OpenCL requires that we convert `true` boolean expressions to -1, but
7329     // only when splatting vectors.
7330     if (DestElemTy->isFloatingType()) {
7331       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7332       // in two steps: boolean to signed integral, then to floating.
7333       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7334                                                  CK_BooleanToSignedIntegral);
7335       SplattedExpr = CastExprRes.get();
7336       CK = CK_IntegralToFloating;
7337     } else {
7338       CK = CK_BooleanToSignedIntegral;
7339     }
7340   } else {
7341     ExprResult CastExprRes = SplattedExpr;
7342     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7343     if (CastExprRes.isInvalid())
7344       return ExprError();
7345     SplattedExpr = CastExprRes.get();
7346   }
7347   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7348 }
7349 
7350 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7351                                     Expr *CastExpr, CastKind &Kind) {
7352   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7353 
7354   QualType SrcTy = CastExpr->getType();
7355 
7356   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7357   // an ExtVectorType.
7358   // In OpenCL, casts between vectors of different types are not allowed.
7359   // (See OpenCL 6.2).
7360   if (SrcTy->isVectorType()) {
7361     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7362         (getLangOpts().OpenCL &&
7363          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7364       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7365         << DestTy << SrcTy << R;
7366       return ExprError();
7367     }
7368     Kind = CK_BitCast;
7369     return CastExpr;
7370   }
7371 
7372   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7373   // conversion will take place first from scalar to elt type, and then
7374   // splat from elt type to vector.
7375   if (SrcTy->isPointerType())
7376     return Diag(R.getBegin(),
7377                 diag::err_invalid_conversion_between_vector_and_scalar)
7378       << DestTy << SrcTy << R;
7379 
7380   Kind = CK_VectorSplat;
7381   return prepareVectorSplat(DestTy, CastExpr);
7382 }
7383 
7384 ExprResult
7385 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7386                     Declarator &D, ParsedType &Ty,
7387                     SourceLocation RParenLoc, Expr *CastExpr) {
7388   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7389          "ActOnCastExpr(): missing type or expr");
7390 
7391   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7392   if (D.isInvalidType())
7393     return ExprError();
7394 
7395   if (getLangOpts().CPlusPlus) {
7396     // Check that there are no default arguments (C++ only).
7397     CheckExtraCXXDefaultArguments(D);
7398   } else {
7399     // Make sure any TypoExprs have been dealt with.
7400     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7401     if (!Res.isUsable())
7402       return ExprError();
7403     CastExpr = Res.get();
7404   }
7405 
7406   checkUnusedDeclAttributes(D);
7407 
7408   QualType castType = castTInfo->getType();
7409   Ty = CreateParsedType(castType, castTInfo);
7410 
7411   bool isVectorLiteral = false;
7412 
7413   // Check for an altivec or OpenCL literal,
7414   // i.e. all the elements are integer constants.
7415   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7416   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7417   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7418        && castType->isVectorType() && (PE || PLE)) {
7419     if (PLE && PLE->getNumExprs() == 0) {
7420       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7421       return ExprError();
7422     }
7423     if (PE || PLE->getNumExprs() == 1) {
7424       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7425       if (!E->getType()->isVectorType())
7426         isVectorLiteral = true;
7427     }
7428     else
7429       isVectorLiteral = true;
7430   }
7431 
7432   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7433   // then handle it as such.
7434   if (isVectorLiteral)
7435     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7436 
7437   // If the Expr being casted is a ParenListExpr, handle it specially.
7438   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7439   // sequence of BinOp comma operators.
7440   if (isa<ParenListExpr>(CastExpr)) {
7441     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7442     if (Result.isInvalid()) return ExprError();
7443     CastExpr = Result.get();
7444   }
7445 
7446   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7447       !getSourceManager().isInSystemMacro(LParenLoc))
7448     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7449 
7450   CheckTollFreeBridgeCast(castType, CastExpr);
7451 
7452   CheckObjCBridgeRelatedCast(castType, CastExpr);
7453 
7454   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7455 
7456   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7457 }
7458 
7459 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7460                                     SourceLocation RParenLoc, Expr *E,
7461                                     TypeSourceInfo *TInfo) {
7462   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7463          "Expected paren or paren list expression");
7464 
7465   Expr **exprs;
7466   unsigned numExprs;
7467   Expr *subExpr;
7468   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7469   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7470     LiteralLParenLoc = PE->getLParenLoc();
7471     LiteralRParenLoc = PE->getRParenLoc();
7472     exprs = PE->getExprs();
7473     numExprs = PE->getNumExprs();
7474   } else { // isa<ParenExpr> by assertion at function entrance
7475     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7476     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7477     subExpr = cast<ParenExpr>(E)->getSubExpr();
7478     exprs = &subExpr;
7479     numExprs = 1;
7480   }
7481 
7482   QualType Ty = TInfo->getType();
7483   assert(Ty->isVectorType() && "Expected vector type");
7484 
7485   SmallVector<Expr *, 8> initExprs;
7486   const VectorType *VTy = Ty->castAs<VectorType>();
7487   unsigned numElems = VTy->getNumElements();
7488 
7489   // '(...)' form of vector initialization in AltiVec: the number of
7490   // initializers must be one or must match the size of the vector.
7491   // If a single value is specified in the initializer then it will be
7492   // replicated to all the components of the vector
7493   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7494     // The number of initializers must be one or must match the size of the
7495     // vector. If a single value is specified in the initializer then it will
7496     // be replicated to all the components of the vector
7497     if (numExprs == 1) {
7498       QualType ElemTy = VTy->getElementType();
7499       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7500       if (Literal.isInvalid())
7501         return ExprError();
7502       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7503                                   PrepareScalarCast(Literal, ElemTy));
7504       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7505     }
7506     else if (numExprs < numElems) {
7507       Diag(E->getExprLoc(),
7508            diag::err_incorrect_number_of_vector_initializers);
7509       return ExprError();
7510     }
7511     else
7512       initExprs.append(exprs, exprs + numExprs);
7513   }
7514   else {
7515     // For OpenCL, when the number of initializers is a single value,
7516     // it will be replicated to all components of the vector.
7517     if (getLangOpts().OpenCL &&
7518         VTy->getVectorKind() == VectorType::GenericVector &&
7519         numExprs == 1) {
7520         QualType ElemTy = VTy->getElementType();
7521         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7522         if (Literal.isInvalid())
7523           return ExprError();
7524         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7525                                     PrepareScalarCast(Literal, ElemTy));
7526         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7527     }
7528 
7529     initExprs.append(exprs, exprs + numExprs);
7530   }
7531   // FIXME: This means that pretty-printing the final AST will produce curly
7532   // braces instead of the original commas.
7533   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7534                                                    initExprs, LiteralRParenLoc);
7535   initE->setType(Ty);
7536   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7537 }
7538 
7539 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7540 /// the ParenListExpr into a sequence of comma binary operators.
7541 ExprResult
7542 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7543   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7544   if (!E)
7545     return OrigExpr;
7546 
7547   ExprResult Result(E->getExpr(0));
7548 
7549   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7550     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7551                         E->getExpr(i));
7552 
7553   if (Result.isInvalid()) return ExprError();
7554 
7555   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7556 }
7557 
7558 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7559                                     SourceLocation R,
7560                                     MultiExprArg Val) {
7561   return ParenListExpr::Create(Context, L, Val, R);
7562 }
7563 
7564 /// Emit a specialized diagnostic when one expression is a null pointer
7565 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7566 /// emitted.
7567 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7568                                       SourceLocation QuestionLoc) {
7569   Expr *NullExpr = LHSExpr;
7570   Expr *NonPointerExpr = RHSExpr;
7571   Expr::NullPointerConstantKind NullKind =
7572       NullExpr->isNullPointerConstant(Context,
7573                                       Expr::NPC_ValueDependentIsNotNull);
7574 
7575   if (NullKind == Expr::NPCK_NotNull) {
7576     NullExpr = RHSExpr;
7577     NonPointerExpr = LHSExpr;
7578     NullKind =
7579         NullExpr->isNullPointerConstant(Context,
7580                                         Expr::NPC_ValueDependentIsNotNull);
7581   }
7582 
7583   if (NullKind == Expr::NPCK_NotNull)
7584     return false;
7585 
7586   if (NullKind == Expr::NPCK_ZeroExpression)
7587     return false;
7588 
7589   if (NullKind == Expr::NPCK_ZeroLiteral) {
7590     // In this case, check to make sure that we got here from a "NULL"
7591     // string in the source code.
7592     NullExpr = NullExpr->IgnoreParenImpCasts();
7593     SourceLocation loc = NullExpr->getExprLoc();
7594     if (!findMacroSpelling(loc, "NULL"))
7595       return false;
7596   }
7597 
7598   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7599   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7600       << NonPointerExpr->getType() << DiagType
7601       << NonPointerExpr->getSourceRange();
7602   return true;
7603 }
7604 
7605 /// Return false if the condition expression is valid, true otherwise.
7606 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7607   QualType CondTy = Cond->getType();
7608 
7609   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7610   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7611     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7612       << CondTy << Cond->getSourceRange();
7613     return true;
7614   }
7615 
7616   // C99 6.5.15p2
7617   if (CondTy->isScalarType()) return false;
7618 
7619   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7620     << CondTy << Cond->getSourceRange();
7621   return true;
7622 }
7623 
7624 /// Handle when one or both operands are void type.
7625 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7626                                          ExprResult &RHS) {
7627     Expr *LHSExpr = LHS.get();
7628     Expr *RHSExpr = RHS.get();
7629 
7630     if (!LHSExpr->getType()->isVoidType())
7631       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7632           << RHSExpr->getSourceRange();
7633     if (!RHSExpr->getType()->isVoidType())
7634       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7635           << LHSExpr->getSourceRange();
7636     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7637     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7638     return S.Context.VoidTy;
7639 }
7640 
7641 /// Return false if the NullExpr can be promoted to PointerTy,
7642 /// true otherwise.
7643 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7644                                         QualType PointerTy) {
7645   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7646       !NullExpr.get()->isNullPointerConstant(S.Context,
7647                                             Expr::NPC_ValueDependentIsNull))
7648     return true;
7649 
7650   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7651   return false;
7652 }
7653 
7654 /// Checks compatibility between two pointers and return the resulting
7655 /// type.
7656 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7657                                                      ExprResult &RHS,
7658                                                      SourceLocation Loc) {
7659   QualType LHSTy = LHS.get()->getType();
7660   QualType RHSTy = RHS.get()->getType();
7661 
7662   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7663     // Two identical pointers types are always compatible.
7664     return LHSTy;
7665   }
7666 
7667   QualType lhptee, rhptee;
7668 
7669   // Get the pointee types.
7670   bool IsBlockPointer = false;
7671   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7672     lhptee = LHSBTy->getPointeeType();
7673     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7674     IsBlockPointer = true;
7675   } else {
7676     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7677     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7678   }
7679 
7680   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7681   // differently qualified versions of compatible types, the result type is
7682   // a pointer to an appropriately qualified version of the composite
7683   // type.
7684 
7685   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7686   // clause doesn't make sense for our extensions. E.g. address space 2 should
7687   // be incompatible with address space 3: they may live on different devices or
7688   // anything.
7689   Qualifiers lhQual = lhptee.getQualifiers();
7690   Qualifiers rhQual = rhptee.getQualifiers();
7691 
7692   LangAS ResultAddrSpace = LangAS::Default;
7693   LangAS LAddrSpace = lhQual.getAddressSpace();
7694   LangAS RAddrSpace = rhQual.getAddressSpace();
7695 
7696   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7697   // spaces is disallowed.
7698   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7699     ResultAddrSpace = LAddrSpace;
7700   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7701     ResultAddrSpace = RAddrSpace;
7702   else {
7703     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7704         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7705         << RHS.get()->getSourceRange();
7706     return QualType();
7707   }
7708 
7709   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7710   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7711   lhQual.removeCVRQualifiers();
7712   rhQual.removeCVRQualifiers();
7713 
7714   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7715   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7716   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7717   // qual types are compatible iff
7718   //  * corresponded types are compatible
7719   //  * CVR qualifiers are equal
7720   //  * address spaces are equal
7721   // Thus for conditional operator we merge CVR and address space unqualified
7722   // pointees and if there is a composite type we return a pointer to it with
7723   // merged qualifiers.
7724   LHSCastKind =
7725       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7726   RHSCastKind =
7727       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7728   lhQual.removeAddressSpace();
7729   rhQual.removeAddressSpace();
7730 
7731   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7732   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7733 
7734   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7735 
7736   if (CompositeTy.isNull()) {
7737     // In this situation, we assume void* type. No especially good
7738     // reason, but this is what gcc does, and we do have to pick
7739     // to get a consistent AST.
7740     QualType incompatTy;
7741     incompatTy = S.Context.getPointerType(
7742         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7743     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7744     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7745 
7746     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7747     // for casts between types with incompatible address space qualifiers.
7748     // For the following code the compiler produces casts between global and
7749     // local address spaces of the corresponded innermost pointees:
7750     // local int *global *a;
7751     // global int *global *b;
7752     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7753     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7754         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7755         << RHS.get()->getSourceRange();
7756 
7757     return incompatTy;
7758   }
7759 
7760   // The pointer types are compatible.
7761   // In case of OpenCL ResultTy should have the address space qualifier
7762   // which is a superset of address spaces of both the 2nd and the 3rd
7763   // operands of the conditional operator.
7764   QualType ResultTy = [&, ResultAddrSpace]() {
7765     if (S.getLangOpts().OpenCL) {
7766       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7767       CompositeQuals.setAddressSpace(ResultAddrSpace);
7768       return S.Context
7769           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7770           .withCVRQualifiers(MergedCVRQual);
7771     }
7772     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7773   }();
7774   if (IsBlockPointer)
7775     ResultTy = S.Context.getBlockPointerType(ResultTy);
7776   else
7777     ResultTy = S.Context.getPointerType(ResultTy);
7778 
7779   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7780   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7781   return ResultTy;
7782 }
7783 
7784 /// Return the resulting type when the operands are both block pointers.
7785 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7786                                                           ExprResult &LHS,
7787                                                           ExprResult &RHS,
7788                                                           SourceLocation Loc) {
7789   QualType LHSTy = LHS.get()->getType();
7790   QualType RHSTy = RHS.get()->getType();
7791 
7792   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7793     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7794       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7795       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7796       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7797       return destType;
7798     }
7799     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7800       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7801       << RHS.get()->getSourceRange();
7802     return QualType();
7803   }
7804 
7805   // We have 2 block pointer types.
7806   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7807 }
7808 
7809 /// Return the resulting type when the operands are both pointers.
7810 static QualType
7811 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7812                                             ExprResult &RHS,
7813                                             SourceLocation Loc) {
7814   // get the pointer types
7815   QualType LHSTy = LHS.get()->getType();
7816   QualType RHSTy = RHS.get()->getType();
7817 
7818   // get the "pointed to" types
7819   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7820   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7821 
7822   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7823   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7824     // Figure out necessary qualifiers (C99 6.5.15p6)
7825     QualType destPointee
7826       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7827     QualType destType = S.Context.getPointerType(destPointee);
7828     // Add qualifiers if necessary.
7829     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7830     // Promote to void*.
7831     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7832     return destType;
7833   }
7834   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7835     QualType destPointee
7836       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7837     QualType destType = S.Context.getPointerType(destPointee);
7838     // Add qualifiers if necessary.
7839     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7840     // Promote to void*.
7841     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7842     return destType;
7843   }
7844 
7845   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7846 }
7847 
7848 /// Return false if the first expression is not an integer and the second
7849 /// expression is not a pointer, true otherwise.
7850 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7851                                         Expr* PointerExpr, SourceLocation Loc,
7852                                         bool IsIntFirstExpr) {
7853   if (!PointerExpr->getType()->isPointerType() ||
7854       !Int.get()->getType()->isIntegerType())
7855     return false;
7856 
7857   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7858   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7859 
7860   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7861     << Expr1->getType() << Expr2->getType()
7862     << Expr1->getSourceRange() << Expr2->getSourceRange();
7863   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7864                             CK_IntegralToPointer);
7865   return true;
7866 }
7867 
7868 /// Simple conversion between integer and floating point types.
7869 ///
7870 /// Used when handling the OpenCL conditional operator where the
7871 /// condition is a vector while the other operands are scalar.
7872 ///
7873 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7874 /// types are either integer or floating type. Between the two
7875 /// operands, the type with the higher rank is defined as the "result
7876 /// type". The other operand needs to be promoted to the same type. No
7877 /// other type promotion is allowed. We cannot use
7878 /// UsualArithmeticConversions() for this purpose, since it always
7879 /// promotes promotable types.
7880 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7881                                             ExprResult &RHS,
7882                                             SourceLocation QuestionLoc) {
7883   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7884   if (LHS.isInvalid())
7885     return QualType();
7886   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7887   if (RHS.isInvalid())
7888     return QualType();
7889 
7890   // For conversion purposes, we ignore any qualifiers.
7891   // For example, "const float" and "float" are equivalent.
7892   QualType LHSType =
7893     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7894   QualType RHSType =
7895     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7896 
7897   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7898     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7899       << LHSType << LHS.get()->getSourceRange();
7900     return QualType();
7901   }
7902 
7903   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7904     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7905       << RHSType << RHS.get()->getSourceRange();
7906     return QualType();
7907   }
7908 
7909   // If both types are identical, no conversion is needed.
7910   if (LHSType == RHSType)
7911     return LHSType;
7912 
7913   // Now handle "real" floating types (i.e. float, double, long double).
7914   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7915     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7916                                  /*IsCompAssign = */ false);
7917 
7918   // Finally, we have two differing integer types.
7919   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7920   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7921 }
7922 
7923 /// Convert scalar operands to a vector that matches the
7924 ///        condition in length.
7925 ///
7926 /// Used when handling the OpenCL conditional operator where the
7927 /// condition is a vector while the other operands are scalar.
7928 ///
7929 /// We first compute the "result type" for the scalar operands
7930 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7931 /// into a vector of that type where the length matches the condition
7932 /// vector type. s6.11.6 requires that the element types of the result
7933 /// and the condition must have the same number of bits.
7934 static QualType
7935 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7936                               QualType CondTy, SourceLocation QuestionLoc) {
7937   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7938   if (ResTy.isNull()) return QualType();
7939 
7940   const VectorType *CV = CondTy->getAs<VectorType>();
7941   assert(CV);
7942 
7943   // Determine the vector result type
7944   unsigned NumElements = CV->getNumElements();
7945   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7946 
7947   // Ensure that all types have the same number of bits
7948   if (S.Context.getTypeSize(CV->getElementType())
7949       != S.Context.getTypeSize(ResTy)) {
7950     // Since VectorTy is created internally, it does not pretty print
7951     // with an OpenCL name. Instead, we just print a description.
7952     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7953     SmallString<64> Str;
7954     llvm::raw_svector_ostream OS(Str);
7955     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7956     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7957       << CondTy << OS.str();
7958     return QualType();
7959   }
7960 
7961   // Convert operands to the vector result type
7962   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7963   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7964 
7965   return VectorTy;
7966 }
7967 
7968 /// Return false if this is a valid OpenCL condition vector
7969 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7970                                        SourceLocation QuestionLoc) {
7971   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7972   // integral type.
7973   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7974   assert(CondTy);
7975   QualType EleTy = CondTy->getElementType();
7976   if (EleTy->isIntegerType()) return false;
7977 
7978   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7979     << Cond->getType() << Cond->getSourceRange();
7980   return true;
7981 }
7982 
7983 /// Return false if the vector condition type and the vector
7984 ///        result type are compatible.
7985 ///
7986 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7987 /// number of elements, and their element types have the same number
7988 /// of bits.
7989 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7990                               SourceLocation QuestionLoc) {
7991   const VectorType *CV = CondTy->getAs<VectorType>();
7992   const VectorType *RV = VecResTy->getAs<VectorType>();
7993   assert(CV && RV);
7994 
7995   if (CV->getNumElements() != RV->getNumElements()) {
7996     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7997       << CondTy << VecResTy;
7998     return true;
7999   }
8000 
8001   QualType CVE = CV->getElementType();
8002   QualType RVE = RV->getElementType();
8003 
8004   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8005     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8006       << CondTy << VecResTy;
8007     return true;
8008   }
8009 
8010   return false;
8011 }
8012 
8013 /// Return the resulting type for the conditional operator in
8014 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8015 ///        s6.3.i) when the condition is a vector type.
8016 static QualType
8017 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8018                              ExprResult &LHS, ExprResult &RHS,
8019                              SourceLocation QuestionLoc) {
8020   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8021   if (Cond.isInvalid())
8022     return QualType();
8023   QualType CondTy = Cond.get()->getType();
8024 
8025   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8026     return QualType();
8027 
8028   // If either operand is a vector then find the vector type of the
8029   // result as specified in OpenCL v1.1 s6.3.i.
8030   if (LHS.get()->getType()->isVectorType() ||
8031       RHS.get()->getType()->isVectorType()) {
8032     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8033                                               /*isCompAssign*/false,
8034                                               /*AllowBothBool*/true,
8035                                               /*AllowBoolConversions*/false);
8036     if (VecResTy.isNull()) return QualType();
8037     // The result type must match the condition type as specified in
8038     // OpenCL v1.1 s6.11.6.
8039     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8040       return QualType();
8041     return VecResTy;
8042   }
8043 
8044   // Both operands are scalar.
8045   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8046 }
8047 
8048 /// Return true if the Expr is block type
8049 static bool checkBlockType(Sema &S, const Expr *E) {
8050   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8051     QualType Ty = CE->getCallee()->getType();
8052     if (Ty->isBlockPointerType()) {
8053       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8054       return true;
8055     }
8056   }
8057   return false;
8058 }
8059 
8060 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8061 /// In that case, LHS = cond.
8062 /// C99 6.5.15
8063 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8064                                         ExprResult &RHS, ExprValueKind &VK,
8065                                         ExprObjectKind &OK,
8066                                         SourceLocation QuestionLoc) {
8067 
8068   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8069   if (!LHSResult.isUsable()) return QualType();
8070   LHS = LHSResult;
8071 
8072   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8073   if (!RHSResult.isUsable()) return QualType();
8074   RHS = RHSResult;
8075 
8076   // C++ is sufficiently different to merit its own checker.
8077   if (getLangOpts().CPlusPlus)
8078     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8079 
8080   VK = VK_RValue;
8081   OK = OK_Ordinary;
8082 
8083   // The OpenCL operator with a vector condition is sufficiently
8084   // different to merit its own checker.
8085   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8086       Cond.get()->getType()->isExtVectorType())
8087     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8088 
8089   // First, check the condition.
8090   Cond = UsualUnaryConversions(Cond.get());
8091   if (Cond.isInvalid())
8092     return QualType();
8093   if (checkCondition(*this, Cond.get(), QuestionLoc))
8094     return QualType();
8095 
8096   // Now check the two expressions.
8097   if (LHS.get()->getType()->isVectorType() ||
8098       RHS.get()->getType()->isVectorType())
8099     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8100                                /*AllowBothBool*/true,
8101                                /*AllowBoolConversions*/false);
8102 
8103   QualType ResTy =
8104       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8105   if (LHS.isInvalid() || RHS.isInvalid())
8106     return QualType();
8107 
8108   QualType LHSTy = LHS.get()->getType();
8109   QualType RHSTy = RHS.get()->getType();
8110 
8111   // Diagnose attempts to convert between __float128 and long double where
8112   // such conversions currently can't be handled.
8113   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8114     Diag(QuestionLoc,
8115          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8116       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8117     return QualType();
8118   }
8119 
8120   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8121   // selection operator (?:).
8122   if (getLangOpts().OpenCL &&
8123       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8124     return QualType();
8125   }
8126 
8127   // If both operands have arithmetic type, do the usual arithmetic conversions
8128   // to find a common type: C99 6.5.15p3,5.
8129   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8130     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8131     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8132 
8133     return ResTy;
8134   }
8135 
8136   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8137   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8138     return LHSTy;
8139   }
8140 
8141   // If both operands are the same structure or union type, the result is that
8142   // type.
8143   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8144     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8145       if (LHSRT->getDecl() == RHSRT->getDecl())
8146         // "If both the operands have structure or union type, the result has
8147         // that type."  This implies that CV qualifiers are dropped.
8148         return LHSTy.getUnqualifiedType();
8149     // FIXME: Type of conditional expression must be complete in C mode.
8150   }
8151 
8152   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8153   // The following || allows only one side to be void (a GCC-ism).
8154   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8155     return checkConditionalVoidType(*this, LHS, RHS);
8156   }
8157 
8158   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8159   // the type of the other operand."
8160   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8161   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8162 
8163   // All objective-c pointer type analysis is done here.
8164   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8165                                                         QuestionLoc);
8166   if (LHS.isInvalid() || RHS.isInvalid())
8167     return QualType();
8168   if (!compositeType.isNull())
8169     return compositeType;
8170 
8171 
8172   // Handle block pointer types.
8173   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8174     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8175                                                      QuestionLoc);
8176 
8177   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8178   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8179     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8180                                                        QuestionLoc);
8181 
8182   // GCC compatibility: soften pointer/integer mismatch.  Note that
8183   // null pointers have been filtered out by this point.
8184   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8185       /*IsIntFirstExpr=*/true))
8186     return RHSTy;
8187   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8188       /*IsIntFirstExpr=*/false))
8189     return LHSTy;
8190 
8191   // Allow ?: operations in which both operands have the same
8192   // built-in sizeless type.
8193   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8194     return LHSTy;
8195 
8196   // Emit a better diagnostic if one of the expressions is a null pointer
8197   // constant and the other is not a pointer type. In this case, the user most
8198   // likely forgot to take the address of the other expression.
8199   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8200     return QualType();
8201 
8202   // Otherwise, the operands are not compatible.
8203   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8204     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8205     << RHS.get()->getSourceRange();
8206   return QualType();
8207 }
8208 
8209 /// FindCompositeObjCPointerType - Helper method to find composite type of
8210 /// two objective-c pointer types of the two input expressions.
8211 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8212                                             SourceLocation QuestionLoc) {
8213   QualType LHSTy = LHS.get()->getType();
8214   QualType RHSTy = RHS.get()->getType();
8215 
8216   // Handle things like Class and struct objc_class*.  Here we case the result
8217   // to the pseudo-builtin, because that will be implicitly cast back to the
8218   // redefinition type if an attempt is made to access its fields.
8219   if (LHSTy->isObjCClassType() &&
8220       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8221     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8222     return LHSTy;
8223   }
8224   if (RHSTy->isObjCClassType() &&
8225       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8226     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8227     return RHSTy;
8228   }
8229   // And the same for struct objc_object* / id
8230   if (LHSTy->isObjCIdType() &&
8231       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8232     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8233     return LHSTy;
8234   }
8235   if (RHSTy->isObjCIdType() &&
8236       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8237     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8238     return RHSTy;
8239   }
8240   // And the same for struct objc_selector* / SEL
8241   if (Context.isObjCSelType(LHSTy) &&
8242       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8243     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8244     return LHSTy;
8245   }
8246   if (Context.isObjCSelType(RHSTy) &&
8247       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8248     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8249     return RHSTy;
8250   }
8251   // Check constraints for Objective-C object pointers types.
8252   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8253 
8254     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8255       // Two identical object pointer types are always compatible.
8256       return LHSTy;
8257     }
8258     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8259     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8260     QualType compositeType = LHSTy;
8261 
8262     // If both operands are interfaces and either operand can be
8263     // assigned to the other, use that type as the composite
8264     // type. This allows
8265     //   xxx ? (A*) a : (B*) b
8266     // where B is a subclass of A.
8267     //
8268     // Additionally, as for assignment, if either type is 'id'
8269     // allow silent coercion. Finally, if the types are
8270     // incompatible then make sure to use 'id' as the composite
8271     // type so the result is acceptable for sending messages to.
8272 
8273     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8274     // It could return the composite type.
8275     if (!(compositeType =
8276           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8277       // Nothing more to do.
8278     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8279       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8280     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8281       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8282     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8283                 RHSOPT->isObjCQualifiedIdType()) &&
8284                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8285                                                          true)) {
8286       // Need to handle "id<xx>" explicitly.
8287       // GCC allows qualified id and any Objective-C type to devolve to
8288       // id. Currently localizing to here until clear this should be
8289       // part of ObjCQualifiedIdTypesAreCompatible.
8290       compositeType = Context.getObjCIdType();
8291     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8292       compositeType = Context.getObjCIdType();
8293     } else {
8294       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8295       << LHSTy << RHSTy
8296       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8297       QualType incompatTy = Context.getObjCIdType();
8298       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8299       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8300       return incompatTy;
8301     }
8302     // The object pointer types are compatible.
8303     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8304     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8305     return compositeType;
8306   }
8307   // Check Objective-C object pointer types and 'void *'
8308   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8309     if (getLangOpts().ObjCAutoRefCount) {
8310       // ARC forbids the implicit conversion of object pointers to 'void *',
8311       // so these types are not compatible.
8312       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8313           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8314       LHS = RHS = true;
8315       return QualType();
8316     }
8317     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8318     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8319     QualType destPointee
8320     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8321     QualType destType = Context.getPointerType(destPointee);
8322     // Add qualifiers if necessary.
8323     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8324     // Promote to void*.
8325     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8326     return destType;
8327   }
8328   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8329     if (getLangOpts().ObjCAutoRefCount) {
8330       // ARC forbids the implicit conversion of object pointers to 'void *',
8331       // so these types are not compatible.
8332       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8333           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8334       LHS = RHS = true;
8335       return QualType();
8336     }
8337     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8338     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8339     QualType destPointee
8340     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8341     QualType destType = Context.getPointerType(destPointee);
8342     // Add qualifiers if necessary.
8343     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8344     // Promote to void*.
8345     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8346     return destType;
8347   }
8348   return QualType();
8349 }
8350 
8351 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8352 /// ParenRange in parentheses.
8353 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8354                                const PartialDiagnostic &Note,
8355                                SourceRange ParenRange) {
8356   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8357   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8358       EndLoc.isValid()) {
8359     Self.Diag(Loc, Note)
8360       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8361       << FixItHint::CreateInsertion(EndLoc, ")");
8362   } else {
8363     // We can't display the parentheses, so just show the bare note.
8364     Self.Diag(Loc, Note) << ParenRange;
8365   }
8366 }
8367 
8368 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8369   return BinaryOperator::isAdditiveOp(Opc) ||
8370          BinaryOperator::isMultiplicativeOp(Opc) ||
8371          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8372   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8373   // not any of the logical operators.  Bitwise-xor is commonly used as a
8374   // logical-xor because there is no logical-xor operator.  The logical
8375   // operators, including uses of xor, have a high false positive rate for
8376   // precedence warnings.
8377 }
8378 
8379 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8380 /// expression, either using a built-in or overloaded operator,
8381 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8382 /// expression.
8383 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8384                                    Expr **RHSExprs) {
8385   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8386   E = E->IgnoreImpCasts();
8387   E = E->IgnoreConversionOperator();
8388   E = E->IgnoreImpCasts();
8389   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8390     E = MTE->getSubExpr();
8391     E = E->IgnoreImpCasts();
8392   }
8393 
8394   // Built-in binary operator.
8395   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8396     if (IsArithmeticOp(OP->getOpcode())) {
8397       *Opcode = OP->getOpcode();
8398       *RHSExprs = OP->getRHS();
8399       return true;
8400     }
8401   }
8402 
8403   // Overloaded operator.
8404   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8405     if (Call->getNumArgs() != 2)
8406       return false;
8407 
8408     // Make sure this is really a binary operator that is safe to pass into
8409     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8410     OverloadedOperatorKind OO = Call->getOperator();
8411     if (OO < OO_Plus || OO > OO_Arrow ||
8412         OO == OO_PlusPlus || OO == OO_MinusMinus)
8413       return false;
8414 
8415     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8416     if (IsArithmeticOp(OpKind)) {
8417       *Opcode = OpKind;
8418       *RHSExprs = Call->getArg(1);
8419       return true;
8420     }
8421   }
8422 
8423   return false;
8424 }
8425 
8426 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8427 /// or is a logical expression such as (x==y) which has int type, but is
8428 /// commonly interpreted as boolean.
8429 static bool ExprLooksBoolean(Expr *E) {
8430   E = E->IgnoreParenImpCasts();
8431 
8432   if (E->getType()->isBooleanType())
8433     return true;
8434   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8435     return OP->isComparisonOp() || OP->isLogicalOp();
8436   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8437     return OP->getOpcode() == UO_LNot;
8438   if (E->getType()->isPointerType())
8439     return true;
8440   // FIXME: What about overloaded operator calls returning "unspecified boolean
8441   // type"s (commonly pointer-to-members)?
8442 
8443   return false;
8444 }
8445 
8446 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8447 /// and binary operator are mixed in a way that suggests the programmer assumed
8448 /// the conditional operator has higher precedence, for example:
8449 /// "int x = a + someBinaryCondition ? 1 : 2".
8450 static void DiagnoseConditionalPrecedence(Sema &Self,
8451                                           SourceLocation OpLoc,
8452                                           Expr *Condition,
8453                                           Expr *LHSExpr,
8454                                           Expr *RHSExpr) {
8455   BinaryOperatorKind CondOpcode;
8456   Expr *CondRHS;
8457 
8458   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8459     return;
8460   if (!ExprLooksBoolean(CondRHS))
8461     return;
8462 
8463   // The condition is an arithmetic binary expression, with a right-
8464   // hand side that looks boolean, so warn.
8465 
8466   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8467                         ? diag::warn_precedence_bitwise_conditional
8468                         : diag::warn_precedence_conditional;
8469 
8470   Self.Diag(OpLoc, DiagID)
8471       << Condition->getSourceRange()
8472       << BinaryOperator::getOpcodeStr(CondOpcode);
8473 
8474   SuggestParentheses(
8475       Self, OpLoc,
8476       Self.PDiag(diag::note_precedence_silence)
8477           << BinaryOperator::getOpcodeStr(CondOpcode),
8478       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8479 
8480   SuggestParentheses(Self, OpLoc,
8481                      Self.PDiag(diag::note_precedence_conditional_first),
8482                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8483 }
8484 
8485 /// Compute the nullability of a conditional expression.
8486 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8487                                               QualType LHSTy, QualType RHSTy,
8488                                               ASTContext &Ctx) {
8489   if (!ResTy->isAnyPointerType())
8490     return ResTy;
8491 
8492   auto GetNullability = [&Ctx](QualType Ty) {
8493     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8494     if (Kind)
8495       return *Kind;
8496     return NullabilityKind::Unspecified;
8497   };
8498 
8499   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8500   NullabilityKind MergedKind;
8501 
8502   // Compute nullability of a binary conditional expression.
8503   if (IsBin) {
8504     if (LHSKind == NullabilityKind::NonNull)
8505       MergedKind = NullabilityKind::NonNull;
8506     else
8507       MergedKind = RHSKind;
8508   // Compute nullability of a normal conditional expression.
8509   } else {
8510     if (LHSKind == NullabilityKind::Nullable ||
8511         RHSKind == NullabilityKind::Nullable)
8512       MergedKind = NullabilityKind::Nullable;
8513     else if (LHSKind == NullabilityKind::NonNull)
8514       MergedKind = RHSKind;
8515     else if (RHSKind == NullabilityKind::NonNull)
8516       MergedKind = LHSKind;
8517     else
8518       MergedKind = NullabilityKind::Unspecified;
8519   }
8520 
8521   // Return if ResTy already has the correct nullability.
8522   if (GetNullability(ResTy) == MergedKind)
8523     return ResTy;
8524 
8525   // Strip all nullability from ResTy.
8526   while (ResTy->getNullability(Ctx))
8527     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8528 
8529   // Create a new AttributedType with the new nullability kind.
8530   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8531   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8532 }
8533 
8534 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8535 /// in the case of a the GNU conditional expr extension.
8536 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8537                                     SourceLocation ColonLoc,
8538                                     Expr *CondExpr, Expr *LHSExpr,
8539                                     Expr *RHSExpr) {
8540   if (!getLangOpts().CPlusPlus) {
8541     // C cannot handle TypoExpr nodes in the condition because it
8542     // doesn't handle dependent types properly, so make sure any TypoExprs have
8543     // been dealt with before checking the operands.
8544     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8545     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8546     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8547 
8548     if (!CondResult.isUsable())
8549       return ExprError();
8550 
8551     if (LHSExpr) {
8552       if (!LHSResult.isUsable())
8553         return ExprError();
8554     }
8555 
8556     if (!RHSResult.isUsable())
8557       return ExprError();
8558 
8559     CondExpr = CondResult.get();
8560     LHSExpr = LHSResult.get();
8561     RHSExpr = RHSResult.get();
8562   }
8563 
8564   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8565   // was the condition.
8566   OpaqueValueExpr *opaqueValue = nullptr;
8567   Expr *commonExpr = nullptr;
8568   if (!LHSExpr) {
8569     commonExpr = CondExpr;
8570     // Lower out placeholder types first.  This is important so that we don't
8571     // try to capture a placeholder. This happens in few cases in C++; such
8572     // as Objective-C++'s dictionary subscripting syntax.
8573     if (commonExpr->hasPlaceholderType()) {
8574       ExprResult result = CheckPlaceholderExpr(commonExpr);
8575       if (!result.isUsable()) return ExprError();
8576       commonExpr = result.get();
8577     }
8578     // We usually want to apply unary conversions *before* saving, except
8579     // in the special case of a C++ l-value conditional.
8580     if (!(getLangOpts().CPlusPlus
8581           && !commonExpr->isTypeDependent()
8582           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8583           && commonExpr->isGLValue()
8584           && commonExpr->isOrdinaryOrBitFieldObject()
8585           && RHSExpr->isOrdinaryOrBitFieldObject()
8586           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8587       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8588       if (commonRes.isInvalid())
8589         return ExprError();
8590       commonExpr = commonRes.get();
8591     }
8592 
8593     // If the common expression is a class or array prvalue, materialize it
8594     // so that we can safely refer to it multiple times.
8595     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8596                                    commonExpr->getType()->isArrayType())) {
8597       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8598       if (MatExpr.isInvalid())
8599         return ExprError();
8600       commonExpr = MatExpr.get();
8601     }
8602 
8603     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8604                                                 commonExpr->getType(),
8605                                                 commonExpr->getValueKind(),
8606                                                 commonExpr->getObjectKind(),
8607                                                 commonExpr);
8608     LHSExpr = CondExpr = opaqueValue;
8609   }
8610 
8611   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8612   ExprValueKind VK = VK_RValue;
8613   ExprObjectKind OK = OK_Ordinary;
8614   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8615   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8616                                              VK, OK, QuestionLoc);
8617   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8618       RHS.isInvalid())
8619     return ExprError();
8620 
8621   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8622                                 RHS.get());
8623 
8624   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8625 
8626   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8627                                          Context);
8628 
8629   if (!commonExpr)
8630     return new (Context)
8631         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8632                             RHS.get(), result, VK, OK);
8633 
8634   return new (Context) BinaryConditionalOperator(
8635       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8636       ColonLoc, result, VK, OK);
8637 }
8638 
8639 // Check if we have a conversion between incompatible cmse function pointer
8640 // types, that is, a conversion between a function pointer with the
8641 // cmse_nonsecure_call attribute and one without.
8642 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8643                                           QualType ToType) {
8644   if (const auto *ToFn =
8645           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8646     if (const auto *FromFn =
8647             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8648       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8649       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8650 
8651       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8652     }
8653   }
8654   return false;
8655 }
8656 
8657 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8658 // being closely modeled after the C99 spec:-). The odd characteristic of this
8659 // routine is it effectively iqnores the qualifiers on the top level pointee.
8660 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8661 // FIXME: add a couple examples in this comment.
8662 static Sema::AssignConvertType
8663 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8664   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8665   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8666 
8667   // get the "pointed to" type (ignoring qualifiers at the top level)
8668   const Type *lhptee, *rhptee;
8669   Qualifiers lhq, rhq;
8670   std::tie(lhptee, lhq) =
8671       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8672   std::tie(rhptee, rhq) =
8673       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8674 
8675   Sema::AssignConvertType ConvTy = Sema::Compatible;
8676 
8677   // C99 6.5.16.1p1: This following citation is common to constraints
8678   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8679   // qualifiers of the type *pointed to* by the right;
8680 
8681   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8682   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8683       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8684     // Ignore lifetime for further calculation.
8685     lhq.removeObjCLifetime();
8686     rhq.removeObjCLifetime();
8687   }
8688 
8689   if (!lhq.compatiblyIncludes(rhq)) {
8690     // Treat address-space mismatches as fatal.
8691     if (!lhq.isAddressSpaceSupersetOf(rhq))
8692       return Sema::IncompatiblePointerDiscardsQualifiers;
8693 
8694     // It's okay to add or remove GC or lifetime qualifiers when converting to
8695     // and from void*.
8696     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8697                         .compatiblyIncludes(
8698                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8699              && (lhptee->isVoidType() || rhptee->isVoidType()))
8700       ; // keep old
8701 
8702     // Treat lifetime mismatches as fatal.
8703     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8704       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8705 
8706     // For GCC/MS compatibility, other qualifier mismatches are treated
8707     // as still compatible in C.
8708     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8709   }
8710 
8711   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8712   // incomplete type and the other is a pointer to a qualified or unqualified
8713   // version of void...
8714   if (lhptee->isVoidType()) {
8715     if (rhptee->isIncompleteOrObjectType())
8716       return ConvTy;
8717 
8718     // As an extension, we allow cast to/from void* to function pointer.
8719     assert(rhptee->isFunctionType());
8720     return Sema::FunctionVoidPointer;
8721   }
8722 
8723   if (rhptee->isVoidType()) {
8724     if (lhptee->isIncompleteOrObjectType())
8725       return ConvTy;
8726 
8727     // As an extension, we allow cast to/from void* to function pointer.
8728     assert(lhptee->isFunctionType());
8729     return Sema::FunctionVoidPointer;
8730   }
8731 
8732   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8733   // unqualified versions of compatible types, ...
8734   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8735   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8736     // Check if the pointee types are compatible ignoring the sign.
8737     // We explicitly check for char so that we catch "char" vs
8738     // "unsigned char" on systems where "char" is unsigned.
8739     if (lhptee->isCharType())
8740       ltrans = S.Context.UnsignedCharTy;
8741     else if (lhptee->hasSignedIntegerRepresentation())
8742       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8743 
8744     if (rhptee->isCharType())
8745       rtrans = S.Context.UnsignedCharTy;
8746     else if (rhptee->hasSignedIntegerRepresentation())
8747       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8748 
8749     if (ltrans == rtrans) {
8750       // Types are compatible ignoring the sign. Qualifier incompatibility
8751       // takes priority over sign incompatibility because the sign
8752       // warning can be disabled.
8753       if (ConvTy != Sema::Compatible)
8754         return ConvTy;
8755 
8756       return Sema::IncompatiblePointerSign;
8757     }
8758 
8759     // If we are a multi-level pointer, it's possible that our issue is simply
8760     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8761     // the eventual target type is the same and the pointers have the same
8762     // level of indirection, this must be the issue.
8763     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8764       do {
8765         std::tie(lhptee, lhq) =
8766           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8767         std::tie(rhptee, rhq) =
8768           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8769 
8770         // Inconsistent address spaces at this point is invalid, even if the
8771         // address spaces would be compatible.
8772         // FIXME: This doesn't catch address space mismatches for pointers of
8773         // different nesting levels, like:
8774         //   __local int *** a;
8775         //   int ** b = a;
8776         // It's not clear how to actually determine when such pointers are
8777         // invalidly incompatible.
8778         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8779           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8780 
8781       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8782 
8783       if (lhptee == rhptee)
8784         return Sema::IncompatibleNestedPointerQualifiers;
8785     }
8786 
8787     // General pointer incompatibility takes priority over qualifiers.
8788     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8789       return Sema::IncompatibleFunctionPointer;
8790     return Sema::IncompatiblePointer;
8791   }
8792   if (!S.getLangOpts().CPlusPlus &&
8793       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8794     return Sema::IncompatibleFunctionPointer;
8795   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8796     return Sema::IncompatibleFunctionPointer;
8797   return ConvTy;
8798 }
8799 
8800 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8801 /// block pointer types are compatible or whether a block and normal pointer
8802 /// are compatible. It is more restrict than comparing two function pointer
8803 // types.
8804 static Sema::AssignConvertType
8805 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8806                                     QualType RHSType) {
8807   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8808   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8809 
8810   QualType lhptee, rhptee;
8811 
8812   // get the "pointed to" type (ignoring qualifiers at the top level)
8813   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8814   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8815 
8816   // In C++, the types have to match exactly.
8817   if (S.getLangOpts().CPlusPlus)
8818     return Sema::IncompatibleBlockPointer;
8819 
8820   Sema::AssignConvertType ConvTy = Sema::Compatible;
8821 
8822   // For blocks we enforce that qualifiers are identical.
8823   Qualifiers LQuals = lhptee.getLocalQualifiers();
8824   Qualifiers RQuals = rhptee.getLocalQualifiers();
8825   if (S.getLangOpts().OpenCL) {
8826     LQuals.removeAddressSpace();
8827     RQuals.removeAddressSpace();
8828   }
8829   if (LQuals != RQuals)
8830     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8831 
8832   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8833   // assignment.
8834   // The current behavior is similar to C++ lambdas. A block might be
8835   // assigned to a variable iff its return type and parameters are compatible
8836   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8837   // an assignment. Presumably it should behave in way that a function pointer
8838   // assignment does in C, so for each parameter and return type:
8839   //  * CVR and address space of LHS should be a superset of CVR and address
8840   //  space of RHS.
8841   //  * unqualified types should be compatible.
8842   if (S.getLangOpts().OpenCL) {
8843     if (!S.Context.typesAreBlockPointerCompatible(
8844             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8845             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8846       return Sema::IncompatibleBlockPointer;
8847   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8848     return Sema::IncompatibleBlockPointer;
8849 
8850   return ConvTy;
8851 }
8852 
8853 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8854 /// for assignment compatibility.
8855 static Sema::AssignConvertType
8856 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8857                                    QualType RHSType) {
8858   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8859   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8860 
8861   if (LHSType->isObjCBuiltinType()) {
8862     // Class is not compatible with ObjC object pointers.
8863     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8864         !RHSType->isObjCQualifiedClassType())
8865       return Sema::IncompatiblePointer;
8866     return Sema::Compatible;
8867   }
8868   if (RHSType->isObjCBuiltinType()) {
8869     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8870         !LHSType->isObjCQualifiedClassType())
8871       return Sema::IncompatiblePointer;
8872     return Sema::Compatible;
8873   }
8874   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8875   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8876 
8877   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8878       // make an exception for id<P>
8879       !LHSType->isObjCQualifiedIdType())
8880     return Sema::CompatiblePointerDiscardsQualifiers;
8881 
8882   if (S.Context.typesAreCompatible(LHSType, RHSType))
8883     return Sema::Compatible;
8884   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8885     return Sema::IncompatibleObjCQualifiedId;
8886   return Sema::IncompatiblePointer;
8887 }
8888 
8889 Sema::AssignConvertType
8890 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8891                                  QualType LHSType, QualType RHSType) {
8892   // Fake up an opaque expression.  We don't actually care about what
8893   // cast operations are required, so if CheckAssignmentConstraints
8894   // adds casts to this they'll be wasted, but fortunately that doesn't
8895   // usually happen on valid code.
8896   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8897   ExprResult RHSPtr = &RHSExpr;
8898   CastKind K;
8899 
8900   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8901 }
8902 
8903 /// This helper function returns true if QT is a vector type that has element
8904 /// type ElementType.
8905 static bool isVector(QualType QT, QualType ElementType) {
8906   if (const VectorType *VT = QT->getAs<VectorType>())
8907     return VT->getElementType().getCanonicalType() == ElementType;
8908   return false;
8909 }
8910 
8911 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8912 /// has code to accommodate several GCC extensions when type checking
8913 /// pointers. Here are some objectionable examples that GCC considers warnings:
8914 ///
8915 ///  int a, *pint;
8916 ///  short *pshort;
8917 ///  struct foo *pfoo;
8918 ///
8919 ///  pint = pshort; // warning: assignment from incompatible pointer type
8920 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8921 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8922 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8923 ///
8924 /// As a result, the code for dealing with pointers is more complex than the
8925 /// C99 spec dictates.
8926 ///
8927 /// Sets 'Kind' for any result kind except Incompatible.
8928 Sema::AssignConvertType
8929 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8930                                  CastKind &Kind, bool ConvertRHS) {
8931   QualType RHSType = RHS.get()->getType();
8932   QualType OrigLHSType = LHSType;
8933 
8934   // Get canonical types.  We're not formatting these types, just comparing
8935   // them.
8936   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8937   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8938 
8939   // Common case: no conversion required.
8940   if (LHSType == RHSType) {
8941     Kind = CK_NoOp;
8942     return Compatible;
8943   }
8944 
8945   // If we have an atomic type, try a non-atomic assignment, then just add an
8946   // atomic qualification step.
8947   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8948     Sema::AssignConvertType result =
8949       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8950     if (result != Compatible)
8951       return result;
8952     if (Kind != CK_NoOp && ConvertRHS)
8953       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8954     Kind = CK_NonAtomicToAtomic;
8955     return Compatible;
8956   }
8957 
8958   // If the left-hand side is a reference type, then we are in a
8959   // (rare!) case where we've allowed the use of references in C,
8960   // e.g., as a parameter type in a built-in function. In this case,
8961   // just make sure that the type referenced is compatible with the
8962   // right-hand side type. The caller is responsible for adjusting
8963   // LHSType so that the resulting expression does not have reference
8964   // type.
8965   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8966     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8967       Kind = CK_LValueBitCast;
8968       return Compatible;
8969     }
8970     return Incompatible;
8971   }
8972 
8973   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8974   // to the same ExtVector type.
8975   if (LHSType->isExtVectorType()) {
8976     if (RHSType->isExtVectorType())
8977       return Incompatible;
8978     if (RHSType->isArithmeticType()) {
8979       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8980       if (ConvertRHS)
8981         RHS = prepareVectorSplat(LHSType, RHS.get());
8982       Kind = CK_VectorSplat;
8983       return Compatible;
8984     }
8985   }
8986 
8987   // Conversions to or from vector type.
8988   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8989     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8990       // Allow assignments of an AltiVec vector type to an equivalent GCC
8991       // vector type and vice versa
8992       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8993         Kind = CK_BitCast;
8994         return Compatible;
8995       }
8996 
8997       // If we are allowing lax vector conversions, and LHS and RHS are both
8998       // vectors, the total size only needs to be the same. This is a bitcast;
8999       // no bits are changed but the result type is different.
9000       if (isLaxVectorConversion(RHSType, LHSType)) {
9001         Kind = CK_BitCast;
9002         return IncompatibleVectors;
9003       }
9004     }
9005 
9006     // When the RHS comes from another lax conversion (e.g. binops between
9007     // scalars and vectors) the result is canonicalized as a vector. When the
9008     // LHS is also a vector, the lax is allowed by the condition above. Handle
9009     // the case where LHS is a scalar.
9010     if (LHSType->isScalarType()) {
9011       const VectorType *VecType = RHSType->getAs<VectorType>();
9012       if (VecType && VecType->getNumElements() == 1 &&
9013           isLaxVectorConversion(RHSType, LHSType)) {
9014         ExprResult *VecExpr = &RHS;
9015         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9016         Kind = CK_BitCast;
9017         return Compatible;
9018       }
9019     }
9020 
9021     return Incompatible;
9022   }
9023 
9024   // Diagnose attempts to convert between __float128 and long double where
9025   // such conversions currently can't be handled.
9026   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9027     return Incompatible;
9028 
9029   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9030   // discards the imaginary part.
9031   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9032       !LHSType->getAs<ComplexType>())
9033     return Incompatible;
9034 
9035   // Arithmetic conversions.
9036   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9037       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9038     if (ConvertRHS)
9039       Kind = PrepareScalarCast(RHS, LHSType);
9040     return Compatible;
9041   }
9042 
9043   // Conversions to normal pointers.
9044   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9045     // U* -> T*
9046     if (isa<PointerType>(RHSType)) {
9047       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9048       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9049       if (AddrSpaceL != AddrSpaceR)
9050         Kind = CK_AddressSpaceConversion;
9051       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9052         Kind = CK_NoOp;
9053       else
9054         Kind = CK_BitCast;
9055       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9056     }
9057 
9058     // int -> T*
9059     if (RHSType->isIntegerType()) {
9060       Kind = CK_IntegralToPointer; // FIXME: null?
9061       return IntToPointer;
9062     }
9063 
9064     // C pointers are not compatible with ObjC object pointers,
9065     // with two exceptions:
9066     if (isa<ObjCObjectPointerType>(RHSType)) {
9067       //  - conversions to void*
9068       if (LHSPointer->getPointeeType()->isVoidType()) {
9069         Kind = CK_BitCast;
9070         return Compatible;
9071       }
9072 
9073       //  - conversions from 'Class' to the redefinition type
9074       if (RHSType->isObjCClassType() &&
9075           Context.hasSameType(LHSType,
9076                               Context.getObjCClassRedefinitionType())) {
9077         Kind = CK_BitCast;
9078         return Compatible;
9079       }
9080 
9081       Kind = CK_BitCast;
9082       return IncompatiblePointer;
9083     }
9084 
9085     // U^ -> void*
9086     if (RHSType->getAs<BlockPointerType>()) {
9087       if (LHSPointer->getPointeeType()->isVoidType()) {
9088         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9089         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9090                                 ->getPointeeType()
9091                                 .getAddressSpace();
9092         Kind =
9093             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9094         return Compatible;
9095       }
9096     }
9097 
9098     return Incompatible;
9099   }
9100 
9101   // Conversions to block pointers.
9102   if (isa<BlockPointerType>(LHSType)) {
9103     // U^ -> T^
9104     if (RHSType->isBlockPointerType()) {
9105       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9106                               ->getPointeeType()
9107                               .getAddressSpace();
9108       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9109                               ->getPointeeType()
9110                               .getAddressSpace();
9111       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9112       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9113     }
9114 
9115     // int or null -> T^
9116     if (RHSType->isIntegerType()) {
9117       Kind = CK_IntegralToPointer; // FIXME: null
9118       return IntToBlockPointer;
9119     }
9120 
9121     // id -> T^
9122     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9123       Kind = CK_AnyPointerToBlockPointerCast;
9124       return Compatible;
9125     }
9126 
9127     // void* -> T^
9128     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9129       if (RHSPT->getPointeeType()->isVoidType()) {
9130         Kind = CK_AnyPointerToBlockPointerCast;
9131         return Compatible;
9132       }
9133 
9134     return Incompatible;
9135   }
9136 
9137   // Conversions to Objective-C pointers.
9138   if (isa<ObjCObjectPointerType>(LHSType)) {
9139     // A* -> B*
9140     if (RHSType->isObjCObjectPointerType()) {
9141       Kind = CK_BitCast;
9142       Sema::AssignConvertType result =
9143         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9144       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9145           result == Compatible &&
9146           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9147         result = IncompatibleObjCWeakRef;
9148       return result;
9149     }
9150 
9151     // int or null -> A*
9152     if (RHSType->isIntegerType()) {
9153       Kind = CK_IntegralToPointer; // FIXME: null
9154       return IntToPointer;
9155     }
9156 
9157     // In general, C pointers are not compatible with ObjC object pointers,
9158     // with two exceptions:
9159     if (isa<PointerType>(RHSType)) {
9160       Kind = CK_CPointerToObjCPointerCast;
9161 
9162       //  - conversions from 'void*'
9163       if (RHSType->isVoidPointerType()) {
9164         return Compatible;
9165       }
9166 
9167       //  - conversions to 'Class' from its redefinition type
9168       if (LHSType->isObjCClassType() &&
9169           Context.hasSameType(RHSType,
9170                               Context.getObjCClassRedefinitionType())) {
9171         return Compatible;
9172       }
9173 
9174       return IncompatiblePointer;
9175     }
9176 
9177     // Only under strict condition T^ is compatible with an Objective-C pointer.
9178     if (RHSType->isBlockPointerType() &&
9179         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9180       if (ConvertRHS)
9181         maybeExtendBlockObject(RHS);
9182       Kind = CK_BlockPointerToObjCPointerCast;
9183       return Compatible;
9184     }
9185 
9186     return Incompatible;
9187   }
9188 
9189   // Conversions from pointers that are not covered by the above.
9190   if (isa<PointerType>(RHSType)) {
9191     // T* -> _Bool
9192     if (LHSType == Context.BoolTy) {
9193       Kind = CK_PointerToBoolean;
9194       return Compatible;
9195     }
9196 
9197     // T* -> int
9198     if (LHSType->isIntegerType()) {
9199       Kind = CK_PointerToIntegral;
9200       return PointerToInt;
9201     }
9202 
9203     return Incompatible;
9204   }
9205 
9206   // Conversions from Objective-C pointers that are not covered by the above.
9207   if (isa<ObjCObjectPointerType>(RHSType)) {
9208     // T* -> _Bool
9209     if (LHSType == Context.BoolTy) {
9210       Kind = CK_PointerToBoolean;
9211       return Compatible;
9212     }
9213 
9214     // T* -> int
9215     if (LHSType->isIntegerType()) {
9216       Kind = CK_PointerToIntegral;
9217       return PointerToInt;
9218     }
9219 
9220     return Incompatible;
9221   }
9222 
9223   // struct A -> struct B
9224   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9225     if (Context.typesAreCompatible(LHSType, RHSType)) {
9226       Kind = CK_NoOp;
9227       return Compatible;
9228     }
9229   }
9230 
9231   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9232     Kind = CK_IntToOCLSampler;
9233     return Compatible;
9234   }
9235 
9236   return Incompatible;
9237 }
9238 
9239 /// Constructs a transparent union from an expression that is
9240 /// used to initialize the transparent union.
9241 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9242                                       ExprResult &EResult, QualType UnionType,
9243                                       FieldDecl *Field) {
9244   // Build an initializer list that designates the appropriate member
9245   // of the transparent union.
9246   Expr *E = EResult.get();
9247   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9248                                                    E, SourceLocation());
9249   Initializer->setType(UnionType);
9250   Initializer->setInitializedFieldInUnion(Field);
9251 
9252   // Build a compound literal constructing a value of the transparent
9253   // union type from this initializer list.
9254   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9255   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9256                                         VK_RValue, Initializer, false);
9257 }
9258 
9259 Sema::AssignConvertType
9260 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9261                                                ExprResult &RHS) {
9262   QualType RHSType = RHS.get()->getType();
9263 
9264   // If the ArgType is a Union type, we want to handle a potential
9265   // transparent_union GCC extension.
9266   const RecordType *UT = ArgType->getAsUnionType();
9267   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9268     return Incompatible;
9269 
9270   // The field to initialize within the transparent union.
9271   RecordDecl *UD = UT->getDecl();
9272   FieldDecl *InitField = nullptr;
9273   // It's compatible if the expression matches any of the fields.
9274   for (auto *it : UD->fields()) {
9275     if (it->getType()->isPointerType()) {
9276       // If the transparent union contains a pointer type, we allow:
9277       // 1) void pointer
9278       // 2) null pointer constant
9279       if (RHSType->isPointerType())
9280         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9281           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9282           InitField = it;
9283           break;
9284         }
9285 
9286       if (RHS.get()->isNullPointerConstant(Context,
9287                                            Expr::NPC_ValueDependentIsNull)) {
9288         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9289                                 CK_NullToPointer);
9290         InitField = it;
9291         break;
9292       }
9293     }
9294 
9295     CastKind Kind;
9296     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9297           == Compatible) {
9298       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9299       InitField = it;
9300       break;
9301     }
9302   }
9303 
9304   if (!InitField)
9305     return Incompatible;
9306 
9307   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9308   return Compatible;
9309 }
9310 
9311 Sema::AssignConvertType
9312 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9313                                        bool Diagnose,
9314                                        bool DiagnoseCFAudited,
9315                                        bool ConvertRHS) {
9316   // We need to be able to tell the caller whether we diagnosed a problem, if
9317   // they ask us to issue diagnostics.
9318   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9319 
9320   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9321   // we can't avoid *all* modifications at the moment, so we need some somewhere
9322   // to put the updated value.
9323   ExprResult LocalRHS = CallerRHS;
9324   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9325 
9326   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9327     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9328       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9329           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9330         Diag(RHS.get()->getExprLoc(),
9331              diag::warn_noderef_to_dereferenceable_pointer)
9332             << RHS.get()->getSourceRange();
9333       }
9334     }
9335   }
9336 
9337   if (getLangOpts().CPlusPlus) {
9338     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9339       // C++ 5.17p3: If the left operand is not of class type, the
9340       // expression is implicitly converted (C++ 4) to the
9341       // cv-unqualified type of the left operand.
9342       QualType RHSType = RHS.get()->getType();
9343       if (Diagnose) {
9344         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9345                                         AA_Assigning);
9346       } else {
9347         ImplicitConversionSequence ICS =
9348             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9349                                   /*SuppressUserConversions=*/false,
9350                                   AllowedExplicit::None,
9351                                   /*InOverloadResolution=*/false,
9352                                   /*CStyle=*/false,
9353                                   /*AllowObjCWritebackConversion=*/false);
9354         if (ICS.isFailure())
9355           return Incompatible;
9356         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9357                                         ICS, AA_Assigning);
9358       }
9359       if (RHS.isInvalid())
9360         return Incompatible;
9361       Sema::AssignConvertType result = Compatible;
9362       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9363           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9364         result = IncompatibleObjCWeakRef;
9365       return result;
9366     }
9367 
9368     // FIXME: Currently, we fall through and treat C++ classes like C
9369     // structures.
9370     // FIXME: We also fall through for atomics; not sure what should
9371     // happen there, though.
9372   } else if (RHS.get()->getType() == Context.OverloadTy) {
9373     // As a set of extensions to C, we support overloading on functions. These
9374     // functions need to be resolved here.
9375     DeclAccessPair DAP;
9376     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9377             RHS.get(), LHSType, /*Complain=*/false, DAP))
9378       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9379     else
9380       return Incompatible;
9381   }
9382 
9383   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9384   // a null pointer constant.
9385   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9386        LHSType->isBlockPointerType()) &&
9387       RHS.get()->isNullPointerConstant(Context,
9388                                        Expr::NPC_ValueDependentIsNull)) {
9389     if (Diagnose || ConvertRHS) {
9390       CastKind Kind;
9391       CXXCastPath Path;
9392       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9393                              /*IgnoreBaseAccess=*/false, Diagnose);
9394       if (ConvertRHS)
9395         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9396     }
9397     return Compatible;
9398   }
9399 
9400   // OpenCL queue_t type assignment.
9401   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9402                                  Context, Expr::NPC_ValueDependentIsNull)) {
9403     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9404     return Compatible;
9405   }
9406 
9407   // This check seems unnatural, however it is necessary to ensure the proper
9408   // conversion of functions/arrays. If the conversion were done for all
9409   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9410   // expressions that suppress this implicit conversion (&, sizeof).
9411   //
9412   // Suppress this for references: C++ 8.5.3p5.
9413   if (!LHSType->isReferenceType()) {
9414     // FIXME: We potentially allocate here even if ConvertRHS is false.
9415     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9416     if (RHS.isInvalid())
9417       return Incompatible;
9418   }
9419   CastKind Kind;
9420   Sema::AssignConvertType result =
9421     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9422 
9423   // C99 6.5.16.1p2: The value of the right operand is converted to the
9424   // type of the assignment expression.
9425   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9426   // so that we can use references in built-in functions even in C.
9427   // The getNonReferenceType() call makes sure that the resulting expression
9428   // does not have reference type.
9429   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9430     QualType Ty = LHSType.getNonLValueExprType(Context);
9431     Expr *E = RHS.get();
9432 
9433     // Check for various Objective-C errors. If we are not reporting
9434     // diagnostics and just checking for errors, e.g., during overload
9435     // resolution, return Incompatible to indicate the failure.
9436     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9437         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9438                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9439       if (!Diagnose)
9440         return Incompatible;
9441     }
9442     if (getLangOpts().ObjC &&
9443         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9444                                            E->getType(), E, Diagnose) ||
9445          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9446       if (!Diagnose)
9447         return Incompatible;
9448       // Replace the expression with a corrected version and continue so we
9449       // can find further errors.
9450       RHS = E;
9451       return Compatible;
9452     }
9453 
9454     if (ConvertRHS)
9455       RHS = ImpCastExprToType(E, Ty, Kind);
9456   }
9457 
9458   return result;
9459 }
9460 
9461 namespace {
9462 /// The original operand to an operator, prior to the application of the usual
9463 /// arithmetic conversions and converting the arguments of a builtin operator
9464 /// candidate.
9465 struct OriginalOperand {
9466   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9467     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9468       Op = MTE->getSubExpr();
9469     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9470       Op = BTE->getSubExpr();
9471     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9472       Orig = ICE->getSubExprAsWritten();
9473       Conversion = ICE->getConversionFunction();
9474     }
9475   }
9476 
9477   QualType getType() const { return Orig->getType(); }
9478 
9479   Expr *Orig;
9480   NamedDecl *Conversion;
9481 };
9482 }
9483 
9484 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9485                                ExprResult &RHS) {
9486   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9487 
9488   Diag(Loc, diag::err_typecheck_invalid_operands)
9489     << OrigLHS.getType() << OrigRHS.getType()
9490     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9491 
9492   // If a user-defined conversion was applied to either of the operands prior
9493   // to applying the built-in operator rules, tell the user about it.
9494   if (OrigLHS.Conversion) {
9495     Diag(OrigLHS.Conversion->getLocation(),
9496          diag::note_typecheck_invalid_operands_converted)
9497       << 0 << LHS.get()->getType();
9498   }
9499   if (OrigRHS.Conversion) {
9500     Diag(OrigRHS.Conversion->getLocation(),
9501          diag::note_typecheck_invalid_operands_converted)
9502       << 1 << RHS.get()->getType();
9503   }
9504 
9505   return QualType();
9506 }
9507 
9508 // Diagnose cases where a scalar was implicitly converted to a vector and
9509 // diagnose the underlying types. Otherwise, diagnose the error
9510 // as invalid vector logical operands for non-C++ cases.
9511 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9512                                             ExprResult &RHS) {
9513   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9514   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9515 
9516   bool LHSNatVec = LHSType->isVectorType();
9517   bool RHSNatVec = RHSType->isVectorType();
9518 
9519   if (!(LHSNatVec && RHSNatVec)) {
9520     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9521     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9522     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9523         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9524         << Vector->getSourceRange();
9525     return QualType();
9526   }
9527 
9528   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9529       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9530       << RHS.get()->getSourceRange();
9531 
9532   return QualType();
9533 }
9534 
9535 /// Try to convert a value of non-vector type to a vector type by converting
9536 /// the type to the element type of the vector and then performing a splat.
9537 /// If the language is OpenCL, we only use conversions that promote scalar
9538 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9539 /// for float->int.
9540 ///
9541 /// OpenCL V2.0 6.2.6.p2:
9542 /// An error shall occur if any scalar operand type has greater rank
9543 /// than the type of the vector element.
9544 ///
9545 /// \param scalar - if non-null, actually perform the conversions
9546 /// \return true if the operation fails (but without diagnosing the failure)
9547 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9548                                      QualType scalarTy,
9549                                      QualType vectorEltTy,
9550                                      QualType vectorTy,
9551                                      unsigned &DiagID) {
9552   // The conversion to apply to the scalar before splatting it,
9553   // if necessary.
9554   CastKind scalarCast = CK_NoOp;
9555 
9556   if (vectorEltTy->isIntegralType(S.Context)) {
9557     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9558         (scalarTy->isIntegerType() &&
9559          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9560       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9561       return true;
9562     }
9563     if (!scalarTy->isIntegralType(S.Context))
9564       return true;
9565     scalarCast = CK_IntegralCast;
9566   } else if (vectorEltTy->isRealFloatingType()) {
9567     if (scalarTy->isRealFloatingType()) {
9568       if (S.getLangOpts().OpenCL &&
9569           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9570         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9571         return true;
9572       }
9573       scalarCast = CK_FloatingCast;
9574     }
9575     else if (scalarTy->isIntegralType(S.Context))
9576       scalarCast = CK_IntegralToFloating;
9577     else
9578       return true;
9579   } else {
9580     return true;
9581   }
9582 
9583   // Adjust scalar if desired.
9584   if (scalar) {
9585     if (scalarCast != CK_NoOp)
9586       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9587     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9588   }
9589   return false;
9590 }
9591 
9592 /// Convert vector E to a vector with the same number of elements but different
9593 /// element type.
9594 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9595   const auto *VecTy = E->getType()->getAs<VectorType>();
9596   assert(VecTy && "Expression E must be a vector");
9597   QualType NewVecTy = S.Context.getVectorType(ElementType,
9598                                               VecTy->getNumElements(),
9599                                               VecTy->getVectorKind());
9600 
9601   // Look through the implicit cast. Return the subexpression if its type is
9602   // NewVecTy.
9603   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9604     if (ICE->getSubExpr()->getType() == NewVecTy)
9605       return ICE->getSubExpr();
9606 
9607   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9608   return S.ImpCastExprToType(E, NewVecTy, Cast);
9609 }
9610 
9611 /// Test if a (constant) integer Int can be casted to another integer type
9612 /// IntTy without losing precision.
9613 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9614                                       QualType OtherIntTy) {
9615   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9616 
9617   // Reject cases where the value of the Int is unknown as that would
9618   // possibly cause truncation, but accept cases where the scalar can be
9619   // demoted without loss of precision.
9620   Expr::EvalResult EVResult;
9621   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9622   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9623   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9624   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9625 
9626   if (CstInt) {
9627     // If the scalar is constant and is of a higher order and has more active
9628     // bits that the vector element type, reject it.
9629     llvm::APSInt Result = EVResult.Val.getInt();
9630     unsigned NumBits = IntSigned
9631                            ? (Result.isNegative() ? Result.getMinSignedBits()
9632                                                   : Result.getActiveBits())
9633                            : Result.getActiveBits();
9634     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9635       return true;
9636 
9637     // If the signedness of the scalar type and the vector element type
9638     // differs and the number of bits is greater than that of the vector
9639     // element reject it.
9640     return (IntSigned != OtherIntSigned &&
9641             NumBits > S.Context.getIntWidth(OtherIntTy));
9642   }
9643 
9644   // Reject cases where the value of the scalar is not constant and it's
9645   // order is greater than that of the vector element type.
9646   return (Order < 0);
9647 }
9648 
9649 /// Test if a (constant) integer Int can be casted to floating point type
9650 /// FloatTy without losing precision.
9651 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9652                                      QualType FloatTy) {
9653   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9654 
9655   // Determine if the integer constant can be expressed as a floating point
9656   // number of the appropriate type.
9657   Expr::EvalResult EVResult;
9658   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9659 
9660   uint64_t Bits = 0;
9661   if (CstInt) {
9662     // Reject constants that would be truncated if they were converted to
9663     // the floating point type. Test by simple to/from conversion.
9664     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9665     //        could be avoided if there was a convertFromAPInt method
9666     //        which could signal back if implicit truncation occurred.
9667     llvm::APSInt Result = EVResult.Val.getInt();
9668     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9669     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9670                            llvm::APFloat::rmTowardZero);
9671     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9672                              !IntTy->hasSignedIntegerRepresentation());
9673     bool Ignored = false;
9674     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9675                            &Ignored);
9676     if (Result != ConvertBack)
9677       return true;
9678   } else {
9679     // Reject types that cannot be fully encoded into the mantissa of
9680     // the float.
9681     Bits = S.Context.getTypeSize(IntTy);
9682     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9683         S.Context.getFloatTypeSemantics(FloatTy));
9684     if (Bits > FloatPrec)
9685       return true;
9686   }
9687 
9688   return false;
9689 }
9690 
9691 /// Attempt to convert and splat Scalar into a vector whose types matches
9692 /// Vector following GCC conversion rules. The rule is that implicit
9693 /// conversion can occur when Scalar can be casted to match Vector's element
9694 /// type without causing truncation of Scalar.
9695 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9696                                         ExprResult *Vector) {
9697   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9698   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9699   const VectorType *VT = VectorTy->getAs<VectorType>();
9700 
9701   assert(!isa<ExtVectorType>(VT) &&
9702          "ExtVectorTypes should not be handled here!");
9703 
9704   QualType VectorEltTy = VT->getElementType();
9705 
9706   // Reject cases where the vector element type or the scalar element type are
9707   // not integral or floating point types.
9708   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9709     return true;
9710 
9711   // The conversion to apply to the scalar before splatting it,
9712   // if necessary.
9713   CastKind ScalarCast = CK_NoOp;
9714 
9715   // Accept cases where the vector elements are integers and the scalar is
9716   // an integer.
9717   // FIXME: Notionally if the scalar was a floating point value with a precise
9718   //        integral representation, we could cast it to an appropriate integer
9719   //        type and then perform the rest of the checks here. GCC will perform
9720   //        this conversion in some cases as determined by the input language.
9721   //        We should accept it on a language independent basis.
9722   if (VectorEltTy->isIntegralType(S.Context) &&
9723       ScalarTy->isIntegralType(S.Context) &&
9724       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9725 
9726     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9727       return true;
9728 
9729     ScalarCast = CK_IntegralCast;
9730   } else if (VectorEltTy->isIntegralType(S.Context) &&
9731              ScalarTy->isRealFloatingType()) {
9732     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9733       ScalarCast = CK_FloatingToIntegral;
9734     else
9735       return true;
9736   } else if (VectorEltTy->isRealFloatingType()) {
9737     if (ScalarTy->isRealFloatingType()) {
9738 
9739       // Reject cases where the scalar type is not a constant and has a higher
9740       // Order than the vector element type.
9741       llvm::APFloat Result(0.0);
9742 
9743       // Determine whether this is a constant scalar. In the event that the
9744       // value is dependent (and thus cannot be evaluated by the constant
9745       // evaluator), skip the evaluation. This will then diagnose once the
9746       // expression is instantiated.
9747       bool CstScalar = Scalar->get()->isValueDependent() ||
9748                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9749       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9750       if (!CstScalar && Order < 0)
9751         return true;
9752 
9753       // If the scalar cannot be safely casted to the vector element type,
9754       // reject it.
9755       if (CstScalar) {
9756         bool Truncated = false;
9757         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9758                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9759         if (Truncated)
9760           return true;
9761       }
9762 
9763       ScalarCast = CK_FloatingCast;
9764     } else if (ScalarTy->isIntegralType(S.Context)) {
9765       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9766         return true;
9767 
9768       ScalarCast = CK_IntegralToFloating;
9769     } else
9770       return true;
9771   } else if (ScalarTy->isEnumeralType())
9772     return true;
9773 
9774   // Adjust scalar if desired.
9775   if (Scalar) {
9776     if (ScalarCast != CK_NoOp)
9777       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9778     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9779   }
9780   return false;
9781 }
9782 
9783 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9784                                    SourceLocation Loc, bool IsCompAssign,
9785                                    bool AllowBothBool,
9786                                    bool AllowBoolConversions) {
9787   if (!IsCompAssign) {
9788     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9789     if (LHS.isInvalid())
9790       return QualType();
9791   }
9792   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9793   if (RHS.isInvalid())
9794     return QualType();
9795 
9796   // For conversion purposes, we ignore any qualifiers.
9797   // For example, "const float" and "float" are equivalent.
9798   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9799   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9800 
9801   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9802   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9803   assert(LHSVecType || RHSVecType);
9804 
9805   // AltiVec-style "vector bool op vector bool" combinations are allowed
9806   // for some operators but not others.
9807   if (!AllowBothBool &&
9808       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9809       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9810     return InvalidOperands(Loc, LHS, RHS);
9811 
9812   // If the vector types are identical, return.
9813   if (Context.hasSameType(LHSType, RHSType))
9814     return LHSType;
9815 
9816   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9817   if (LHSVecType && RHSVecType &&
9818       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9819     if (isa<ExtVectorType>(LHSVecType)) {
9820       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9821       return LHSType;
9822     }
9823 
9824     if (!IsCompAssign)
9825       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9826     return RHSType;
9827   }
9828 
9829   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9830   // can be mixed, with the result being the non-bool type.  The non-bool
9831   // operand must have integer element type.
9832   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9833       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9834       (Context.getTypeSize(LHSVecType->getElementType()) ==
9835        Context.getTypeSize(RHSVecType->getElementType()))) {
9836     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9837         LHSVecType->getElementType()->isIntegerType() &&
9838         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9839       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9840       return LHSType;
9841     }
9842     if (!IsCompAssign &&
9843         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9844         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9845         RHSVecType->getElementType()->isIntegerType()) {
9846       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9847       return RHSType;
9848     }
9849   }
9850 
9851   // If there's a vector type and a scalar, try to convert the scalar to
9852   // the vector element type and splat.
9853   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9854   if (!RHSVecType) {
9855     if (isa<ExtVectorType>(LHSVecType)) {
9856       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9857                                     LHSVecType->getElementType(), LHSType,
9858                                     DiagID))
9859         return LHSType;
9860     } else {
9861       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9862         return LHSType;
9863     }
9864   }
9865   if (!LHSVecType) {
9866     if (isa<ExtVectorType>(RHSVecType)) {
9867       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9868                                     LHSType, RHSVecType->getElementType(),
9869                                     RHSType, DiagID))
9870         return RHSType;
9871     } else {
9872       if (LHS.get()->getValueKind() == VK_LValue ||
9873           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9874         return RHSType;
9875     }
9876   }
9877 
9878   // FIXME: The code below also handles conversion between vectors and
9879   // non-scalars, we should break this down into fine grained specific checks
9880   // and emit proper diagnostics.
9881   QualType VecType = LHSVecType ? LHSType : RHSType;
9882   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9883   QualType OtherType = LHSVecType ? RHSType : LHSType;
9884   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9885   if (isLaxVectorConversion(OtherType, VecType)) {
9886     // If we're allowing lax vector conversions, only the total (data) size
9887     // needs to be the same. For non compound assignment, if one of the types is
9888     // scalar, the result is always the vector type.
9889     if (!IsCompAssign) {
9890       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9891       return VecType;
9892     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9893     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9894     // type. Note that this is already done by non-compound assignments in
9895     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9896     // <1 x T> -> T. The result is also a vector type.
9897     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9898                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9899       ExprResult *RHSExpr = &RHS;
9900       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9901       return VecType;
9902     }
9903   }
9904 
9905   // Okay, the expression is invalid.
9906 
9907   // If there's a non-vector, non-real operand, diagnose that.
9908   if ((!RHSVecType && !RHSType->isRealType()) ||
9909       (!LHSVecType && !LHSType->isRealType())) {
9910     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9911       << LHSType << RHSType
9912       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9913     return QualType();
9914   }
9915 
9916   // OpenCL V1.1 6.2.6.p1:
9917   // If the operands are of more than one vector type, then an error shall
9918   // occur. Implicit conversions between vector types are not permitted, per
9919   // section 6.2.1.
9920   if (getLangOpts().OpenCL &&
9921       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9922       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9923     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9924                                                            << RHSType;
9925     return QualType();
9926   }
9927 
9928 
9929   // If there is a vector type that is not a ExtVector and a scalar, we reach
9930   // this point if scalar could not be converted to the vector's element type
9931   // without truncation.
9932   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9933       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9934     QualType Scalar = LHSVecType ? RHSType : LHSType;
9935     QualType Vector = LHSVecType ? LHSType : RHSType;
9936     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9937     Diag(Loc,
9938          diag::err_typecheck_vector_not_convertable_implict_truncation)
9939         << ScalarOrVector << Scalar << Vector;
9940 
9941     return QualType();
9942   }
9943 
9944   // Otherwise, use the generic diagnostic.
9945   Diag(Loc, DiagID)
9946     << LHSType << RHSType
9947     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9948   return QualType();
9949 }
9950 
9951 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9952 // expression.  These are mainly cases where the null pointer is used as an
9953 // integer instead of a pointer.
9954 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9955                                 SourceLocation Loc, bool IsCompare) {
9956   // The canonical way to check for a GNU null is with isNullPointerConstant,
9957   // but we use a bit of a hack here for speed; this is a relatively
9958   // hot path, and isNullPointerConstant is slow.
9959   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9960   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9961 
9962   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9963 
9964   // Avoid analyzing cases where the result will either be invalid (and
9965   // diagnosed as such) or entirely valid and not something to warn about.
9966   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9967       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9968     return;
9969 
9970   // Comparison operations would not make sense with a null pointer no matter
9971   // what the other expression is.
9972   if (!IsCompare) {
9973     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9974         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9975         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9976     return;
9977   }
9978 
9979   // The rest of the operations only make sense with a null pointer
9980   // if the other expression is a pointer.
9981   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9982       NonNullType->canDecayToPointerType())
9983     return;
9984 
9985   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9986       << LHSNull /* LHS is NULL */ << NonNullType
9987       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9988 }
9989 
9990 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9991                                           SourceLocation Loc) {
9992   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9993   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9994   if (!LUE || !RUE)
9995     return;
9996   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9997       RUE->getKind() != UETT_SizeOf)
9998     return;
9999 
10000   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10001   QualType LHSTy = LHSArg->getType();
10002   QualType RHSTy;
10003 
10004   if (RUE->isArgumentType())
10005     RHSTy = RUE->getArgumentType();
10006   else
10007     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10008 
10009   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10010     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10011       return;
10012 
10013     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10014     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10015       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10016         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10017             << LHSArgDecl;
10018     }
10019   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10020     QualType ArrayElemTy = ArrayTy->getElementType();
10021     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10022         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10023         ArrayElemTy->isCharType() ||
10024         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10025       return;
10026     S.Diag(Loc, diag::warn_division_sizeof_array)
10027         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10028     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10029       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10030         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10031             << LHSArgDecl;
10032     }
10033 
10034     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10035   }
10036 }
10037 
10038 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10039                                                ExprResult &RHS,
10040                                                SourceLocation Loc, bool IsDiv) {
10041   // Check for division/remainder by zero.
10042   Expr::EvalResult RHSValue;
10043   if (!RHS.get()->isValueDependent() &&
10044       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10045       RHSValue.Val.getInt() == 0)
10046     S.DiagRuntimeBehavior(Loc, RHS.get(),
10047                           S.PDiag(diag::warn_remainder_division_by_zero)
10048                             << IsDiv << RHS.get()->getSourceRange());
10049 }
10050 
10051 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10052                                            SourceLocation Loc,
10053                                            bool IsCompAssign, bool IsDiv) {
10054   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10055 
10056   if (LHS.get()->getType()->isVectorType() ||
10057       RHS.get()->getType()->isVectorType())
10058     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10059                                /*AllowBothBool*/getLangOpts().AltiVec,
10060                                /*AllowBoolConversions*/false);
10061   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10062                  RHS.get()->getType()->isConstantMatrixType()))
10063     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10064 
10065   QualType compType = UsualArithmeticConversions(
10066       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10067   if (LHS.isInvalid() || RHS.isInvalid())
10068     return QualType();
10069 
10070 
10071   if (compType.isNull() || !compType->isArithmeticType())
10072     return InvalidOperands(Loc, LHS, RHS);
10073   if (IsDiv) {
10074     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10075     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10076   }
10077   return compType;
10078 }
10079 
10080 QualType Sema::CheckRemainderOperands(
10081   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10082   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10083 
10084   if (LHS.get()->getType()->isVectorType() ||
10085       RHS.get()->getType()->isVectorType()) {
10086     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10087         RHS.get()->getType()->hasIntegerRepresentation())
10088       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10089                                  /*AllowBothBool*/getLangOpts().AltiVec,
10090                                  /*AllowBoolConversions*/false);
10091     return InvalidOperands(Loc, LHS, RHS);
10092   }
10093 
10094   QualType compType = UsualArithmeticConversions(
10095       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10096   if (LHS.isInvalid() || RHS.isInvalid())
10097     return QualType();
10098 
10099   if (compType.isNull() || !compType->isIntegerType())
10100     return InvalidOperands(Loc, LHS, RHS);
10101   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10102   return compType;
10103 }
10104 
10105 /// Diagnose invalid arithmetic on two void pointers.
10106 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10107                                                 Expr *LHSExpr, Expr *RHSExpr) {
10108   S.Diag(Loc, S.getLangOpts().CPlusPlus
10109                 ? diag::err_typecheck_pointer_arith_void_type
10110                 : diag::ext_gnu_void_ptr)
10111     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10112                             << RHSExpr->getSourceRange();
10113 }
10114 
10115 /// Diagnose invalid arithmetic on a void pointer.
10116 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10117                                             Expr *Pointer) {
10118   S.Diag(Loc, S.getLangOpts().CPlusPlus
10119                 ? diag::err_typecheck_pointer_arith_void_type
10120                 : diag::ext_gnu_void_ptr)
10121     << 0 /* one pointer */ << Pointer->getSourceRange();
10122 }
10123 
10124 /// Diagnose invalid arithmetic on a null pointer.
10125 ///
10126 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10127 /// idiom, which we recognize as a GNU extension.
10128 ///
10129 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10130                                             Expr *Pointer, bool IsGNUIdiom) {
10131   if (IsGNUIdiom)
10132     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10133       << Pointer->getSourceRange();
10134   else
10135     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10136       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10137 }
10138 
10139 /// Diagnose invalid arithmetic on two function pointers.
10140 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10141                                                     Expr *LHS, Expr *RHS) {
10142   assert(LHS->getType()->isAnyPointerType());
10143   assert(RHS->getType()->isAnyPointerType());
10144   S.Diag(Loc, S.getLangOpts().CPlusPlus
10145                 ? diag::err_typecheck_pointer_arith_function_type
10146                 : diag::ext_gnu_ptr_func_arith)
10147     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10148     // We only show the second type if it differs from the first.
10149     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10150                                                    RHS->getType())
10151     << RHS->getType()->getPointeeType()
10152     << LHS->getSourceRange() << RHS->getSourceRange();
10153 }
10154 
10155 /// Diagnose invalid arithmetic on a function pointer.
10156 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10157                                                 Expr *Pointer) {
10158   assert(Pointer->getType()->isAnyPointerType());
10159   S.Diag(Loc, S.getLangOpts().CPlusPlus
10160                 ? diag::err_typecheck_pointer_arith_function_type
10161                 : diag::ext_gnu_ptr_func_arith)
10162     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10163     << 0 /* one pointer, so only one type */
10164     << Pointer->getSourceRange();
10165 }
10166 
10167 /// Emit error if Operand is incomplete pointer type
10168 ///
10169 /// \returns True if pointer has incomplete type
10170 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10171                                                  Expr *Operand) {
10172   QualType ResType = Operand->getType();
10173   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10174     ResType = ResAtomicType->getValueType();
10175 
10176   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10177   QualType PointeeTy = ResType->getPointeeType();
10178   return S.RequireCompleteSizedType(
10179       Loc, PointeeTy,
10180       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10181       Operand->getSourceRange());
10182 }
10183 
10184 /// Check the validity of an arithmetic pointer operand.
10185 ///
10186 /// If the operand has pointer type, this code will check for pointer types
10187 /// which are invalid in arithmetic operations. These will be diagnosed
10188 /// appropriately, including whether or not the use is supported as an
10189 /// extension.
10190 ///
10191 /// \returns True when the operand is valid to use (even if as an extension).
10192 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10193                                             Expr *Operand) {
10194   QualType ResType = Operand->getType();
10195   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10196     ResType = ResAtomicType->getValueType();
10197 
10198   if (!ResType->isAnyPointerType()) return true;
10199 
10200   QualType PointeeTy = ResType->getPointeeType();
10201   if (PointeeTy->isVoidType()) {
10202     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10203     return !S.getLangOpts().CPlusPlus;
10204   }
10205   if (PointeeTy->isFunctionType()) {
10206     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10207     return !S.getLangOpts().CPlusPlus;
10208   }
10209 
10210   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10211 
10212   return true;
10213 }
10214 
10215 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10216 /// operands.
10217 ///
10218 /// This routine will diagnose any invalid arithmetic on pointer operands much
10219 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10220 /// for emitting a single diagnostic even for operations where both LHS and RHS
10221 /// are (potentially problematic) pointers.
10222 ///
10223 /// \returns True when the operand is valid to use (even if as an extension).
10224 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10225                                                 Expr *LHSExpr, Expr *RHSExpr) {
10226   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10227   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10228   if (!isLHSPointer && !isRHSPointer) return true;
10229 
10230   QualType LHSPointeeTy, RHSPointeeTy;
10231   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10232   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10233 
10234   // if both are pointers check if operation is valid wrt address spaces
10235   if (isLHSPointer && isRHSPointer) {
10236     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10237       S.Diag(Loc,
10238              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10239           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10240           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10241       return false;
10242     }
10243   }
10244 
10245   // Check for arithmetic on pointers to incomplete types.
10246   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10247   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10248   if (isLHSVoidPtr || isRHSVoidPtr) {
10249     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10250     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10251     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10252 
10253     return !S.getLangOpts().CPlusPlus;
10254   }
10255 
10256   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10257   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10258   if (isLHSFuncPtr || isRHSFuncPtr) {
10259     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10260     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10261                                                                 RHSExpr);
10262     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10263 
10264     return !S.getLangOpts().CPlusPlus;
10265   }
10266 
10267   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10268     return false;
10269   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10270     return false;
10271 
10272   return true;
10273 }
10274 
10275 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10276 /// literal.
10277 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10278                                   Expr *LHSExpr, Expr *RHSExpr) {
10279   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10280   Expr* IndexExpr = RHSExpr;
10281   if (!StrExpr) {
10282     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10283     IndexExpr = LHSExpr;
10284   }
10285 
10286   bool IsStringPlusInt = StrExpr &&
10287       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10288   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10289     return;
10290 
10291   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10292   Self.Diag(OpLoc, diag::warn_string_plus_int)
10293       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10294 
10295   // Only print a fixit for "str" + int, not for int + "str".
10296   if (IndexExpr == RHSExpr) {
10297     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10298     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10299         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10300         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10301         << FixItHint::CreateInsertion(EndLoc, "]");
10302   } else
10303     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10304 }
10305 
10306 /// Emit a warning when adding a char literal to a string.
10307 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10308                                    Expr *LHSExpr, Expr *RHSExpr) {
10309   const Expr *StringRefExpr = LHSExpr;
10310   const CharacterLiteral *CharExpr =
10311       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10312 
10313   if (!CharExpr) {
10314     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10315     StringRefExpr = RHSExpr;
10316   }
10317 
10318   if (!CharExpr || !StringRefExpr)
10319     return;
10320 
10321   const QualType StringType = StringRefExpr->getType();
10322 
10323   // Return if not a PointerType.
10324   if (!StringType->isAnyPointerType())
10325     return;
10326 
10327   // Return if not a CharacterType.
10328   if (!StringType->getPointeeType()->isAnyCharacterType())
10329     return;
10330 
10331   ASTContext &Ctx = Self.getASTContext();
10332   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10333 
10334   const QualType CharType = CharExpr->getType();
10335   if (!CharType->isAnyCharacterType() &&
10336       CharType->isIntegerType() &&
10337       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10338     Self.Diag(OpLoc, diag::warn_string_plus_char)
10339         << DiagRange << Ctx.CharTy;
10340   } else {
10341     Self.Diag(OpLoc, diag::warn_string_plus_char)
10342         << DiagRange << CharExpr->getType();
10343   }
10344 
10345   // Only print a fixit for str + char, not for char + str.
10346   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10347     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10348     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10349         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10350         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10351         << FixItHint::CreateInsertion(EndLoc, "]");
10352   } else {
10353     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10354   }
10355 }
10356 
10357 /// Emit error when two pointers are incompatible.
10358 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10359                                            Expr *LHSExpr, Expr *RHSExpr) {
10360   assert(LHSExpr->getType()->isAnyPointerType());
10361   assert(RHSExpr->getType()->isAnyPointerType());
10362   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10363     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10364     << RHSExpr->getSourceRange();
10365 }
10366 
10367 // C99 6.5.6
10368 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10369                                      SourceLocation Loc, BinaryOperatorKind Opc,
10370                                      QualType* CompLHSTy) {
10371   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10372 
10373   if (LHS.get()->getType()->isVectorType() ||
10374       RHS.get()->getType()->isVectorType()) {
10375     QualType compType = CheckVectorOperands(
10376         LHS, RHS, Loc, CompLHSTy,
10377         /*AllowBothBool*/getLangOpts().AltiVec,
10378         /*AllowBoolConversions*/getLangOpts().ZVector);
10379     if (CompLHSTy) *CompLHSTy = compType;
10380     return compType;
10381   }
10382 
10383   if (LHS.get()->getType()->isConstantMatrixType() ||
10384       RHS.get()->getType()->isConstantMatrixType()) {
10385     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10386   }
10387 
10388   QualType compType = UsualArithmeticConversions(
10389       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10390   if (LHS.isInvalid() || RHS.isInvalid())
10391     return QualType();
10392 
10393   // Diagnose "string literal" '+' int and string '+' "char literal".
10394   if (Opc == BO_Add) {
10395     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10396     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10397   }
10398 
10399   // handle the common case first (both operands are arithmetic).
10400   if (!compType.isNull() && compType->isArithmeticType()) {
10401     if (CompLHSTy) *CompLHSTy = compType;
10402     return compType;
10403   }
10404 
10405   // Type-checking.  Ultimately the pointer's going to be in PExp;
10406   // note that we bias towards the LHS being the pointer.
10407   Expr *PExp = LHS.get(), *IExp = RHS.get();
10408 
10409   bool isObjCPointer;
10410   if (PExp->getType()->isPointerType()) {
10411     isObjCPointer = false;
10412   } else if (PExp->getType()->isObjCObjectPointerType()) {
10413     isObjCPointer = true;
10414   } else {
10415     std::swap(PExp, IExp);
10416     if (PExp->getType()->isPointerType()) {
10417       isObjCPointer = false;
10418     } else if (PExp->getType()->isObjCObjectPointerType()) {
10419       isObjCPointer = true;
10420     } else {
10421       return InvalidOperands(Loc, LHS, RHS);
10422     }
10423   }
10424   assert(PExp->getType()->isAnyPointerType());
10425 
10426   if (!IExp->getType()->isIntegerType())
10427     return InvalidOperands(Loc, LHS, RHS);
10428 
10429   // Adding to a null pointer results in undefined behavior.
10430   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10431           Context, Expr::NPC_ValueDependentIsNotNull)) {
10432     // In C++ adding zero to a null pointer is defined.
10433     Expr::EvalResult KnownVal;
10434     if (!getLangOpts().CPlusPlus ||
10435         (!IExp->isValueDependent() &&
10436          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10437           KnownVal.Val.getInt() != 0))) {
10438       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10439       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10440           Context, BO_Add, PExp, IExp);
10441       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10442     }
10443   }
10444 
10445   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10446     return QualType();
10447 
10448   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10449     return QualType();
10450 
10451   // Check array bounds for pointer arithemtic
10452   CheckArrayAccess(PExp, IExp);
10453 
10454   if (CompLHSTy) {
10455     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10456     if (LHSTy.isNull()) {
10457       LHSTy = LHS.get()->getType();
10458       if (LHSTy->isPromotableIntegerType())
10459         LHSTy = Context.getPromotedIntegerType(LHSTy);
10460     }
10461     *CompLHSTy = LHSTy;
10462   }
10463 
10464   return PExp->getType();
10465 }
10466 
10467 // C99 6.5.6
10468 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10469                                         SourceLocation Loc,
10470                                         QualType* CompLHSTy) {
10471   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10472 
10473   if (LHS.get()->getType()->isVectorType() ||
10474       RHS.get()->getType()->isVectorType()) {
10475     QualType compType = CheckVectorOperands(
10476         LHS, RHS, Loc, CompLHSTy,
10477         /*AllowBothBool*/getLangOpts().AltiVec,
10478         /*AllowBoolConversions*/getLangOpts().ZVector);
10479     if (CompLHSTy) *CompLHSTy = compType;
10480     return compType;
10481   }
10482 
10483   if (LHS.get()->getType()->isConstantMatrixType() ||
10484       RHS.get()->getType()->isConstantMatrixType()) {
10485     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10486   }
10487 
10488   QualType compType = UsualArithmeticConversions(
10489       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10490   if (LHS.isInvalid() || RHS.isInvalid())
10491     return QualType();
10492 
10493   // Enforce type constraints: C99 6.5.6p3.
10494 
10495   // Handle the common case first (both operands are arithmetic).
10496   if (!compType.isNull() && compType->isArithmeticType()) {
10497     if (CompLHSTy) *CompLHSTy = compType;
10498     return compType;
10499   }
10500 
10501   // Either ptr - int   or   ptr - ptr.
10502   if (LHS.get()->getType()->isAnyPointerType()) {
10503     QualType lpointee = LHS.get()->getType()->getPointeeType();
10504 
10505     // Diagnose bad cases where we step over interface counts.
10506     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10507         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10508       return QualType();
10509 
10510     // The result type of a pointer-int computation is the pointer type.
10511     if (RHS.get()->getType()->isIntegerType()) {
10512       // Subtracting from a null pointer should produce a warning.
10513       // The last argument to the diagnose call says this doesn't match the
10514       // GNU int-to-pointer idiom.
10515       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10516                                            Expr::NPC_ValueDependentIsNotNull)) {
10517         // In C++ adding zero to a null pointer is defined.
10518         Expr::EvalResult KnownVal;
10519         if (!getLangOpts().CPlusPlus ||
10520             (!RHS.get()->isValueDependent() &&
10521              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10522               KnownVal.Val.getInt() != 0))) {
10523           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10524         }
10525       }
10526 
10527       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10528         return QualType();
10529 
10530       // Check array bounds for pointer arithemtic
10531       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10532                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10533 
10534       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10535       return LHS.get()->getType();
10536     }
10537 
10538     // Handle pointer-pointer subtractions.
10539     if (const PointerType *RHSPTy
10540           = RHS.get()->getType()->getAs<PointerType>()) {
10541       QualType rpointee = RHSPTy->getPointeeType();
10542 
10543       if (getLangOpts().CPlusPlus) {
10544         // Pointee types must be the same: C++ [expr.add]
10545         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10546           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10547         }
10548       } else {
10549         // Pointee types must be compatible C99 6.5.6p3
10550         if (!Context.typesAreCompatible(
10551                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10552                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10553           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10554           return QualType();
10555         }
10556       }
10557 
10558       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10559                                                LHS.get(), RHS.get()))
10560         return QualType();
10561 
10562       // FIXME: Add warnings for nullptr - ptr.
10563 
10564       // The pointee type may have zero size.  As an extension, a structure or
10565       // union may have zero size or an array may have zero length.  In this
10566       // case subtraction does not make sense.
10567       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10568         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10569         if (ElementSize.isZero()) {
10570           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10571             << rpointee.getUnqualifiedType()
10572             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10573         }
10574       }
10575 
10576       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10577       return Context.getPointerDiffType();
10578     }
10579   }
10580 
10581   return InvalidOperands(Loc, LHS, RHS);
10582 }
10583 
10584 static bool isScopedEnumerationType(QualType T) {
10585   if (const EnumType *ET = T->getAs<EnumType>())
10586     return ET->getDecl()->isScoped();
10587   return false;
10588 }
10589 
10590 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10591                                    SourceLocation Loc, BinaryOperatorKind Opc,
10592                                    QualType LHSType) {
10593   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10594   // so skip remaining warnings as we don't want to modify values within Sema.
10595   if (S.getLangOpts().OpenCL)
10596     return;
10597 
10598   // Check right/shifter operand
10599   Expr::EvalResult RHSResult;
10600   if (RHS.get()->isValueDependent() ||
10601       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10602     return;
10603   llvm::APSInt Right = RHSResult.Val.getInt();
10604 
10605   if (Right.isNegative()) {
10606     S.DiagRuntimeBehavior(Loc, RHS.get(),
10607                           S.PDiag(diag::warn_shift_negative)
10608                             << RHS.get()->getSourceRange());
10609     return;
10610   }
10611 
10612   QualType LHSExprType = LHS.get()->getType();
10613   uint64_t LeftSize = LHSExprType->isExtIntType()
10614                           ? S.Context.getIntWidth(LHSExprType)
10615                           : S.Context.getTypeSize(LHSExprType);
10616   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10617   if (Right.uge(LeftBits)) {
10618     S.DiagRuntimeBehavior(Loc, RHS.get(),
10619                           S.PDiag(diag::warn_shift_gt_typewidth)
10620                             << RHS.get()->getSourceRange());
10621     return;
10622   }
10623 
10624   if (Opc != BO_Shl)
10625     return;
10626 
10627   // When left shifting an ICE which is signed, we can check for overflow which
10628   // according to C++ standards prior to C++2a has undefined behavior
10629   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10630   // more than the maximum value representable in the result type, so never
10631   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10632   // expression is still probably a bug.)
10633   Expr::EvalResult LHSResult;
10634   if (LHS.get()->isValueDependent() ||
10635       LHSType->hasUnsignedIntegerRepresentation() ||
10636       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10637     return;
10638   llvm::APSInt Left = LHSResult.Val.getInt();
10639 
10640   // If LHS does not have a signed type and non-negative value
10641   // then, the behavior is undefined before C++2a. Warn about it.
10642   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10643       !S.getLangOpts().CPlusPlus20) {
10644     S.DiagRuntimeBehavior(Loc, LHS.get(),
10645                           S.PDiag(diag::warn_shift_lhs_negative)
10646                             << LHS.get()->getSourceRange());
10647     return;
10648   }
10649 
10650   llvm::APInt ResultBits =
10651       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10652   if (LeftBits.uge(ResultBits))
10653     return;
10654   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10655   Result = Result.shl(Right);
10656 
10657   // Print the bit representation of the signed integer as an unsigned
10658   // hexadecimal number.
10659   SmallString<40> HexResult;
10660   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10661 
10662   // If we are only missing a sign bit, this is less likely to result in actual
10663   // bugs -- if the result is cast back to an unsigned type, it will have the
10664   // expected value. Thus we place this behind a different warning that can be
10665   // turned off separately if needed.
10666   if (LeftBits == ResultBits - 1) {
10667     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10668         << HexResult << LHSType
10669         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10670     return;
10671   }
10672 
10673   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10674     << HexResult.str() << Result.getMinSignedBits() << LHSType
10675     << Left.getBitWidth() << LHS.get()->getSourceRange()
10676     << RHS.get()->getSourceRange();
10677 }
10678 
10679 /// Return the resulting type when a vector is shifted
10680 ///        by a scalar or vector shift amount.
10681 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10682                                  SourceLocation Loc, bool IsCompAssign) {
10683   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10684   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10685       !LHS.get()->getType()->isVectorType()) {
10686     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10687       << RHS.get()->getType() << LHS.get()->getType()
10688       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10689     return QualType();
10690   }
10691 
10692   if (!IsCompAssign) {
10693     LHS = S.UsualUnaryConversions(LHS.get());
10694     if (LHS.isInvalid()) return QualType();
10695   }
10696 
10697   RHS = S.UsualUnaryConversions(RHS.get());
10698   if (RHS.isInvalid()) return QualType();
10699 
10700   QualType LHSType = LHS.get()->getType();
10701   // Note that LHS might be a scalar because the routine calls not only in
10702   // OpenCL case.
10703   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10704   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10705 
10706   // Note that RHS might not be a vector.
10707   QualType RHSType = RHS.get()->getType();
10708   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10709   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10710 
10711   // The operands need to be integers.
10712   if (!LHSEleType->isIntegerType()) {
10713     S.Diag(Loc, diag::err_typecheck_expect_int)
10714       << LHS.get()->getType() << LHS.get()->getSourceRange();
10715     return QualType();
10716   }
10717 
10718   if (!RHSEleType->isIntegerType()) {
10719     S.Diag(Loc, diag::err_typecheck_expect_int)
10720       << RHS.get()->getType() << RHS.get()->getSourceRange();
10721     return QualType();
10722   }
10723 
10724   if (!LHSVecTy) {
10725     assert(RHSVecTy);
10726     if (IsCompAssign)
10727       return RHSType;
10728     if (LHSEleType != RHSEleType) {
10729       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10730       LHSEleType = RHSEleType;
10731     }
10732     QualType VecTy =
10733         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10734     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10735     LHSType = VecTy;
10736   } else if (RHSVecTy) {
10737     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10738     // are applied component-wise. So if RHS is a vector, then ensure
10739     // that the number of elements is the same as LHS...
10740     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10741       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10742         << LHS.get()->getType() << RHS.get()->getType()
10743         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10744       return QualType();
10745     }
10746     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10747       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10748       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10749       if (LHSBT != RHSBT &&
10750           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10751         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10752             << LHS.get()->getType() << RHS.get()->getType()
10753             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10754       }
10755     }
10756   } else {
10757     // ...else expand RHS to match the number of elements in LHS.
10758     QualType VecTy =
10759       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10760     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10761   }
10762 
10763   return LHSType;
10764 }
10765 
10766 // C99 6.5.7
10767 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10768                                   SourceLocation Loc, BinaryOperatorKind Opc,
10769                                   bool IsCompAssign) {
10770   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10771 
10772   // Vector shifts promote their scalar inputs to vector type.
10773   if (LHS.get()->getType()->isVectorType() ||
10774       RHS.get()->getType()->isVectorType()) {
10775     if (LangOpts.ZVector) {
10776       // The shift operators for the z vector extensions work basically
10777       // like general shifts, except that neither the LHS nor the RHS is
10778       // allowed to be a "vector bool".
10779       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10780         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10781           return InvalidOperands(Loc, LHS, RHS);
10782       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10783         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10784           return InvalidOperands(Loc, LHS, RHS);
10785     }
10786     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10787   }
10788 
10789   // Shifts don't perform usual arithmetic conversions, they just do integer
10790   // promotions on each operand. C99 6.5.7p3
10791 
10792   // For the LHS, do usual unary conversions, but then reset them away
10793   // if this is a compound assignment.
10794   ExprResult OldLHS = LHS;
10795   LHS = UsualUnaryConversions(LHS.get());
10796   if (LHS.isInvalid())
10797     return QualType();
10798   QualType LHSType = LHS.get()->getType();
10799   if (IsCompAssign) LHS = OldLHS;
10800 
10801   // The RHS is simpler.
10802   RHS = UsualUnaryConversions(RHS.get());
10803   if (RHS.isInvalid())
10804     return QualType();
10805   QualType RHSType = RHS.get()->getType();
10806 
10807   // C99 6.5.7p2: Each of the operands shall have integer type.
10808   if (!LHSType->hasIntegerRepresentation() ||
10809       !RHSType->hasIntegerRepresentation())
10810     return InvalidOperands(Loc, LHS, RHS);
10811 
10812   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10813   // hasIntegerRepresentation() above instead of this.
10814   if (isScopedEnumerationType(LHSType) ||
10815       isScopedEnumerationType(RHSType)) {
10816     return InvalidOperands(Loc, LHS, RHS);
10817   }
10818   // Sanity-check shift operands
10819   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10820 
10821   // "The type of the result is that of the promoted left operand."
10822   return LHSType;
10823 }
10824 
10825 /// Diagnose bad pointer comparisons.
10826 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10827                                               ExprResult &LHS, ExprResult &RHS,
10828                                               bool IsError) {
10829   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10830                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10831     << LHS.get()->getType() << RHS.get()->getType()
10832     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10833 }
10834 
10835 /// Returns false if the pointers are converted to a composite type,
10836 /// true otherwise.
10837 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10838                                            ExprResult &LHS, ExprResult &RHS) {
10839   // C++ [expr.rel]p2:
10840   //   [...] Pointer conversions (4.10) and qualification
10841   //   conversions (4.4) are performed on pointer operands (or on
10842   //   a pointer operand and a null pointer constant) to bring
10843   //   them to their composite pointer type. [...]
10844   //
10845   // C++ [expr.eq]p1 uses the same notion for (in)equality
10846   // comparisons of pointers.
10847 
10848   QualType LHSType = LHS.get()->getType();
10849   QualType RHSType = RHS.get()->getType();
10850   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10851          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10852 
10853   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10854   if (T.isNull()) {
10855     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10856         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10857       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10858     else
10859       S.InvalidOperands(Loc, LHS, RHS);
10860     return true;
10861   }
10862 
10863   return false;
10864 }
10865 
10866 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10867                                                     ExprResult &LHS,
10868                                                     ExprResult &RHS,
10869                                                     bool IsError) {
10870   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10871                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10872     << LHS.get()->getType() << RHS.get()->getType()
10873     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10874 }
10875 
10876 static bool isObjCObjectLiteral(ExprResult &E) {
10877   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10878   case Stmt::ObjCArrayLiteralClass:
10879   case Stmt::ObjCDictionaryLiteralClass:
10880   case Stmt::ObjCStringLiteralClass:
10881   case Stmt::ObjCBoxedExprClass:
10882     return true;
10883   default:
10884     // Note that ObjCBoolLiteral is NOT an object literal!
10885     return false;
10886   }
10887 }
10888 
10889 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10890   const ObjCObjectPointerType *Type =
10891     LHS->getType()->getAs<ObjCObjectPointerType>();
10892 
10893   // If this is not actually an Objective-C object, bail out.
10894   if (!Type)
10895     return false;
10896 
10897   // Get the LHS object's interface type.
10898   QualType InterfaceType = Type->getPointeeType();
10899 
10900   // If the RHS isn't an Objective-C object, bail out.
10901   if (!RHS->getType()->isObjCObjectPointerType())
10902     return false;
10903 
10904   // Try to find the -isEqual: method.
10905   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10906   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10907                                                       InterfaceType,
10908                                                       /*IsInstance=*/true);
10909   if (!Method) {
10910     if (Type->isObjCIdType()) {
10911       // For 'id', just check the global pool.
10912       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10913                                                   /*receiverId=*/true);
10914     } else {
10915       // Check protocols.
10916       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10917                                              /*IsInstance=*/true);
10918     }
10919   }
10920 
10921   if (!Method)
10922     return false;
10923 
10924   QualType T = Method->parameters()[0]->getType();
10925   if (!T->isObjCObjectPointerType())
10926     return false;
10927 
10928   QualType R = Method->getReturnType();
10929   if (!R->isScalarType())
10930     return false;
10931 
10932   return true;
10933 }
10934 
10935 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10936   FromE = FromE->IgnoreParenImpCasts();
10937   switch (FromE->getStmtClass()) {
10938     default:
10939       break;
10940     case Stmt::ObjCStringLiteralClass:
10941       // "string literal"
10942       return LK_String;
10943     case Stmt::ObjCArrayLiteralClass:
10944       // "array literal"
10945       return LK_Array;
10946     case Stmt::ObjCDictionaryLiteralClass:
10947       // "dictionary literal"
10948       return LK_Dictionary;
10949     case Stmt::BlockExprClass:
10950       return LK_Block;
10951     case Stmt::ObjCBoxedExprClass: {
10952       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10953       switch (Inner->getStmtClass()) {
10954         case Stmt::IntegerLiteralClass:
10955         case Stmt::FloatingLiteralClass:
10956         case Stmt::CharacterLiteralClass:
10957         case Stmt::ObjCBoolLiteralExprClass:
10958         case Stmt::CXXBoolLiteralExprClass:
10959           // "numeric literal"
10960           return LK_Numeric;
10961         case Stmt::ImplicitCastExprClass: {
10962           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10963           // Boolean literals can be represented by implicit casts.
10964           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10965             return LK_Numeric;
10966           break;
10967         }
10968         default:
10969           break;
10970       }
10971       return LK_Boxed;
10972     }
10973   }
10974   return LK_None;
10975 }
10976 
10977 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10978                                           ExprResult &LHS, ExprResult &RHS,
10979                                           BinaryOperator::Opcode Opc){
10980   Expr *Literal;
10981   Expr *Other;
10982   if (isObjCObjectLiteral(LHS)) {
10983     Literal = LHS.get();
10984     Other = RHS.get();
10985   } else {
10986     Literal = RHS.get();
10987     Other = LHS.get();
10988   }
10989 
10990   // Don't warn on comparisons against nil.
10991   Other = Other->IgnoreParenCasts();
10992   if (Other->isNullPointerConstant(S.getASTContext(),
10993                                    Expr::NPC_ValueDependentIsNotNull))
10994     return;
10995 
10996   // This should be kept in sync with warn_objc_literal_comparison.
10997   // LK_String should always be after the other literals, since it has its own
10998   // warning flag.
10999   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11000   assert(LiteralKind != Sema::LK_Block);
11001   if (LiteralKind == Sema::LK_None) {
11002     llvm_unreachable("Unknown Objective-C object literal kind");
11003   }
11004 
11005   if (LiteralKind == Sema::LK_String)
11006     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11007       << Literal->getSourceRange();
11008   else
11009     S.Diag(Loc, diag::warn_objc_literal_comparison)
11010       << LiteralKind << Literal->getSourceRange();
11011 
11012   if (BinaryOperator::isEqualityOp(Opc) &&
11013       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11014     SourceLocation Start = LHS.get()->getBeginLoc();
11015     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11016     CharSourceRange OpRange =
11017       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11018 
11019     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11020       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11021       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11022       << FixItHint::CreateInsertion(End, "]");
11023   }
11024 }
11025 
11026 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11027 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11028                                            ExprResult &RHS, SourceLocation Loc,
11029                                            BinaryOperatorKind Opc) {
11030   // Check that left hand side is !something.
11031   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11032   if (!UO || UO->getOpcode() != UO_LNot) return;
11033 
11034   // Only check if the right hand side is non-bool arithmetic type.
11035   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11036 
11037   // Make sure that the something in !something is not bool.
11038   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11039   if (SubExpr->isKnownToHaveBooleanValue()) return;
11040 
11041   // Emit warning.
11042   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11043   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11044       << Loc << IsBitwiseOp;
11045 
11046   // First note suggest !(x < y)
11047   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11048   SourceLocation FirstClose = RHS.get()->getEndLoc();
11049   FirstClose = S.getLocForEndOfToken(FirstClose);
11050   if (FirstClose.isInvalid())
11051     FirstOpen = SourceLocation();
11052   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11053       << IsBitwiseOp
11054       << FixItHint::CreateInsertion(FirstOpen, "(")
11055       << FixItHint::CreateInsertion(FirstClose, ")");
11056 
11057   // Second note suggests (!x) < y
11058   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11059   SourceLocation SecondClose = LHS.get()->getEndLoc();
11060   SecondClose = S.getLocForEndOfToken(SecondClose);
11061   if (SecondClose.isInvalid())
11062     SecondOpen = SourceLocation();
11063   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11064       << FixItHint::CreateInsertion(SecondOpen, "(")
11065       << FixItHint::CreateInsertion(SecondClose, ")");
11066 }
11067 
11068 // Returns true if E refers to a non-weak array.
11069 static bool checkForArray(const Expr *E) {
11070   const ValueDecl *D = nullptr;
11071   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11072     D = DR->getDecl();
11073   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11074     if (Mem->isImplicitAccess())
11075       D = Mem->getMemberDecl();
11076   }
11077   if (!D)
11078     return false;
11079   return D->getType()->isArrayType() && !D->isWeak();
11080 }
11081 
11082 /// Diagnose some forms of syntactically-obvious tautological comparison.
11083 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11084                                            Expr *LHS, Expr *RHS,
11085                                            BinaryOperatorKind Opc) {
11086   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11087   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11088 
11089   QualType LHSType = LHS->getType();
11090   QualType RHSType = RHS->getType();
11091   if (LHSType->hasFloatingRepresentation() ||
11092       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11093       S.inTemplateInstantiation())
11094     return;
11095 
11096   // Comparisons between two array types are ill-formed for operator<=>, so
11097   // we shouldn't emit any additional warnings about it.
11098   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11099     return;
11100 
11101   // For non-floating point types, check for self-comparisons of the form
11102   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11103   // often indicate logic errors in the program.
11104   //
11105   // NOTE: Don't warn about comparison expressions resulting from macro
11106   // expansion. Also don't warn about comparisons which are only self
11107   // comparisons within a template instantiation. The warnings should catch
11108   // obvious cases in the definition of the template anyways. The idea is to
11109   // warn when the typed comparison operator will always evaluate to the same
11110   // result.
11111 
11112   // Used for indexing into %select in warn_comparison_always
11113   enum {
11114     AlwaysConstant,
11115     AlwaysTrue,
11116     AlwaysFalse,
11117     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11118   };
11119 
11120   // C++2a [depr.array.comp]:
11121   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11122   //   operands of array type are deprecated.
11123   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11124       RHSStripped->getType()->isArrayType()) {
11125     S.Diag(Loc, diag::warn_depr_array_comparison)
11126         << LHS->getSourceRange() << RHS->getSourceRange()
11127         << LHSStripped->getType() << RHSStripped->getType();
11128     // Carry on to produce the tautological comparison warning, if this
11129     // expression is potentially-evaluated, we can resolve the array to a
11130     // non-weak declaration, and so on.
11131   }
11132 
11133   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11134     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11135       unsigned Result;
11136       switch (Opc) {
11137       case BO_EQ:
11138       case BO_LE:
11139       case BO_GE:
11140         Result = AlwaysTrue;
11141         break;
11142       case BO_NE:
11143       case BO_LT:
11144       case BO_GT:
11145         Result = AlwaysFalse;
11146         break;
11147       case BO_Cmp:
11148         Result = AlwaysEqual;
11149         break;
11150       default:
11151         Result = AlwaysConstant;
11152         break;
11153       }
11154       S.DiagRuntimeBehavior(Loc, nullptr,
11155                             S.PDiag(diag::warn_comparison_always)
11156                                 << 0 /*self-comparison*/
11157                                 << Result);
11158     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11159       // What is it always going to evaluate to?
11160       unsigned Result;
11161       switch (Opc) {
11162       case BO_EQ: // e.g. array1 == array2
11163         Result = AlwaysFalse;
11164         break;
11165       case BO_NE: // e.g. array1 != array2
11166         Result = AlwaysTrue;
11167         break;
11168       default: // e.g. array1 <= array2
11169         // The best we can say is 'a constant'
11170         Result = AlwaysConstant;
11171         break;
11172       }
11173       S.DiagRuntimeBehavior(Loc, nullptr,
11174                             S.PDiag(diag::warn_comparison_always)
11175                                 << 1 /*array comparison*/
11176                                 << Result);
11177     }
11178   }
11179 
11180   if (isa<CastExpr>(LHSStripped))
11181     LHSStripped = LHSStripped->IgnoreParenCasts();
11182   if (isa<CastExpr>(RHSStripped))
11183     RHSStripped = RHSStripped->IgnoreParenCasts();
11184 
11185   // Warn about comparisons against a string constant (unless the other
11186   // operand is null); the user probably wants string comparison function.
11187   Expr *LiteralString = nullptr;
11188   Expr *LiteralStringStripped = nullptr;
11189   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11190       !RHSStripped->isNullPointerConstant(S.Context,
11191                                           Expr::NPC_ValueDependentIsNull)) {
11192     LiteralString = LHS;
11193     LiteralStringStripped = LHSStripped;
11194   } else if ((isa<StringLiteral>(RHSStripped) ||
11195               isa<ObjCEncodeExpr>(RHSStripped)) &&
11196              !LHSStripped->isNullPointerConstant(S.Context,
11197                                           Expr::NPC_ValueDependentIsNull)) {
11198     LiteralString = RHS;
11199     LiteralStringStripped = RHSStripped;
11200   }
11201 
11202   if (LiteralString) {
11203     S.DiagRuntimeBehavior(Loc, nullptr,
11204                           S.PDiag(diag::warn_stringcompare)
11205                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11206                               << LiteralString->getSourceRange());
11207   }
11208 }
11209 
11210 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11211   switch (CK) {
11212   default: {
11213 #ifndef NDEBUG
11214     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11215                  << "\n";
11216 #endif
11217     llvm_unreachable("unhandled cast kind");
11218   }
11219   case CK_UserDefinedConversion:
11220     return ICK_Identity;
11221   case CK_LValueToRValue:
11222     return ICK_Lvalue_To_Rvalue;
11223   case CK_ArrayToPointerDecay:
11224     return ICK_Array_To_Pointer;
11225   case CK_FunctionToPointerDecay:
11226     return ICK_Function_To_Pointer;
11227   case CK_IntegralCast:
11228     return ICK_Integral_Conversion;
11229   case CK_FloatingCast:
11230     return ICK_Floating_Conversion;
11231   case CK_IntegralToFloating:
11232   case CK_FloatingToIntegral:
11233     return ICK_Floating_Integral;
11234   case CK_IntegralComplexCast:
11235   case CK_FloatingComplexCast:
11236   case CK_FloatingComplexToIntegralComplex:
11237   case CK_IntegralComplexToFloatingComplex:
11238     return ICK_Complex_Conversion;
11239   case CK_FloatingComplexToReal:
11240   case CK_FloatingRealToComplex:
11241   case CK_IntegralComplexToReal:
11242   case CK_IntegralRealToComplex:
11243     return ICK_Complex_Real;
11244   }
11245 }
11246 
11247 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11248                                              QualType FromType,
11249                                              SourceLocation Loc) {
11250   // Check for a narrowing implicit conversion.
11251   StandardConversionSequence SCS;
11252   SCS.setAsIdentityConversion();
11253   SCS.setToType(0, FromType);
11254   SCS.setToType(1, ToType);
11255   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11256     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11257 
11258   APValue PreNarrowingValue;
11259   QualType PreNarrowingType;
11260   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11261                                PreNarrowingType,
11262                                /*IgnoreFloatToIntegralConversion*/ true)) {
11263   case NK_Dependent_Narrowing:
11264     // Implicit conversion to a narrower type, but the expression is
11265     // value-dependent so we can't tell whether it's actually narrowing.
11266   case NK_Not_Narrowing:
11267     return false;
11268 
11269   case NK_Constant_Narrowing:
11270     // Implicit conversion to a narrower type, and the value is not a constant
11271     // expression.
11272     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11273         << /*Constant*/ 1
11274         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11275     return true;
11276 
11277   case NK_Variable_Narrowing:
11278     // Implicit conversion to a narrower type, and the value is not a constant
11279     // expression.
11280   case NK_Type_Narrowing:
11281     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11282         << /*Constant*/ 0 << FromType << ToType;
11283     // TODO: It's not a constant expression, but what if the user intended it
11284     // to be? Can we produce notes to help them figure out why it isn't?
11285     return true;
11286   }
11287   llvm_unreachable("unhandled case in switch");
11288 }
11289 
11290 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11291                                                          ExprResult &LHS,
11292                                                          ExprResult &RHS,
11293                                                          SourceLocation Loc) {
11294   QualType LHSType = LHS.get()->getType();
11295   QualType RHSType = RHS.get()->getType();
11296   // Dig out the original argument type and expression before implicit casts
11297   // were applied. These are the types/expressions we need to check the
11298   // [expr.spaceship] requirements against.
11299   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11300   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11301   QualType LHSStrippedType = LHSStripped.get()->getType();
11302   QualType RHSStrippedType = RHSStripped.get()->getType();
11303 
11304   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11305   // other is not, the program is ill-formed.
11306   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11307     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11308     return QualType();
11309   }
11310 
11311   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11312   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11313                     RHSStrippedType->isEnumeralType();
11314   if (NumEnumArgs == 1) {
11315     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11316     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11317     if (OtherTy->hasFloatingRepresentation()) {
11318       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11319       return QualType();
11320     }
11321   }
11322   if (NumEnumArgs == 2) {
11323     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11324     // type E, the operator yields the result of converting the operands
11325     // to the underlying type of E and applying <=> to the converted operands.
11326     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11327       S.InvalidOperands(Loc, LHS, RHS);
11328       return QualType();
11329     }
11330     QualType IntType =
11331         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11332     assert(IntType->isArithmeticType());
11333 
11334     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11335     // promote the boolean type, and all other promotable integer types, to
11336     // avoid this.
11337     if (IntType->isPromotableIntegerType())
11338       IntType = S.Context.getPromotedIntegerType(IntType);
11339 
11340     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11341     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11342     LHSType = RHSType = IntType;
11343   }
11344 
11345   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11346   // usual arithmetic conversions are applied to the operands.
11347   QualType Type =
11348       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11349   if (LHS.isInvalid() || RHS.isInvalid())
11350     return QualType();
11351   if (Type.isNull())
11352     return S.InvalidOperands(Loc, LHS, RHS);
11353 
11354   Optional<ComparisonCategoryType> CCT =
11355       getComparisonCategoryForBuiltinCmp(Type);
11356   if (!CCT)
11357     return S.InvalidOperands(Loc, LHS, RHS);
11358 
11359   bool HasNarrowing = checkThreeWayNarrowingConversion(
11360       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11361   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11362                                                    RHS.get()->getBeginLoc());
11363   if (HasNarrowing)
11364     return QualType();
11365 
11366   assert(!Type.isNull() && "composite type for <=> has not been set");
11367 
11368   return S.CheckComparisonCategoryType(
11369       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11370 }
11371 
11372 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11373                                                  ExprResult &RHS,
11374                                                  SourceLocation Loc,
11375                                                  BinaryOperatorKind Opc) {
11376   if (Opc == BO_Cmp)
11377     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11378 
11379   // C99 6.5.8p3 / C99 6.5.9p4
11380   QualType Type =
11381       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11382   if (LHS.isInvalid() || RHS.isInvalid())
11383     return QualType();
11384   if (Type.isNull())
11385     return S.InvalidOperands(Loc, LHS, RHS);
11386   assert(Type->isArithmeticType() || Type->isEnumeralType());
11387 
11388   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11389     return S.InvalidOperands(Loc, LHS, RHS);
11390 
11391   // Check for comparisons of floating point operands using != and ==.
11392   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11393     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11394 
11395   // The result of comparisons is 'bool' in C++, 'int' in C.
11396   return S.Context.getLogicalOperationType();
11397 }
11398 
11399 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11400   if (!NullE.get()->getType()->isAnyPointerType())
11401     return;
11402   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11403   if (!E.get()->getType()->isAnyPointerType() &&
11404       E.get()->isNullPointerConstant(Context,
11405                                      Expr::NPC_ValueDependentIsNotNull) ==
11406         Expr::NPCK_ZeroExpression) {
11407     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11408       if (CL->getValue() == 0)
11409         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11410             << NullValue
11411             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11412                                             NullValue ? "NULL" : "(void *)0");
11413     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11414         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11415         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11416         if (T == Context.CharTy)
11417           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11418               << NullValue
11419               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11420                                               NullValue ? "NULL" : "(void *)0");
11421       }
11422   }
11423 }
11424 
11425 // C99 6.5.8, C++ [expr.rel]
11426 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11427                                     SourceLocation Loc,
11428                                     BinaryOperatorKind Opc) {
11429   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11430   bool IsThreeWay = Opc == BO_Cmp;
11431   bool IsOrdered = IsRelational || IsThreeWay;
11432   auto IsAnyPointerType = [](ExprResult E) {
11433     QualType Ty = E.get()->getType();
11434     return Ty->isPointerType() || Ty->isMemberPointerType();
11435   };
11436 
11437   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11438   // type, array-to-pointer, ..., conversions are performed on both operands to
11439   // bring them to their composite type.
11440   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11441   // any type-related checks.
11442   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11443     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11444     if (LHS.isInvalid())
11445       return QualType();
11446     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11447     if (RHS.isInvalid())
11448       return QualType();
11449   } else {
11450     LHS = DefaultLvalueConversion(LHS.get());
11451     if (LHS.isInvalid())
11452       return QualType();
11453     RHS = DefaultLvalueConversion(RHS.get());
11454     if (RHS.isInvalid())
11455       return QualType();
11456   }
11457 
11458   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11459   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11460     CheckPtrComparisonWithNullChar(LHS, RHS);
11461     CheckPtrComparisonWithNullChar(RHS, LHS);
11462   }
11463 
11464   // Handle vector comparisons separately.
11465   if (LHS.get()->getType()->isVectorType() ||
11466       RHS.get()->getType()->isVectorType())
11467     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11468 
11469   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11470   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11471 
11472   QualType LHSType = LHS.get()->getType();
11473   QualType RHSType = RHS.get()->getType();
11474   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11475       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11476     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11477 
11478   const Expr::NullPointerConstantKind LHSNullKind =
11479       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11480   const Expr::NullPointerConstantKind RHSNullKind =
11481       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11482   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11483   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11484 
11485   auto computeResultTy = [&]() {
11486     if (Opc != BO_Cmp)
11487       return Context.getLogicalOperationType();
11488     assert(getLangOpts().CPlusPlus);
11489     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11490 
11491     QualType CompositeTy = LHS.get()->getType();
11492     assert(!CompositeTy->isReferenceType());
11493 
11494     Optional<ComparisonCategoryType> CCT =
11495         getComparisonCategoryForBuiltinCmp(CompositeTy);
11496     if (!CCT)
11497       return InvalidOperands(Loc, LHS, RHS);
11498 
11499     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11500       // P0946R0: Comparisons between a null pointer constant and an object
11501       // pointer result in std::strong_equality, which is ill-formed under
11502       // P1959R0.
11503       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11504           << (LHSIsNull ? LHS.get()->getSourceRange()
11505                         : RHS.get()->getSourceRange());
11506       return QualType();
11507     }
11508 
11509     return CheckComparisonCategoryType(
11510         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11511   };
11512 
11513   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11514     bool IsEquality = Opc == BO_EQ;
11515     if (RHSIsNull)
11516       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11517                                    RHS.get()->getSourceRange());
11518     else
11519       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11520                                    LHS.get()->getSourceRange());
11521   }
11522 
11523   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11524       (RHSType->isIntegerType() && !RHSIsNull)) {
11525     // Skip normal pointer conversion checks in this case; we have better
11526     // diagnostics for this below.
11527   } else if (getLangOpts().CPlusPlus) {
11528     // Equality comparison of a function pointer to a void pointer is invalid,
11529     // but we allow it as an extension.
11530     // FIXME: If we really want to allow this, should it be part of composite
11531     // pointer type computation so it works in conditionals too?
11532     if (!IsOrdered &&
11533         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11534          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11535       // This is a gcc extension compatibility comparison.
11536       // In a SFINAE context, we treat this as a hard error to maintain
11537       // conformance with the C++ standard.
11538       diagnoseFunctionPointerToVoidComparison(
11539           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11540 
11541       if (isSFINAEContext())
11542         return QualType();
11543 
11544       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11545       return computeResultTy();
11546     }
11547 
11548     // C++ [expr.eq]p2:
11549     //   If at least one operand is a pointer [...] bring them to their
11550     //   composite pointer type.
11551     // C++ [expr.spaceship]p6
11552     //  If at least one of the operands is of pointer type, [...] bring them
11553     //  to their composite pointer type.
11554     // C++ [expr.rel]p2:
11555     //   If both operands are pointers, [...] bring them to their composite
11556     //   pointer type.
11557     // For <=>, the only valid non-pointer types are arrays and functions, and
11558     // we already decayed those, so this is really the same as the relational
11559     // comparison rule.
11560     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11561             (IsOrdered ? 2 : 1) &&
11562         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11563                                          RHSType->isObjCObjectPointerType()))) {
11564       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11565         return QualType();
11566       return computeResultTy();
11567     }
11568   } else if (LHSType->isPointerType() &&
11569              RHSType->isPointerType()) { // C99 6.5.8p2
11570     // All of the following pointer-related warnings are GCC extensions, except
11571     // when handling null pointer constants.
11572     QualType LCanPointeeTy =
11573       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11574     QualType RCanPointeeTy =
11575       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11576 
11577     // C99 6.5.9p2 and C99 6.5.8p2
11578     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11579                                    RCanPointeeTy.getUnqualifiedType())) {
11580       // Valid unless a relational comparison of function pointers
11581       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11582         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11583           << LHSType << RHSType << LHS.get()->getSourceRange()
11584           << RHS.get()->getSourceRange();
11585       }
11586     } else if (!IsRelational &&
11587                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11588       // Valid unless comparison between non-null pointer and function pointer
11589       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11590           && !LHSIsNull && !RHSIsNull)
11591         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11592                                                 /*isError*/false);
11593     } else {
11594       // Invalid
11595       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11596     }
11597     if (LCanPointeeTy != RCanPointeeTy) {
11598       // Treat NULL constant as a special case in OpenCL.
11599       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11600         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11601           Diag(Loc,
11602                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11603               << LHSType << RHSType << 0 /* comparison */
11604               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11605         }
11606       }
11607       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11608       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11609       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11610                                                : CK_BitCast;
11611       if (LHSIsNull && !RHSIsNull)
11612         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11613       else
11614         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11615     }
11616     return computeResultTy();
11617   }
11618 
11619   if (getLangOpts().CPlusPlus) {
11620     // C++ [expr.eq]p4:
11621     //   Two operands of type std::nullptr_t or one operand of type
11622     //   std::nullptr_t and the other a null pointer constant compare equal.
11623     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11624       if (LHSType->isNullPtrType()) {
11625         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11626         return computeResultTy();
11627       }
11628       if (RHSType->isNullPtrType()) {
11629         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11630         return computeResultTy();
11631       }
11632     }
11633 
11634     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11635     // These aren't covered by the composite pointer type rules.
11636     if (!IsOrdered && RHSType->isNullPtrType() &&
11637         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11638       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11639       return computeResultTy();
11640     }
11641     if (!IsOrdered && LHSType->isNullPtrType() &&
11642         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11643       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11644       return computeResultTy();
11645     }
11646 
11647     if (IsRelational &&
11648         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11649          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11650       // HACK: Relational comparison of nullptr_t against a pointer type is
11651       // invalid per DR583, but we allow it within std::less<> and friends,
11652       // since otherwise common uses of it break.
11653       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11654       // friends to have std::nullptr_t overload candidates.
11655       DeclContext *DC = CurContext;
11656       if (isa<FunctionDecl>(DC))
11657         DC = DC->getParent();
11658       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11659         if (CTSD->isInStdNamespace() &&
11660             llvm::StringSwitch<bool>(CTSD->getName())
11661                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11662                 .Default(false)) {
11663           if (RHSType->isNullPtrType())
11664             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11665           else
11666             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11667           return computeResultTy();
11668         }
11669       }
11670     }
11671 
11672     // C++ [expr.eq]p2:
11673     //   If at least one operand is a pointer to member, [...] bring them to
11674     //   their composite pointer type.
11675     if (!IsOrdered &&
11676         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11677       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11678         return QualType();
11679       else
11680         return computeResultTy();
11681     }
11682   }
11683 
11684   // Handle block pointer types.
11685   if (!IsOrdered && LHSType->isBlockPointerType() &&
11686       RHSType->isBlockPointerType()) {
11687     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11688     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11689 
11690     if (!LHSIsNull && !RHSIsNull &&
11691         !Context.typesAreCompatible(lpointee, rpointee)) {
11692       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11693         << LHSType << RHSType << LHS.get()->getSourceRange()
11694         << RHS.get()->getSourceRange();
11695     }
11696     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11697     return computeResultTy();
11698   }
11699 
11700   // Allow block pointers to be compared with null pointer constants.
11701   if (!IsOrdered
11702       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11703           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11704     if (!LHSIsNull && !RHSIsNull) {
11705       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11706              ->getPointeeType()->isVoidType())
11707             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11708                 ->getPointeeType()->isVoidType())))
11709         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11710           << LHSType << RHSType << LHS.get()->getSourceRange()
11711           << RHS.get()->getSourceRange();
11712     }
11713     if (LHSIsNull && !RHSIsNull)
11714       LHS = ImpCastExprToType(LHS.get(), RHSType,
11715                               RHSType->isPointerType() ? CK_BitCast
11716                                 : CK_AnyPointerToBlockPointerCast);
11717     else
11718       RHS = ImpCastExprToType(RHS.get(), LHSType,
11719                               LHSType->isPointerType() ? CK_BitCast
11720                                 : CK_AnyPointerToBlockPointerCast);
11721     return computeResultTy();
11722   }
11723 
11724   if (LHSType->isObjCObjectPointerType() ||
11725       RHSType->isObjCObjectPointerType()) {
11726     const PointerType *LPT = LHSType->getAs<PointerType>();
11727     const PointerType *RPT = RHSType->getAs<PointerType>();
11728     if (LPT || RPT) {
11729       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11730       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11731 
11732       if (!LPtrToVoid && !RPtrToVoid &&
11733           !Context.typesAreCompatible(LHSType, RHSType)) {
11734         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11735                                           /*isError*/false);
11736       }
11737       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11738       // the RHS, but we have test coverage for this behavior.
11739       // FIXME: Consider using convertPointersToCompositeType in C++.
11740       if (LHSIsNull && !RHSIsNull) {
11741         Expr *E = LHS.get();
11742         if (getLangOpts().ObjCAutoRefCount)
11743           CheckObjCConversion(SourceRange(), RHSType, E,
11744                               CCK_ImplicitConversion);
11745         LHS = ImpCastExprToType(E, RHSType,
11746                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11747       }
11748       else {
11749         Expr *E = RHS.get();
11750         if (getLangOpts().ObjCAutoRefCount)
11751           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11752                               /*Diagnose=*/true,
11753                               /*DiagnoseCFAudited=*/false, Opc);
11754         RHS = ImpCastExprToType(E, LHSType,
11755                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11756       }
11757       return computeResultTy();
11758     }
11759     if (LHSType->isObjCObjectPointerType() &&
11760         RHSType->isObjCObjectPointerType()) {
11761       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11762         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11763                                           /*isError*/false);
11764       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11765         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11766 
11767       if (LHSIsNull && !RHSIsNull)
11768         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11769       else
11770         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11771       return computeResultTy();
11772     }
11773 
11774     if (!IsOrdered && LHSType->isBlockPointerType() &&
11775         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11776       LHS = ImpCastExprToType(LHS.get(), RHSType,
11777                               CK_BlockPointerToObjCPointerCast);
11778       return computeResultTy();
11779     } else if (!IsOrdered &&
11780                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11781                RHSType->isBlockPointerType()) {
11782       RHS = ImpCastExprToType(RHS.get(), LHSType,
11783                               CK_BlockPointerToObjCPointerCast);
11784       return computeResultTy();
11785     }
11786   }
11787   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11788       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11789     unsigned DiagID = 0;
11790     bool isError = false;
11791     if (LangOpts.DebuggerSupport) {
11792       // Under a debugger, allow the comparison of pointers to integers,
11793       // since users tend to want to compare addresses.
11794     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11795                (RHSIsNull && RHSType->isIntegerType())) {
11796       if (IsOrdered) {
11797         isError = getLangOpts().CPlusPlus;
11798         DiagID =
11799           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11800                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11801       }
11802     } else if (getLangOpts().CPlusPlus) {
11803       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11804       isError = true;
11805     } else if (IsOrdered)
11806       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11807     else
11808       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11809 
11810     if (DiagID) {
11811       Diag(Loc, DiagID)
11812         << LHSType << RHSType << LHS.get()->getSourceRange()
11813         << RHS.get()->getSourceRange();
11814       if (isError)
11815         return QualType();
11816     }
11817 
11818     if (LHSType->isIntegerType())
11819       LHS = ImpCastExprToType(LHS.get(), RHSType,
11820                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11821     else
11822       RHS = ImpCastExprToType(RHS.get(), LHSType,
11823                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11824     return computeResultTy();
11825   }
11826 
11827   // Handle block pointers.
11828   if (!IsOrdered && RHSIsNull
11829       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11830     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11831     return computeResultTy();
11832   }
11833   if (!IsOrdered && LHSIsNull
11834       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11835     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11836     return computeResultTy();
11837   }
11838 
11839   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11840     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11841       return computeResultTy();
11842     }
11843 
11844     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11845       return computeResultTy();
11846     }
11847 
11848     if (LHSIsNull && RHSType->isQueueT()) {
11849       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11850       return computeResultTy();
11851     }
11852 
11853     if (LHSType->isQueueT() && RHSIsNull) {
11854       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11855       return computeResultTy();
11856     }
11857   }
11858 
11859   return InvalidOperands(Loc, LHS, RHS);
11860 }
11861 
11862 // Return a signed ext_vector_type that is of identical size and number of
11863 // elements. For floating point vectors, return an integer type of identical
11864 // size and number of elements. In the non ext_vector_type case, search from
11865 // the largest type to the smallest type to avoid cases where long long == long,
11866 // where long gets picked over long long.
11867 QualType Sema::GetSignedVectorType(QualType V) {
11868   const VectorType *VTy = V->castAs<VectorType>();
11869   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11870 
11871   if (isa<ExtVectorType>(VTy)) {
11872     if (TypeSize == Context.getTypeSize(Context.CharTy))
11873       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11874     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11875       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11876     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11877       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11878     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11879       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11880     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11881            "Unhandled vector element size in vector compare");
11882     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11883   }
11884 
11885   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11886     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11887                                  VectorType::GenericVector);
11888   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11889     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11890                                  VectorType::GenericVector);
11891   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11892     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11893                                  VectorType::GenericVector);
11894   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11895     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11896                                  VectorType::GenericVector);
11897   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11898          "Unhandled vector element size in vector compare");
11899   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11900                                VectorType::GenericVector);
11901 }
11902 
11903 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11904 /// operates on extended vector types.  Instead of producing an IntTy result,
11905 /// like a scalar comparison, a vector comparison produces a vector of integer
11906 /// types.
11907 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11908                                           SourceLocation Loc,
11909                                           BinaryOperatorKind Opc) {
11910   if (Opc == BO_Cmp) {
11911     Diag(Loc, diag::err_three_way_vector_comparison);
11912     return QualType();
11913   }
11914 
11915   // Check to make sure we're operating on vectors of the same type and width,
11916   // Allowing one side to be a scalar of element type.
11917   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11918                               /*AllowBothBool*/true,
11919                               /*AllowBoolConversions*/getLangOpts().ZVector);
11920   if (vType.isNull())
11921     return vType;
11922 
11923   QualType LHSType = LHS.get()->getType();
11924 
11925   // If AltiVec, the comparison results in a numeric type, i.e.
11926   // bool for C++, int for C
11927   if (getLangOpts().AltiVec &&
11928       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11929     return Context.getLogicalOperationType();
11930 
11931   // For non-floating point types, check for self-comparisons of the form
11932   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11933   // often indicate logic errors in the program.
11934   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11935 
11936   // Check for comparisons of floating point operands using != and ==.
11937   if (BinaryOperator::isEqualityOp(Opc) &&
11938       LHSType->hasFloatingRepresentation()) {
11939     assert(RHS.get()->getType()->hasFloatingRepresentation());
11940     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11941   }
11942 
11943   // Return a signed type for the vector.
11944   return GetSignedVectorType(vType);
11945 }
11946 
11947 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11948                                     const ExprResult &XorRHS,
11949                                     const SourceLocation Loc) {
11950   // Do not diagnose macros.
11951   if (Loc.isMacroID())
11952     return;
11953 
11954   bool Negative = false;
11955   bool ExplicitPlus = false;
11956   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11957   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11958 
11959   if (!LHSInt)
11960     return;
11961   if (!RHSInt) {
11962     // Check negative literals.
11963     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11964       UnaryOperatorKind Opc = UO->getOpcode();
11965       if (Opc != UO_Minus && Opc != UO_Plus)
11966         return;
11967       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11968       if (!RHSInt)
11969         return;
11970       Negative = (Opc == UO_Minus);
11971       ExplicitPlus = !Negative;
11972     } else {
11973       return;
11974     }
11975   }
11976 
11977   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11978   llvm::APInt RightSideValue = RHSInt->getValue();
11979   if (LeftSideValue != 2 && LeftSideValue != 10)
11980     return;
11981 
11982   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11983     return;
11984 
11985   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11986       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11987   llvm::StringRef ExprStr =
11988       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11989 
11990   CharSourceRange XorRange =
11991       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11992   llvm::StringRef XorStr =
11993       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11994   // Do not diagnose if xor keyword/macro is used.
11995   if (XorStr == "xor")
11996     return;
11997 
11998   std::string LHSStr = std::string(Lexer::getSourceText(
11999       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12000       S.getSourceManager(), S.getLangOpts()));
12001   std::string RHSStr = std::string(Lexer::getSourceText(
12002       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12003       S.getSourceManager(), S.getLangOpts()));
12004 
12005   if (Negative) {
12006     RightSideValue = -RightSideValue;
12007     RHSStr = "-" + RHSStr;
12008   } else if (ExplicitPlus) {
12009     RHSStr = "+" + RHSStr;
12010   }
12011 
12012   StringRef LHSStrRef = LHSStr;
12013   StringRef RHSStrRef = RHSStr;
12014   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12015   // literals.
12016   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12017       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12018       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12019       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12020       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12021       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12022       LHSStrRef.find('\'') != StringRef::npos ||
12023       RHSStrRef.find('\'') != StringRef::npos)
12024     return;
12025 
12026   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12027   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12028   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12029   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12030     std::string SuggestedExpr = "1 << " + RHSStr;
12031     bool Overflow = false;
12032     llvm::APInt One = (LeftSideValue - 1);
12033     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12034     if (Overflow) {
12035       if (RightSideIntValue < 64)
12036         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12037             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12038             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12039       else if (RightSideIntValue == 64)
12040         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12041       else
12042         return;
12043     } else {
12044       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12045           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12046           << PowValue.toString(10, true)
12047           << FixItHint::CreateReplacement(
12048                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12049     }
12050 
12051     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12052   } else if (LeftSideValue == 10) {
12053     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12054     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12055         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12056         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12057     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12058   }
12059 }
12060 
12061 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12062                                           SourceLocation Loc) {
12063   // Ensure that either both operands are of the same vector type, or
12064   // one operand is of a vector type and the other is of its element type.
12065   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12066                                        /*AllowBothBool*/true,
12067                                        /*AllowBoolConversions*/false);
12068   if (vType.isNull())
12069     return InvalidOperands(Loc, LHS, RHS);
12070   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12071       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12072     return InvalidOperands(Loc, LHS, RHS);
12073   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12074   //        usage of the logical operators && and || with vectors in C. This
12075   //        check could be notionally dropped.
12076   if (!getLangOpts().CPlusPlus &&
12077       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12078     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12079 
12080   return GetSignedVectorType(LHS.get()->getType());
12081 }
12082 
12083 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12084                                               SourceLocation Loc,
12085                                               bool IsCompAssign) {
12086   if (!IsCompAssign) {
12087     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12088     if (LHS.isInvalid())
12089       return QualType();
12090   }
12091   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12092   if (RHS.isInvalid())
12093     return QualType();
12094 
12095   // For conversion purposes, we ignore any qualifiers.
12096   // For example, "const float" and "float" are equivalent.
12097   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12098   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12099 
12100   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12101   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12102   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12103 
12104   if (Context.hasSameType(LHSType, RHSType))
12105     return LHSType;
12106 
12107   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12108   // case we have to return InvalidOperands.
12109   ExprResult OriginalLHS = LHS;
12110   ExprResult OriginalRHS = RHS;
12111   if (LHSMatType && !RHSMatType) {
12112     if (tryConvertToTy(*this, LHSMatType->getElementType(), &RHS))
12113       return LHSType;
12114     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12115   }
12116 
12117   if (!LHSMatType && RHSMatType) {
12118     if (tryConvertToTy(*this, RHSMatType->getElementType(), &LHS))
12119       return RHSType;
12120     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12121   }
12122 
12123   return InvalidOperands(Loc, LHS, RHS);
12124 }
12125 
12126 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12127                                            SourceLocation Loc,
12128                                            bool IsCompAssign) {
12129   if (!IsCompAssign) {
12130     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12131     if (LHS.isInvalid())
12132       return QualType();
12133   }
12134   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12135   if (RHS.isInvalid())
12136     return QualType();
12137 
12138   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12139   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12140   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12141 
12142   if (LHSMatType && RHSMatType) {
12143     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12144       return InvalidOperands(Loc, LHS, RHS);
12145 
12146     if (!Context.hasSameType(LHSMatType->getElementType(),
12147                              RHSMatType->getElementType()))
12148       return InvalidOperands(Loc, LHS, RHS);
12149 
12150     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12151                                          LHSMatType->getNumRows(),
12152                                          RHSMatType->getNumColumns());
12153   }
12154   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12155 }
12156 
12157 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12158                                            SourceLocation Loc,
12159                                            BinaryOperatorKind Opc) {
12160   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12161 
12162   bool IsCompAssign =
12163       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12164 
12165   if (LHS.get()->getType()->isVectorType() ||
12166       RHS.get()->getType()->isVectorType()) {
12167     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12168         RHS.get()->getType()->hasIntegerRepresentation())
12169       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12170                         /*AllowBothBool*/true,
12171                         /*AllowBoolConversions*/getLangOpts().ZVector);
12172     return InvalidOperands(Loc, LHS, RHS);
12173   }
12174 
12175   if (Opc == BO_And)
12176     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12177 
12178   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12179       RHS.get()->getType()->hasFloatingRepresentation())
12180     return InvalidOperands(Loc, LHS, RHS);
12181 
12182   ExprResult LHSResult = LHS, RHSResult = RHS;
12183   QualType compType = UsualArithmeticConversions(
12184       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12185   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12186     return QualType();
12187   LHS = LHSResult.get();
12188   RHS = RHSResult.get();
12189 
12190   if (Opc == BO_Xor)
12191     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12192 
12193   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12194     return compType;
12195   return InvalidOperands(Loc, LHS, RHS);
12196 }
12197 
12198 // C99 6.5.[13,14]
12199 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12200                                            SourceLocation Loc,
12201                                            BinaryOperatorKind Opc) {
12202   // Check vector operands differently.
12203   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12204     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12205 
12206   bool EnumConstantInBoolContext = false;
12207   for (const ExprResult &HS : {LHS, RHS}) {
12208     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12209       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12210       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12211         EnumConstantInBoolContext = true;
12212     }
12213   }
12214 
12215   if (EnumConstantInBoolContext)
12216     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12217 
12218   // Diagnose cases where the user write a logical and/or but probably meant a
12219   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12220   // is a constant.
12221   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12222       !LHS.get()->getType()->isBooleanType() &&
12223       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12224       // Don't warn in macros or template instantiations.
12225       !Loc.isMacroID() && !inTemplateInstantiation()) {
12226     // If the RHS can be constant folded, and if it constant folds to something
12227     // that isn't 0 or 1 (which indicate a potential logical operation that
12228     // happened to fold to true/false) then warn.
12229     // Parens on the RHS are ignored.
12230     Expr::EvalResult EVResult;
12231     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12232       llvm::APSInt Result = EVResult.Val.getInt();
12233       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12234            !RHS.get()->getExprLoc().isMacroID()) ||
12235           (Result != 0 && Result != 1)) {
12236         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12237           << RHS.get()->getSourceRange()
12238           << (Opc == BO_LAnd ? "&&" : "||");
12239         // Suggest replacing the logical operator with the bitwise version
12240         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12241             << (Opc == BO_LAnd ? "&" : "|")
12242             << FixItHint::CreateReplacement(SourceRange(
12243                                                  Loc, getLocForEndOfToken(Loc)),
12244                                             Opc == BO_LAnd ? "&" : "|");
12245         if (Opc == BO_LAnd)
12246           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12247           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12248               << FixItHint::CreateRemoval(
12249                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12250                                  RHS.get()->getEndLoc()));
12251       }
12252     }
12253   }
12254 
12255   if (!Context.getLangOpts().CPlusPlus) {
12256     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12257     // not operate on the built-in scalar and vector float types.
12258     if (Context.getLangOpts().OpenCL &&
12259         Context.getLangOpts().OpenCLVersion < 120) {
12260       if (LHS.get()->getType()->isFloatingType() ||
12261           RHS.get()->getType()->isFloatingType())
12262         return InvalidOperands(Loc, LHS, RHS);
12263     }
12264 
12265     LHS = UsualUnaryConversions(LHS.get());
12266     if (LHS.isInvalid())
12267       return QualType();
12268 
12269     RHS = UsualUnaryConversions(RHS.get());
12270     if (RHS.isInvalid())
12271       return QualType();
12272 
12273     if (!LHS.get()->getType()->isScalarType() ||
12274         !RHS.get()->getType()->isScalarType())
12275       return InvalidOperands(Loc, LHS, RHS);
12276 
12277     return Context.IntTy;
12278   }
12279 
12280   // The following is safe because we only use this method for
12281   // non-overloadable operands.
12282 
12283   // C++ [expr.log.and]p1
12284   // C++ [expr.log.or]p1
12285   // The operands are both contextually converted to type bool.
12286   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12287   if (LHSRes.isInvalid())
12288     return InvalidOperands(Loc, LHS, RHS);
12289   LHS = LHSRes;
12290 
12291   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12292   if (RHSRes.isInvalid())
12293     return InvalidOperands(Loc, LHS, RHS);
12294   RHS = RHSRes;
12295 
12296   // C++ [expr.log.and]p2
12297   // C++ [expr.log.or]p2
12298   // The result is a bool.
12299   return Context.BoolTy;
12300 }
12301 
12302 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12303   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12304   if (!ME) return false;
12305   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12306   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12307       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12308   if (!Base) return false;
12309   return Base->getMethodDecl() != nullptr;
12310 }
12311 
12312 /// Is the given expression (which must be 'const') a reference to a
12313 /// variable which was originally non-const, but which has become
12314 /// 'const' due to being captured within a block?
12315 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12316 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12317   assert(E->isLValue() && E->getType().isConstQualified());
12318   E = E->IgnoreParens();
12319 
12320   // Must be a reference to a declaration from an enclosing scope.
12321   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12322   if (!DRE) return NCCK_None;
12323   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12324 
12325   // The declaration must be a variable which is not declared 'const'.
12326   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12327   if (!var) return NCCK_None;
12328   if (var->getType().isConstQualified()) return NCCK_None;
12329   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12330 
12331   // Decide whether the first capture was for a block or a lambda.
12332   DeclContext *DC = S.CurContext, *Prev = nullptr;
12333   // Decide whether the first capture was for a block or a lambda.
12334   while (DC) {
12335     // For init-capture, it is possible that the variable belongs to the
12336     // template pattern of the current context.
12337     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12338       if (var->isInitCapture() &&
12339           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12340         break;
12341     if (DC == var->getDeclContext())
12342       break;
12343     Prev = DC;
12344     DC = DC->getParent();
12345   }
12346   // Unless we have an init-capture, we've gone one step too far.
12347   if (!var->isInitCapture())
12348     DC = Prev;
12349   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12350 }
12351 
12352 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12353   Ty = Ty.getNonReferenceType();
12354   if (IsDereference && Ty->isPointerType())
12355     Ty = Ty->getPointeeType();
12356   return !Ty.isConstQualified();
12357 }
12358 
12359 // Update err_typecheck_assign_const and note_typecheck_assign_const
12360 // when this enum is changed.
12361 enum {
12362   ConstFunction,
12363   ConstVariable,
12364   ConstMember,
12365   ConstMethod,
12366   NestedConstMember,
12367   ConstUnknown,  // Keep as last element
12368 };
12369 
12370 /// Emit the "read-only variable not assignable" error and print notes to give
12371 /// more information about why the variable is not assignable, such as pointing
12372 /// to the declaration of a const variable, showing that a method is const, or
12373 /// that the function is returning a const reference.
12374 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12375                                     SourceLocation Loc) {
12376   SourceRange ExprRange = E->getSourceRange();
12377 
12378   // Only emit one error on the first const found.  All other consts will emit
12379   // a note to the error.
12380   bool DiagnosticEmitted = false;
12381 
12382   // Track if the current expression is the result of a dereference, and if the
12383   // next checked expression is the result of a dereference.
12384   bool IsDereference = false;
12385   bool NextIsDereference = false;
12386 
12387   // Loop to process MemberExpr chains.
12388   while (true) {
12389     IsDereference = NextIsDereference;
12390 
12391     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12392     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12393       NextIsDereference = ME->isArrow();
12394       const ValueDecl *VD = ME->getMemberDecl();
12395       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12396         // Mutable fields can be modified even if the class is const.
12397         if (Field->isMutable()) {
12398           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12399           break;
12400         }
12401 
12402         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12403           if (!DiagnosticEmitted) {
12404             S.Diag(Loc, diag::err_typecheck_assign_const)
12405                 << ExprRange << ConstMember << false /*static*/ << Field
12406                 << Field->getType();
12407             DiagnosticEmitted = true;
12408           }
12409           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12410               << ConstMember << false /*static*/ << Field << Field->getType()
12411               << Field->getSourceRange();
12412         }
12413         E = ME->getBase();
12414         continue;
12415       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12416         if (VDecl->getType().isConstQualified()) {
12417           if (!DiagnosticEmitted) {
12418             S.Diag(Loc, diag::err_typecheck_assign_const)
12419                 << ExprRange << ConstMember << true /*static*/ << VDecl
12420                 << VDecl->getType();
12421             DiagnosticEmitted = true;
12422           }
12423           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12424               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12425               << VDecl->getSourceRange();
12426         }
12427         // Static fields do not inherit constness from parents.
12428         break;
12429       }
12430       break; // End MemberExpr
12431     } else if (const ArraySubscriptExpr *ASE =
12432                    dyn_cast<ArraySubscriptExpr>(E)) {
12433       E = ASE->getBase()->IgnoreParenImpCasts();
12434       continue;
12435     } else if (const ExtVectorElementExpr *EVE =
12436                    dyn_cast<ExtVectorElementExpr>(E)) {
12437       E = EVE->getBase()->IgnoreParenImpCasts();
12438       continue;
12439     }
12440     break;
12441   }
12442 
12443   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12444     // Function calls
12445     const FunctionDecl *FD = CE->getDirectCallee();
12446     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12447       if (!DiagnosticEmitted) {
12448         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12449                                                       << ConstFunction << FD;
12450         DiagnosticEmitted = true;
12451       }
12452       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12453              diag::note_typecheck_assign_const)
12454           << ConstFunction << FD << FD->getReturnType()
12455           << FD->getReturnTypeSourceRange();
12456     }
12457   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12458     // Point to variable declaration.
12459     if (const ValueDecl *VD = DRE->getDecl()) {
12460       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12461         if (!DiagnosticEmitted) {
12462           S.Diag(Loc, diag::err_typecheck_assign_const)
12463               << ExprRange << ConstVariable << VD << VD->getType();
12464           DiagnosticEmitted = true;
12465         }
12466         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12467             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12468       }
12469     }
12470   } else if (isa<CXXThisExpr>(E)) {
12471     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12472       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12473         if (MD->isConst()) {
12474           if (!DiagnosticEmitted) {
12475             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12476                                                           << ConstMethod << MD;
12477             DiagnosticEmitted = true;
12478           }
12479           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12480               << ConstMethod << MD << MD->getSourceRange();
12481         }
12482       }
12483     }
12484   }
12485 
12486   if (DiagnosticEmitted)
12487     return;
12488 
12489   // Can't determine a more specific message, so display the generic error.
12490   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12491 }
12492 
12493 enum OriginalExprKind {
12494   OEK_Variable,
12495   OEK_Member,
12496   OEK_LValue
12497 };
12498 
12499 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12500                                          const RecordType *Ty,
12501                                          SourceLocation Loc, SourceRange Range,
12502                                          OriginalExprKind OEK,
12503                                          bool &DiagnosticEmitted) {
12504   std::vector<const RecordType *> RecordTypeList;
12505   RecordTypeList.push_back(Ty);
12506   unsigned NextToCheckIndex = 0;
12507   // We walk the record hierarchy breadth-first to ensure that we print
12508   // diagnostics in field nesting order.
12509   while (RecordTypeList.size() > NextToCheckIndex) {
12510     bool IsNested = NextToCheckIndex > 0;
12511     for (const FieldDecl *Field :
12512          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12513       // First, check every field for constness.
12514       QualType FieldTy = Field->getType();
12515       if (FieldTy.isConstQualified()) {
12516         if (!DiagnosticEmitted) {
12517           S.Diag(Loc, diag::err_typecheck_assign_const)
12518               << Range << NestedConstMember << OEK << VD
12519               << IsNested << Field;
12520           DiagnosticEmitted = true;
12521         }
12522         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12523             << NestedConstMember << IsNested << Field
12524             << FieldTy << Field->getSourceRange();
12525       }
12526 
12527       // Then we append it to the list to check next in order.
12528       FieldTy = FieldTy.getCanonicalType();
12529       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12530         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12531           RecordTypeList.push_back(FieldRecTy);
12532       }
12533     }
12534     ++NextToCheckIndex;
12535   }
12536 }
12537 
12538 /// Emit an error for the case where a record we are trying to assign to has a
12539 /// const-qualified field somewhere in its hierarchy.
12540 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12541                                          SourceLocation Loc) {
12542   QualType Ty = E->getType();
12543   assert(Ty->isRecordType() && "lvalue was not record?");
12544   SourceRange Range = E->getSourceRange();
12545   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12546   bool DiagEmitted = false;
12547 
12548   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12549     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12550             Range, OEK_Member, DiagEmitted);
12551   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12552     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12553             Range, OEK_Variable, DiagEmitted);
12554   else
12555     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12556             Range, OEK_LValue, DiagEmitted);
12557   if (!DiagEmitted)
12558     DiagnoseConstAssignment(S, E, Loc);
12559 }
12560 
12561 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12562 /// emit an error and return true.  If so, return false.
12563 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12564   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12565 
12566   S.CheckShadowingDeclModification(E, Loc);
12567 
12568   SourceLocation OrigLoc = Loc;
12569   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12570                                                               &Loc);
12571   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12572     IsLV = Expr::MLV_InvalidMessageExpression;
12573   if (IsLV == Expr::MLV_Valid)
12574     return false;
12575 
12576   unsigned DiagID = 0;
12577   bool NeedType = false;
12578   switch (IsLV) { // C99 6.5.16p2
12579   case Expr::MLV_ConstQualified:
12580     // Use a specialized diagnostic when we're assigning to an object
12581     // from an enclosing function or block.
12582     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12583       if (NCCK == NCCK_Block)
12584         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12585       else
12586         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12587       break;
12588     }
12589 
12590     // In ARC, use some specialized diagnostics for occasions where we
12591     // infer 'const'.  These are always pseudo-strong variables.
12592     if (S.getLangOpts().ObjCAutoRefCount) {
12593       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12594       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12595         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12596 
12597         // Use the normal diagnostic if it's pseudo-__strong but the
12598         // user actually wrote 'const'.
12599         if (var->isARCPseudoStrong() &&
12600             (!var->getTypeSourceInfo() ||
12601              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12602           // There are three pseudo-strong cases:
12603           //  - self
12604           ObjCMethodDecl *method = S.getCurMethodDecl();
12605           if (method && var == method->getSelfDecl()) {
12606             DiagID = method->isClassMethod()
12607               ? diag::err_typecheck_arc_assign_self_class_method
12608               : diag::err_typecheck_arc_assign_self;
12609 
12610           //  - Objective-C externally_retained attribute.
12611           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12612                      isa<ParmVarDecl>(var)) {
12613             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12614 
12615           //  - fast enumeration variables
12616           } else {
12617             DiagID = diag::err_typecheck_arr_assign_enumeration;
12618           }
12619 
12620           SourceRange Assign;
12621           if (Loc != OrigLoc)
12622             Assign = SourceRange(OrigLoc, OrigLoc);
12623           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12624           // We need to preserve the AST regardless, so migration tool
12625           // can do its job.
12626           return false;
12627         }
12628       }
12629     }
12630 
12631     // If none of the special cases above are triggered, then this is a
12632     // simple const assignment.
12633     if (DiagID == 0) {
12634       DiagnoseConstAssignment(S, E, Loc);
12635       return true;
12636     }
12637 
12638     break;
12639   case Expr::MLV_ConstAddrSpace:
12640     DiagnoseConstAssignment(S, E, Loc);
12641     return true;
12642   case Expr::MLV_ConstQualifiedField:
12643     DiagnoseRecursiveConstFields(S, E, Loc);
12644     return true;
12645   case Expr::MLV_ArrayType:
12646   case Expr::MLV_ArrayTemporary:
12647     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12648     NeedType = true;
12649     break;
12650   case Expr::MLV_NotObjectType:
12651     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12652     NeedType = true;
12653     break;
12654   case Expr::MLV_LValueCast:
12655     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12656     break;
12657   case Expr::MLV_Valid:
12658     llvm_unreachable("did not take early return for MLV_Valid");
12659   case Expr::MLV_InvalidExpression:
12660   case Expr::MLV_MemberFunction:
12661   case Expr::MLV_ClassTemporary:
12662     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12663     break;
12664   case Expr::MLV_IncompleteType:
12665   case Expr::MLV_IncompleteVoidType:
12666     return S.RequireCompleteType(Loc, E->getType(),
12667              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12668   case Expr::MLV_DuplicateVectorComponents:
12669     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12670     break;
12671   case Expr::MLV_NoSetterProperty:
12672     llvm_unreachable("readonly properties should be processed differently");
12673   case Expr::MLV_InvalidMessageExpression:
12674     DiagID = diag::err_readonly_message_assignment;
12675     break;
12676   case Expr::MLV_SubObjCPropertySetting:
12677     DiagID = diag::err_no_subobject_property_setting;
12678     break;
12679   }
12680 
12681   SourceRange Assign;
12682   if (Loc != OrigLoc)
12683     Assign = SourceRange(OrigLoc, OrigLoc);
12684   if (NeedType)
12685     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12686   else
12687     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12688   return true;
12689 }
12690 
12691 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12692                                          SourceLocation Loc,
12693                                          Sema &Sema) {
12694   if (Sema.inTemplateInstantiation())
12695     return;
12696   if (Sema.isUnevaluatedContext())
12697     return;
12698   if (Loc.isInvalid() || Loc.isMacroID())
12699     return;
12700   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12701     return;
12702 
12703   // C / C++ fields
12704   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12705   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12706   if (ML && MR) {
12707     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12708       return;
12709     const ValueDecl *LHSDecl =
12710         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12711     const ValueDecl *RHSDecl =
12712         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12713     if (LHSDecl != RHSDecl)
12714       return;
12715     if (LHSDecl->getType().isVolatileQualified())
12716       return;
12717     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12718       if (RefTy->getPointeeType().isVolatileQualified())
12719         return;
12720 
12721     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12722   }
12723 
12724   // Objective-C instance variables
12725   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12726   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12727   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12728     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12729     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12730     if (RL && RR && RL->getDecl() == RR->getDecl())
12731       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12732   }
12733 }
12734 
12735 // C99 6.5.16.1
12736 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12737                                        SourceLocation Loc,
12738                                        QualType CompoundType) {
12739   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12740 
12741   // Verify that LHS is a modifiable lvalue, and emit error if not.
12742   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12743     return QualType();
12744 
12745   QualType LHSType = LHSExpr->getType();
12746   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12747                                              CompoundType;
12748   // OpenCL v1.2 s6.1.1.1 p2:
12749   // The half data type can only be used to declare a pointer to a buffer that
12750   // contains half values
12751   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12752     LHSType->isHalfType()) {
12753     Diag(Loc, diag::err_opencl_half_load_store) << 1
12754         << LHSType.getUnqualifiedType();
12755     return QualType();
12756   }
12757 
12758   AssignConvertType ConvTy;
12759   if (CompoundType.isNull()) {
12760     Expr *RHSCheck = RHS.get();
12761 
12762     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12763 
12764     QualType LHSTy(LHSType);
12765     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12766     if (RHS.isInvalid())
12767       return QualType();
12768     // Special case of NSObject attributes on c-style pointer types.
12769     if (ConvTy == IncompatiblePointer &&
12770         ((Context.isObjCNSObjectType(LHSType) &&
12771           RHSType->isObjCObjectPointerType()) ||
12772          (Context.isObjCNSObjectType(RHSType) &&
12773           LHSType->isObjCObjectPointerType())))
12774       ConvTy = Compatible;
12775 
12776     if (ConvTy == Compatible &&
12777         LHSType->isObjCObjectType())
12778         Diag(Loc, diag::err_objc_object_assignment)
12779           << LHSType;
12780 
12781     // If the RHS is a unary plus or minus, check to see if they = and + are
12782     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12783     // instead of "x += 4".
12784     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12785       RHSCheck = ICE->getSubExpr();
12786     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12787       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12788           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12789           // Only if the two operators are exactly adjacent.
12790           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12791           // And there is a space or other character before the subexpr of the
12792           // unary +/-.  We don't want to warn on "x=-1".
12793           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12794           UO->getSubExpr()->getBeginLoc().isFileID()) {
12795         Diag(Loc, diag::warn_not_compound_assign)
12796           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12797           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12798       }
12799     }
12800 
12801     if (ConvTy == Compatible) {
12802       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12803         // Warn about retain cycles where a block captures the LHS, but
12804         // not if the LHS is a simple variable into which the block is
12805         // being stored...unless that variable can be captured by reference!
12806         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12807         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12808         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12809           checkRetainCycles(LHSExpr, RHS.get());
12810       }
12811 
12812       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12813           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12814         // It is safe to assign a weak reference into a strong variable.
12815         // Although this code can still have problems:
12816         //   id x = self.weakProp;
12817         //   id y = self.weakProp;
12818         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12819         // paths through the function. This should be revisited if
12820         // -Wrepeated-use-of-weak is made flow-sensitive.
12821         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12822         // variable, which will be valid for the current autorelease scope.
12823         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12824                              RHS.get()->getBeginLoc()))
12825           getCurFunction()->markSafeWeakUse(RHS.get());
12826 
12827       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12828         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12829       }
12830     }
12831   } else {
12832     // Compound assignment "x += y"
12833     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12834   }
12835 
12836   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12837                                RHS.get(), AA_Assigning))
12838     return QualType();
12839 
12840   CheckForNullPointerDereference(*this, LHSExpr);
12841 
12842   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12843     if (CompoundType.isNull()) {
12844       // C++2a [expr.ass]p5:
12845       //   A simple-assignment whose left operand is of a volatile-qualified
12846       //   type is deprecated unless the assignment is either a discarded-value
12847       //   expression or an unevaluated operand
12848       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12849     } else {
12850       // C++2a [expr.ass]p6:
12851       //   [Compound-assignment] expressions are deprecated if E1 has
12852       //   volatile-qualified type
12853       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12854     }
12855   }
12856 
12857   // C99 6.5.16p3: The type of an assignment expression is the type of the
12858   // left operand unless the left operand has qualified type, in which case
12859   // it is the unqualified version of the type of the left operand.
12860   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12861   // is converted to the type of the assignment expression (above).
12862   // C++ 5.17p1: the type of the assignment expression is that of its left
12863   // operand.
12864   return (getLangOpts().CPlusPlus
12865           ? LHSType : LHSType.getUnqualifiedType());
12866 }
12867 
12868 // Only ignore explicit casts to void.
12869 static bool IgnoreCommaOperand(const Expr *E) {
12870   E = E->IgnoreParens();
12871 
12872   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12873     if (CE->getCastKind() == CK_ToVoid) {
12874       return true;
12875     }
12876 
12877     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12878     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12879         CE->getSubExpr()->getType()->isDependentType()) {
12880       return true;
12881     }
12882   }
12883 
12884   return false;
12885 }
12886 
12887 // Look for instances where it is likely the comma operator is confused with
12888 // another operator.  There is a whitelist of acceptable expressions for the
12889 // left hand side of the comma operator, otherwise emit a warning.
12890 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12891   // No warnings in macros
12892   if (Loc.isMacroID())
12893     return;
12894 
12895   // Don't warn in template instantiations.
12896   if (inTemplateInstantiation())
12897     return;
12898 
12899   // Scope isn't fine-grained enough to whitelist the specific cases, so
12900   // instead, skip more than needed, then call back into here with the
12901   // CommaVisitor in SemaStmt.cpp.
12902   // The whitelisted locations are the initialization and increment portions
12903   // of a for loop.  The additional checks are on the condition of
12904   // if statements, do/while loops, and for loops.
12905   // Differences in scope flags for C89 mode requires the extra logic.
12906   const unsigned ForIncrementFlags =
12907       getLangOpts().C99 || getLangOpts().CPlusPlus
12908           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12909           : Scope::ContinueScope | Scope::BreakScope;
12910   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12911   const unsigned ScopeFlags = getCurScope()->getFlags();
12912   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12913       (ScopeFlags & ForInitFlags) == ForInitFlags)
12914     return;
12915 
12916   // If there are multiple comma operators used together, get the RHS of the
12917   // of the comma operator as the LHS.
12918   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12919     if (BO->getOpcode() != BO_Comma)
12920       break;
12921     LHS = BO->getRHS();
12922   }
12923 
12924   // Only allow some expressions on LHS to not warn.
12925   if (IgnoreCommaOperand(LHS))
12926     return;
12927 
12928   Diag(Loc, diag::warn_comma_operator);
12929   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12930       << LHS->getSourceRange()
12931       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12932                                     LangOpts.CPlusPlus ? "static_cast<void>("
12933                                                        : "(void)(")
12934       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12935                                     ")");
12936 }
12937 
12938 // C99 6.5.17
12939 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12940                                    SourceLocation Loc) {
12941   LHS = S.CheckPlaceholderExpr(LHS.get());
12942   RHS = S.CheckPlaceholderExpr(RHS.get());
12943   if (LHS.isInvalid() || RHS.isInvalid())
12944     return QualType();
12945 
12946   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12947   // operands, but not unary promotions.
12948   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12949 
12950   // So we treat the LHS as a ignored value, and in C++ we allow the
12951   // containing site to determine what should be done with the RHS.
12952   LHS = S.IgnoredValueConversions(LHS.get());
12953   if (LHS.isInvalid())
12954     return QualType();
12955 
12956   S.DiagnoseUnusedExprResult(LHS.get());
12957 
12958   if (!S.getLangOpts().CPlusPlus) {
12959     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12960     if (RHS.isInvalid())
12961       return QualType();
12962     if (!RHS.get()->getType()->isVoidType())
12963       S.RequireCompleteType(Loc, RHS.get()->getType(),
12964                             diag::err_incomplete_type);
12965   }
12966 
12967   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12968     S.DiagnoseCommaOperator(LHS.get(), Loc);
12969 
12970   return RHS.get()->getType();
12971 }
12972 
12973 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12974 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12975 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12976                                                ExprValueKind &VK,
12977                                                ExprObjectKind &OK,
12978                                                SourceLocation OpLoc,
12979                                                bool IsInc, bool IsPrefix) {
12980   if (Op->isTypeDependent())
12981     return S.Context.DependentTy;
12982 
12983   QualType ResType = Op->getType();
12984   // Atomic types can be used for increment / decrement where the non-atomic
12985   // versions can, so ignore the _Atomic() specifier for the purpose of
12986   // checking.
12987   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12988     ResType = ResAtomicType->getValueType();
12989 
12990   assert(!ResType.isNull() && "no type for increment/decrement expression");
12991 
12992   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12993     // Decrement of bool is not allowed.
12994     if (!IsInc) {
12995       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12996       return QualType();
12997     }
12998     // Increment of bool sets it to true, but is deprecated.
12999     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13000                                               : diag::warn_increment_bool)
13001       << Op->getSourceRange();
13002   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13003     // Error on enum increments and decrements in C++ mode
13004     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13005     return QualType();
13006   } else if (ResType->isRealType()) {
13007     // OK!
13008   } else if (ResType->isPointerType()) {
13009     // C99 6.5.2.4p2, 6.5.6p2
13010     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13011       return QualType();
13012   } else if (ResType->isObjCObjectPointerType()) {
13013     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13014     // Otherwise, we just need a complete type.
13015     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13016         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13017       return QualType();
13018   } else if (ResType->isAnyComplexType()) {
13019     // C99 does not support ++/-- on complex types, we allow as an extension.
13020     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13021       << ResType << Op->getSourceRange();
13022   } else if (ResType->isPlaceholderType()) {
13023     ExprResult PR = S.CheckPlaceholderExpr(Op);
13024     if (PR.isInvalid()) return QualType();
13025     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13026                                           IsInc, IsPrefix);
13027   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13028     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13029   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13030              (ResType->castAs<VectorType>()->getVectorKind() !=
13031               VectorType::AltiVecBool)) {
13032     // The z vector extensions allow ++ and -- for non-bool vectors.
13033   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13034             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13035     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13036   } else {
13037     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13038       << ResType << int(IsInc) << Op->getSourceRange();
13039     return QualType();
13040   }
13041   // At this point, we know we have a real, complex or pointer type.
13042   // Now make sure the operand is a modifiable lvalue.
13043   if (CheckForModifiableLvalue(Op, OpLoc, S))
13044     return QualType();
13045   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13046     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13047     //   An operand with volatile-qualified type is deprecated
13048     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13049         << IsInc << ResType;
13050   }
13051   // In C++, a prefix increment is the same type as the operand. Otherwise
13052   // (in C or with postfix), the increment is the unqualified type of the
13053   // operand.
13054   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13055     VK = VK_LValue;
13056     OK = Op->getObjectKind();
13057     return ResType;
13058   } else {
13059     VK = VK_RValue;
13060     return ResType.getUnqualifiedType();
13061   }
13062 }
13063 
13064 
13065 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13066 /// This routine allows us to typecheck complex/recursive expressions
13067 /// where the declaration is needed for type checking. We only need to
13068 /// handle cases when the expression references a function designator
13069 /// or is an lvalue. Here are some examples:
13070 ///  - &(x) => x
13071 ///  - &*****f => f for f a function designator.
13072 ///  - &s.xx => s
13073 ///  - &s.zz[1].yy -> s, if zz is an array
13074 ///  - *(x + 1) -> x, if x is an array
13075 ///  - &"123"[2] -> 0
13076 ///  - & __real__ x -> x
13077 ///
13078 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13079 /// members.
13080 static ValueDecl *getPrimaryDecl(Expr *E) {
13081   switch (E->getStmtClass()) {
13082   case Stmt::DeclRefExprClass:
13083     return cast<DeclRefExpr>(E)->getDecl();
13084   case Stmt::MemberExprClass:
13085     // If this is an arrow operator, the address is an offset from
13086     // the base's value, so the object the base refers to is
13087     // irrelevant.
13088     if (cast<MemberExpr>(E)->isArrow())
13089       return nullptr;
13090     // Otherwise, the expression refers to a part of the base
13091     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13092   case Stmt::ArraySubscriptExprClass: {
13093     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13094     // promotion of register arrays earlier.
13095     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13096     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13097       if (ICE->getSubExpr()->getType()->isArrayType())
13098         return getPrimaryDecl(ICE->getSubExpr());
13099     }
13100     return nullptr;
13101   }
13102   case Stmt::UnaryOperatorClass: {
13103     UnaryOperator *UO = cast<UnaryOperator>(E);
13104 
13105     switch(UO->getOpcode()) {
13106     case UO_Real:
13107     case UO_Imag:
13108     case UO_Extension:
13109       return getPrimaryDecl(UO->getSubExpr());
13110     default:
13111       return nullptr;
13112     }
13113   }
13114   case Stmt::ParenExprClass:
13115     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13116   case Stmt::ImplicitCastExprClass:
13117     // If the result of an implicit cast is an l-value, we care about
13118     // the sub-expression; otherwise, the result here doesn't matter.
13119     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13120   case Stmt::CXXUuidofExprClass:
13121     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13122   default:
13123     return nullptr;
13124   }
13125 }
13126 
13127 namespace {
13128 enum {
13129   AO_Bit_Field = 0,
13130   AO_Vector_Element = 1,
13131   AO_Property_Expansion = 2,
13132   AO_Register_Variable = 3,
13133   AO_Matrix_Element = 4,
13134   AO_No_Error = 5
13135 };
13136 }
13137 /// Diagnose invalid operand for address of operations.
13138 ///
13139 /// \param Type The type of operand which cannot have its address taken.
13140 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13141                                          Expr *E, unsigned Type) {
13142   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13143 }
13144 
13145 /// CheckAddressOfOperand - The operand of & must be either a function
13146 /// designator or an lvalue designating an object. If it is an lvalue, the
13147 /// object cannot be declared with storage class register or be a bit field.
13148 /// Note: The usual conversions are *not* applied to the operand of the &
13149 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13150 /// In C++, the operand might be an overloaded function name, in which case
13151 /// we allow the '&' but retain the overloaded-function type.
13152 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13153   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13154     if (PTy->getKind() == BuiltinType::Overload) {
13155       Expr *E = OrigOp.get()->IgnoreParens();
13156       if (!isa<OverloadExpr>(E)) {
13157         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13158         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13159           << OrigOp.get()->getSourceRange();
13160         return QualType();
13161       }
13162 
13163       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13164       if (isa<UnresolvedMemberExpr>(Ovl))
13165         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13166           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13167             << OrigOp.get()->getSourceRange();
13168           return QualType();
13169         }
13170 
13171       return Context.OverloadTy;
13172     }
13173 
13174     if (PTy->getKind() == BuiltinType::UnknownAny)
13175       return Context.UnknownAnyTy;
13176 
13177     if (PTy->getKind() == BuiltinType::BoundMember) {
13178       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13179         << OrigOp.get()->getSourceRange();
13180       return QualType();
13181     }
13182 
13183     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13184     if (OrigOp.isInvalid()) return QualType();
13185   }
13186 
13187   if (OrigOp.get()->isTypeDependent())
13188     return Context.DependentTy;
13189 
13190   assert(!OrigOp.get()->getType()->isPlaceholderType());
13191 
13192   // Make sure to ignore parentheses in subsequent checks
13193   Expr *op = OrigOp.get()->IgnoreParens();
13194 
13195   // In OpenCL captures for blocks called as lambda functions
13196   // are located in the private address space. Blocks used in
13197   // enqueue_kernel can be located in a different address space
13198   // depending on a vendor implementation. Thus preventing
13199   // taking an address of the capture to avoid invalid AS casts.
13200   if (LangOpts.OpenCL) {
13201     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13202     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13203       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13204       return QualType();
13205     }
13206   }
13207 
13208   if (getLangOpts().C99) {
13209     // Implement C99-only parts of addressof rules.
13210     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13211       if (uOp->getOpcode() == UO_Deref)
13212         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13213         // (assuming the deref expression is valid).
13214         return uOp->getSubExpr()->getType();
13215     }
13216     // Technically, there should be a check for array subscript
13217     // expressions here, but the result of one is always an lvalue anyway.
13218   }
13219   ValueDecl *dcl = getPrimaryDecl(op);
13220 
13221   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13222     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13223                                            op->getBeginLoc()))
13224       return QualType();
13225 
13226   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13227   unsigned AddressOfError = AO_No_Error;
13228 
13229   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13230     bool sfinae = (bool)isSFINAEContext();
13231     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13232                                   : diag::ext_typecheck_addrof_temporary)
13233       << op->getType() << op->getSourceRange();
13234     if (sfinae)
13235       return QualType();
13236     // Materialize the temporary as an lvalue so that we can take its address.
13237     OrigOp = op =
13238         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13239   } else if (isa<ObjCSelectorExpr>(op)) {
13240     return Context.getPointerType(op->getType());
13241   } else if (lval == Expr::LV_MemberFunction) {
13242     // If it's an instance method, make a member pointer.
13243     // The expression must have exactly the form &A::foo.
13244 
13245     // If the underlying expression isn't a decl ref, give up.
13246     if (!isa<DeclRefExpr>(op)) {
13247       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13248         << OrigOp.get()->getSourceRange();
13249       return QualType();
13250     }
13251     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13252     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13253 
13254     // The id-expression was parenthesized.
13255     if (OrigOp.get() != DRE) {
13256       Diag(OpLoc, diag::err_parens_pointer_member_function)
13257         << OrigOp.get()->getSourceRange();
13258 
13259     // The method was named without a qualifier.
13260     } else if (!DRE->getQualifier()) {
13261       if (MD->getParent()->getName().empty())
13262         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13263           << op->getSourceRange();
13264       else {
13265         SmallString<32> Str;
13266         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13267         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13268           << op->getSourceRange()
13269           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13270       }
13271     }
13272 
13273     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13274     if (isa<CXXDestructorDecl>(MD))
13275       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13276 
13277     QualType MPTy = Context.getMemberPointerType(
13278         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13279     // Under the MS ABI, lock down the inheritance model now.
13280     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13281       (void)isCompleteType(OpLoc, MPTy);
13282     return MPTy;
13283   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13284     // C99 6.5.3.2p1
13285     // The operand must be either an l-value or a function designator
13286     if (!op->getType()->isFunctionType()) {
13287       // Use a special diagnostic for loads from property references.
13288       if (isa<PseudoObjectExpr>(op)) {
13289         AddressOfError = AO_Property_Expansion;
13290       } else {
13291         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13292           << op->getType() << op->getSourceRange();
13293         return QualType();
13294       }
13295     }
13296   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13297     // The operand cannot be a bit-field
13298     AddressOfError = AO_Bit_Field;
13299   } else if (op->getObjectKind() == OK_VectorComponent) {
13300     // The operand cannot be an element of a vector
13301     AddressOfError = AO_Vector_Element;
13302   } else if (op->getObjectKind() == OK_MatrixComponent) {
13303     // The operand cannot be an element of a matrix.
13304     AddressOfError = AO_Matrix_Element;
13305   } else if (dcl) { // C99 6.5.3.2p1
13306     // We have an lvalue with a decl. Make sure the decl is not declared
13307     // with the register storage-class specifier.
13308     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13309       // in C++ it is not error to take address of a register
13310       // variable (c++03 7.1.1P3)
13311       if (vd->getStorageClass() == SC_Register &&
13312           !getLangOpts().CPlusPlus) {
13313         AddressOfError = AO_Register_Variable;
13314       }
13315     } else if (isa<MSPropertyDecl>(dcl)) {
13316       AddressOfError = AO_Property_Expansion;
13317     } else if (isa<FunctionTemplateDecl>(dcl)) {
13318       return Context.OverloadTy;
13319     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13320       // Okay: we can take the address of a field.
13321       // Could be a pointer to member, though, if there is an explicit
13322       // scope qualifier for the class.
13323       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13324         DeclContext *Ctx = dcl->getDeclContext();
13325         if (Ctx && Ctx->isRecord()) {
13326           if (dcl->getType()->isReferenceType()) {
13327             Diag(OpLoc,
13328                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13329               << dcl->getDeclName() << dcl->getType();
13330             return QualType();
13331           }
13332 
13333           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13334             Ctx = Ctx->getParent();
13335 
13336           QualType MPTy = Context.getMemberPointerType(
13337               op->getType(),
13338               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13339           // Under the MS ABI, lock down the inheritance model now.
13340           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13341             (void)isCompleteType(OpLoc, MPTy);
13342           return MPTy;
13343         }
13344       }
13345     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13346                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13347       llvm_unreachable("Unknown/unexpected decl type");
13348   }
13349 
13350   if (AddressOfError != AO_No_Error) {
13351     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13352     return QualType();
13353   }
13354 
13355   if (lval == Expr::LV_IncompleteVoidType) {
13356     // Taking the address of a void variable is technically illegal, but we
13357     // allow it in cases which are otherwise valid.
13358     // Example: "extern void x; void* y = &x;".
13359     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13360   }
13361 
13362   // If the operand has type "type", the result has type "pointer to type".
13363   if (op->getType()->isObjCObjectType())
13364     return Context.getObjCObjectPointerType(op->getType());
13365 
13366   CheckAddressOfPackedMember(op);
13367 
13368   return Context.getPointerType(op->getType());
13369 }
13370 
13371 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13372   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13373   if (!DRE)
13374     return;
13375   const Decl *D = DRE->getDecl();
13376   if (!D)
13377     return;
13378   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13379   if (!Param)
13380     return;
13381   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13382     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13383       return;
13384   if (FunctionScopeInfo *FD = S.getCurFunction())
13385     if (!FD->ModifiedNonNullParams.count(Param))
13386       FD->ModifiedNonNullParams.insert(Param);
13387 }
13388 
13389 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13390 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13391                                         SourceLocation OpLoc) {
13392   if (Op->isTypeDependent())
13393     return S.Context.DependentTy;
13394 
13395   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13396   if (ConvResult.isInvalid())
13397     return QualType();
13398   Op = ConvResult.get();
13399   QualType OpTy = Op->getType();
13400   QualType Result;
13401 
13402   if (isa<CXXReinterpretCastExpr>(Op)) {
13403     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13404     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13405                                      Op->getSourceRange());
13406   }
13407 
13408   if (const PointerType *PT = OpTy->getAs<PointerType>())
13409   {
13410     Result = PT->getPointeeType();
13411   }
13412   else if (const ObjCObjectPointerType *OPT =
13413              OpTy->getAs<ObjCObjectPointerType>())
13414     Result = OPT->getPointeeType();
13415   else {
13416     ExprResult PR = S.CheckPlaceholderExpr(Op);
13417     if (PR.isInvalid()) return QualType();
13418     if (PR.get() != Op)
13419       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13420   }
13421 
13422   if (Result.isNull()) {
13423     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13424       << OpTy << Op->getSourceRange();
13425     return QualType();
13426   }
13427 
13428   // Note that per both C89 and C99, indirection is always legal, even if Result
13429   // is an incomplete type or void.  It would be possible to warn about
13430   // dereferencing a void pointer, but it's completely well-defined, and such a
13431   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13432   // for pointers to 'void' but is fine for any other pointer type:
13433   //
13434   // C++ [expr.unary.op]p1:
13435   //   [...] the expression to which [the unary * operator] is applied shall
13436   //   be a pointer to an object type, or a pointer to a function type
13437   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13438     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13439       << OpTy << Op->getSourceRange();
13440 
13441   // Dereferences are usually l-values...
13442   VK = VK_LValue;
13443 
13444   // ...except that certain expressions are never l-values in C.
13445   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13446     VK = VK_RValue;
13447 
13448   return Result;
13449 }
13450 
13451 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13452   BinaryOperatorKind Opc;
13453   switch (Kind) {
13454   default: llvm_unreachable("Unknown binop!");
13455   case tok::periodstar:           Opc = BO_PtrMemD; break;
13456   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13457   case tok::star:                 Opc = BO_Mul; break;
13458   case tok::slash:                Opc = BO_Div; break;
13459   case tok::percent:              Opc = BO_Rem; break;
13460   case tok::plus:                 Opc = BO_Add; break;
13461   case tok::minus:                Opc = BO_Sub; break;
13462   case tok::lessless:             Opc = BO_Shl; break;
13463   case tok::greatergreater:       Opc = BO_Shr; break;
13464   case tok::lessequal:            Opc = BO_LE; break;
13465   case tok::less:                 Opc = BO_LT; break;
13466   case tok::greaterequal:         Opc = BO_GE; break;
13467   case tok::greater:              Opc = BO_GT; break;
13468   case tok::exclaimequal:         Opc = BO_NE; break;
13469   case tok::equalequal:           Opc = BO_EQ; break;
13470   case tok::spaceship:            Opc = BO_Cmp; break;
13471   case tok::amp:                  Opc = BO_And; break;
13472   case tok::caret:                Opc = BO_Xor; break;
13473   case tok::pipe:                 Opc = BO_Or; break;
13474   case tok::ampamp:               Opc = BO_LAnd; break;
13475   case tok::pipepipe:             Opc = BO_LOr; break;
13476   case tok::equal:                Opc = BO_Assign; break;
13477   case tok::starequal:            Opc = BO_MulAssign; break;
13478   case tok::slashequal:           Opc = BO_DivAssign; break;
13479   case tok::percentequal:         Opc = BO_RemAssign; break;
13480   case tok::plusequal:            Opc = BO_AddAssign; break;
13481   case tok::minusequal:           Opc = BO_SubAssign; break;
13482   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13483   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13484   case tok::ampequal:             Opc = BO_AndAssign; break;
13485   case tok::caretequal:           Opc = BO_XorAssign; break;
13486   case tok::pipeequal:            Opc = BO_OrAssign; break;
13487   case tok::comma:                Opc = BO_Comma; break;
13488   }
13489   return Opc;
13490 }
13491 
13492 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13493   tok::TokenKind Kind) {
13494   UnaryOperatorKind Opc;
13495   switch (Kind) {
13496   default: llvm_unreachable("Unknown unary op!");
13497   case tok::plusplus:     Opc = UO_PreInc; break;
13498   case tok::minusminus:   Opc = UO_PreDec; break;
13499   case tok::amp:          Opc = UO_AddrOf; break;
13500   case tok::star:         Opc = UO_Deref; break;
13501   case tok::plus:         Opc = UO_Plus; break;
13502   case tok::minus:        Opc = UO_Minus; break;
13503   case tok::tilde:        Opc = UO_Not; break;
13504   case tok::exclaim:      Opc = UO_LNot; break;
13505   case tok::kw___real:    Opc = UO_Real; break;
13506   case tok::kw___imag:    Opc = UO_Imag; break;
13507   case tok::kw___extension__: Opc = UO_Extension; break;
13508   }
13509   return Opc;
13510 }
13511 
13512 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13513 /// This warning suppressed in the event of macro expansions.
13514 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13515                                    SourceLocation OpLoc, bool IsBuiltin) {
13516   if (S.inTemplateInstantiation())
13517     return;
13518   if (S.isUnevaluatedContext())
13519     return;
13520   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13521     return;
13522   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13523   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13524   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13525   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13526   if (!LHSDeclRef || !RHSDeclRef ||
13527       LHSDeclRef->getLocation().isMacroID() ||
13528       RHSDeclRef->getLocation().isMacroID())
13529     return;
13530   const ValueDecl *LHSDecl =
13531     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13532   const ValueDecl *RHSDecl =
13533     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13534   if (LHSDecl != RHSDecl)
13535     return;
13536   if (LHSDecl->getType().isVolatileQualified())
13537     return;
13538   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13539     if (RefTy->getPointeeType().isVolatileQualified())
13540       return;
13541 
13542   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13543                           : diag::warn_self_assignment_overloaded)
13544       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13545       << RHSExpr->getSourceRange();
13546 }
13547 
13548 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13549 /// is usually indicative of introspection within the Objective-C pointer.
13550 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13551                                           SourceLocation OpLoc) {
13552   if (!S.getLangOpts().ObjC)
13553     return;
13554 
13555   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13556   const Expr *LHS = L.get();
13557   const Expr *RHS = R.get();
13558 
13559   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13560     ObjCPointerExpr = LHS;
13561     OtherExpr = RHS;
13562   }
13563   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13564     ObjCPointerExpr = RHS;
13565     OtherExpr = LHS;
13566   }
13567 
13568   // This warning is deliberately made very specific to reduce false
13569   // positives with logic that uses '&' for hashing.  This logic mainly
13570   // looks for code trying to introspect into tagged pointers, which
13571   // code should generally never do.
13572   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13573     unsigned Diag = diag::warn_objc_pointer_masking;
13574     // Determine if we are introspecting the result of performSelectorXXX.
13575     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13576     // Special case messages to -performSelector and friends, which
13577     // can return non-pointer values boxed in a pointer value.
13578     // Some clients may wish to silence warnings in this subcase.
13579     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13580       Selector S = ME->getSelector();
13581       StringRef SelArg0 = S.getNameForSlot(0);
13582       if (SelArg0.startswith("performSelector"))
13583         Diag = diag::warn_objc_pointer_masking_performSelector;
13584     }
13585 
13586     S.Diag(OpLoc, Diag)
13587       << ObjCPointerExpr->getSourceRange();
13588   }
13589 }
13590 
13591 static NamedDecl *getDeclFromExpr(Expr *E) {
13592   if (!E)
13593     return nullptr;
13594   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13595     return DRE->getDecl();
13596   if (auto *ME = dyn_cast<MemberExpr>(E))
13597     return ME->getMemberDecl();
13598   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13599     return IRE->getDecl();
13600   return nullptr;
13601 }
13602 
13603 // This helper function promotes a binary operator's operands (which are of a
13604 // half vector type) to a vector of floats and then truncates the result to
13605 // a vector of either half or short.
13606 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13607                                       BinaryOperatorKind Opc, QualType ResultTy,
13608                                       ExprValueKind VK, ExprObjectKind OK,
13609                                       bool IsCompAssign, SourceLocation OpLoc,
13610                                       FPOptions FPFeatures) {
13611   auto &Context = S.getASTContext();
13612   assert((isVector(ResultTy, Context.HalfTy) ||
13613           isVector(ResultTy, Context.ShortTy)) &&
13614          "Result must be a vector of half or short");
13615   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13616          isVector(RHS.get()->getType(), Context.HalfTy) &&
13617          "both operands expected to be a half vector");
13618 
13619   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13620   QualType BinOpResTy = RHS.get()->getType();
13621 
13622   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13623   // change BinOpResTy to a vector of ints.
13624   if (isVector(ResultTy, Context.ShortTy))
13625     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13626 
13627   if (IsCompAssign)
13628     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13629                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13630                                           BinOpResTy, BinOpResTy);
13631 
13632   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13633   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13634                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13635   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13636 }
13637 
13638 static std::pair<ExprResult, ExprResult>
13639 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13640                            Expr *RHSExpr) {
13641   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13642   if (!S.getLangOpts().CPlusPlus) {
13643     // C cannot handle TypoExpr nodes on either side of a binop because it
13644     // doesn't handle dependent types properly, so make sure any TypoExprs have
13645     // been dealt with before checking the operands.
13646     LHS = S.CorrectDelayedTyposInExpr(LHS);
13647     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13648       if (Opc != BO_Assign)
13649         return ExprResult(E);
13650       // Avoid correcting the RHS to the same Expr as the LHS.
13651       Decl *D = getDeclFromExpr(E);
13652       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13653     });
13654   }
13655   return std::make_pair(LHS, RHS);
13656 }
13657 
13658 /// Returns true if conversion between vectors of halfs and vectors of floats
13659 /// is needed.
13660 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13661                                      Expr *E0, Expr *E1 = nullptr) {
13662   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13663       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13664     return false;
13665 
13666   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13667     QualType Ty = E->IgnoreImplicit()->getType();
13668 
13669     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13670     // to vectors of floats. Although the element type of the vectors is __fp16,
13671     // the vectors shouldn't be treated as storage-only types. See the
13672     // discussion here: https://reviews.llvm.org/rG825235c140e7
13673     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13674       if (VT->getVectorKind() == VectorType::NeonVector)
13675         return false;
13676       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13677     }
13678     return false;
13679   };
13680 
13681   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13682 }
13683 
13684 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13685 /// operator @p Opc at location @c TokLoc. This routine only supports
13686 /// built-in operations; ActOnBinOp handles overloaded operators.
13687 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13688                                     BinaryOperatorKind Opc,
13689                                     Expr *LHSExpr, Expr *RHSExpr) {
13690   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13691     // The syntax only allows initializer lists on the RHS of assignment,
13692     // so we don't need to worry about accepting invalid code for
13693     // non-assignment operators.
13694     // C++11 5.17p9:
13695     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13696     //   of x = {} is x = T().
13697     InitializationKind Kind = InitializationKind::CreateDirectList(
13698         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13699     InitializedEntity Entity =
13700         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13701     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13702     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13703     if (Init.isInvalid())
13704       return Init;
13705     RHSExpr = Init.get();
13706   }
13707 
13708   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13709   QualType ResultTy;     // Result type of the binary operator.
13710   // The following two variables are used for compound assignment operators
13711   QualType CompLHSTy;    // Type of LHS after promotions for computation
13712   QualType CompResultTy; // Type of computation result
13713   ExprValueKind VK = VK_RValue;
13714   ExprObjectKind OK = OK_Ordinary;
13715   bool ConvertHalfVec = false;
13716 
13717   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13718   if (!LHS.isUsable() || !RHS.isUsable())
13719     return ExprError();
13720 
13721   if (getLangOpts().OpenCL) {
13722     QualType LHSTy = LHSExpr->getType();
13723     QualType RHSTy = RHSExpr->getType();
13724     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13725     // the ATOMIC_VAR_INIT macro.
13726     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13727       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13728       if (BO_Assign == Opc)
13729         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13730       else
13731         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13732       return ExprError();
13733     }
13734 
13735     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13736     // only with a builtin functions and therefore should be disallowed here.
13737     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13738         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13739         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13740         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13741       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13742       return ExprError();
13743     }
13744   }
13745 
13746   switch (Opc) {
13747   case BO_Assign:
13748     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13749     if (getLangOpts().CPlusPlus &&
13750         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13751       VK = LHS.get()->getValueKind();
13752       OK = LHS.get()->getObjectKind();
13753     }
13754     if (!ResultTy.isNull()) {
13755       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13756       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13757 
13758       // Avoid copying a block to the heap if the block is assigned to a local
13759       // auto variable that is declared in the same scope as the block. This
13760       // optimization is unsafe if the local variable is declared in an outer
13761       // scope. For example:
13762       //
13763       // BlockTy b;
13764       // {
13765       //   b = ^{...};
13766       // }
13767       // // It is unsafe to invoke the block here if it wasn't copied to the
13768       // // heap.
13769       // b();
13770 
13771       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13772         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13773           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13774             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13775               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13776 
13777       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13778         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13779                               NTCUC_Assignment, NTCUK_Copy);
13780     }
13781     RecordModifiableNonNullParam(*this, LHS.get());
13782     break;
13783   case BO_PtrMemD:
13784   case BO_PtrMemI:
13785     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13786                                             Opc == BO_PtrMemI);
13787     break;
13788   case BO_Mul:
13789   case BO_Div:
13790     ConvertHalfVec = true;
13791     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13792                                            Opc == BO_Div);
13793     break;
13794   case BO_Rem:
13795     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13796     break;
13797   case BO_Add:
13798     ConvertHalfVec = true;
13799     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13800     break;
13801   case BO_Sub:
13802     ConvertHalfVec = true;
13803     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13804     break;
13805   case BO_Shl:
13806   case BO_Shr:
13807     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13808     break;
13809   case BO_LE:
13810   case BO_LT:
13811   case BO_GE:
13812   case BO_GT:
13813     ConvertHalfVec = true;
13814     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13815     break;
13816   case BO_EQ:
13817   case BO_NE:
13818     ConvertHalfVec = true;
13819     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13820     break;
13821   case BO_Cmp:
13822     ConvertHalfVec = true;
13823     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13824     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13825     break;
13826   case BO_And:
13827     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13828     LLVM_FALLTHROUGH;
13829   case BO_Xor:
13830   case BO_Or:
13831     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13832     break;
13833   case BO_LAnd:
13834   case BO_LOr:
13835     ConvertHalfVec = true;
13836     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13837     break;
13838   case BO_MulAssign:
13839   case BO_DivAssign:
13840     ConvertHalfVec = true;
13841     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13842                                                Opc == BO_DivAssign);
13843     CompLHSTy = CompResultTy;
13844     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13845       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13846     break;
13847   case BO_RemAssign:
13848     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13849     CompLHSTy = CompResultTy;
13850     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13851       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13852     break;
13853   case BO_AddAssign:
13854     ConvertHalfVec = true;
13855     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13856     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13857       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13858     break;
13859   case BO_SubAssign:
13860     ConvertHalfVec = true;
13861     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13862     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13863       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13864     break;
13865   case BO_ShlAssign:
13866   case BO_ShrAssign:
13867     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13868     CompLHSTy = CompResultTy;
13869     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13870       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13871     break;
13872   case BO_AndAssign:
13873   case BO_OrAssign: // fallthrough
13874     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13875     LLVM_FALLTHROUGH;
13876   case BO_XorAssign:
13877     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13878     CompLHSTy = CompResultTy;
13879     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13880       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13881     break;
13882   case BO_Comma:
13883     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13884     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13885       VK = RHS.get()->getValueKind();
13886       OK = RHS.get()->getObjectKind();
13887     }
13888     break;
13889   }
13890   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13891     return ExprError();
13892 
13893   // Some of the binary operations require promoting operands of half vector to
13894   // float vectors and truncating the result back to half vector. For now, we do
13895   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13896   // arm64).
13897   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13898          isVector(LHS.get()->getType(), Context.HalfTy) &&
13899          "both sides are half vectors or neither sides are");
13900   ConvertHalfVec =
13901       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13902 
13903   // Check for array bounds violations for both sides of the BinaryOperator
13904   CheckArrayAccess(LHS.get());
13905   CheckArrayAccess(RHS.get());
13906 
13907   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13908     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13909                                                  &Context.Idents.get("object_setClass"),
13910                                                  SourceLocation(), LookupOrdinaryName);
13911     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13912       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13913       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13914           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13915                                         "object_setClass(")
13916           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13917                                           ",")
13918           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13919     }
13920     else
13921       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13922   }
13923   else if (const ObjCIvarRefExpr *OIRE =
13924            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13925     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13926 
13927   // Opc is not a compound assignment if CompResultTy is null.
13928   if (CompResultTy.isNull()) {
13929     if (ConvertHalfVec)
13930       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13931                                  OpLoc, CurFPFeatures);
13932     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13933                                   VK, OK, OpLoc, CurFPFeatures);
13934   }
13935 
13936   // Handle compound assignments.
13937   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13938       OK_ObjCProperty) {
13939     VK = VK_LValue;
13940     OK = LHS.get()->getObjectKind();
13941   }
13942 
13943   // The LHS is not converted to the result type for fixed-point compound
13944   // assignment as the common type is computed on demand. Reset the CompLHSTy
13945   // to the LHS type we would have gotten after unary conversions.
13946   if (CompResultTy->isFixedPointType())
13947     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13948 
13949   if (ConvertHalfVec)
13950     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13951                                OpLoc, CurFPFeatures);
13952 
13953   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13954                                         ResultTy, VK, OK, OpLoc, CurFPFeatures,
13955                                         CompLHSTy, CompResultTy);
13956 }
13957 
13958 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13959 /// operators are mixed in a way that suggests that the programmer forgot that
13960 /// comparison operators have higher precedence. The most typical example of
13961 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13962 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13963                                       SourceLocation OpLoc, Expr *LHSExpr,
13964                                       Expr *RHSExpr) {
13965   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13966   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13967 
13968   // Check that one of the sides is a comparison operator and the other isn't.
13969   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13970   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13971   if (isLeftComp == isRightComp)
13972     return;
13973 
13974   // Bitwise operations are sometimes used as eager logical ops.
13975   // Don't diagnose this.
13976   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13977   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13978   if (isLeftBitwise || isRightBitwise)
13979     return;
13980 
13981   SourceRange DiagRange = isLeftComp
13982                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13983                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13984   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13985   SourceRange ParensRange =
13986       isLeftComp
13987           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13988           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13989 
13990   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13991     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13992   SuggestParentheses(Self, OpLoc,
13993     Self.PDiag(diag::note_precedence_silence) << OpStr,
13994     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13995   SuggestParentheses(Self, OpLoc,
13996     Self.PDiag(diag::note_precedence_bitwise_first)
13997       << BinaryOperator::getOpcodeStr(Opc),
13998     ParensRange);
13999 }
14000 
14001 /// It accepts a '&&' expr that is inside a '||' one.
14002 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14003 /// in parentheses.
14004 static void
14005 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14006                                        BinaryOperator *Bop) {
14007   assert(Bop->getOpcode() == BO_LAnd);
14008   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14009       << Bop->getSourceRange() << OpLoc;
14010   SuggestParentheses(Self, Bop->getOperatorLoc(),
14011     Self.PDiag(diag::note_precedence_silence)
14012       << Bop->getOpcodeStr(),
14013     Bop->getSourceRange());
14014 }
14015 
14016 /// Returns true if the given expression can be evaluated as a constant
14017 /// 'true'.
14018 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14019   bool Res;
14020   return !E->isValueDependent() &&
14021          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14022 }
14023 
14024 /// Returns true if the given expression can be evaluated as a constant
14025 /// 'false'.
14026 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14027   bool Res;
14028   return !E->isValueDependent() &&
14029          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14030 }
14031 
14032 /// Look for '&&' in the left hand of a '||' expr.
14033 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14034                                              Expr *LHSExpr, Expr *RHSExpr) {
14035   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14036     if (Bop->getOpcode() == BO_LAnd) {
14037       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14038       if (EvaluatesAsFalse(S, RHSExpr))
14039         return;
14040       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14041       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14042         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14043     } else if (Bop->getOpcode() == BO_LOr) {
14044       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14045         // If it's "a || b && 1 || c" we didn't warn earlier for
14046         // "a || b && 1", but warn now.
14047         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14048           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14049       }
14050     }
14051   }
14052 }
14053 
14054 /// Look for '&&' in the right hand of a '||' expr.
14055 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14056                                              Expr *LHSExpr, Expr *RHSExpr) {
14057   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14058     if (Bop->getOpcode() == BO_LAnd) {
14059       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14060       if (EvaluatesAsFalse(S, LHSExpr))
14061         return;
14062       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14063       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14064         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14065     }
14066   }
14067 }
14068 
14069 /// Look for bitwise op in the left or right hand of a bitwise op with
14070 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14071 /// the '&' expression in parentheses.
14072 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14073                                          SourceLocation OpLoc, Expr *SubExpr) {
14074   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14075     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14076       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14077         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14078         << Bop->getSourceRange() << OpLoc;
14079       SuggestParentheses(S, Bop->getOperatorLoc(),
14080         S.PDiag(diag::note_precedence_silence)
14081           << Bop->getOpcodeStr(),
14082         Bop->getSourceRange());
14083     }
14084   }
14085 }
14086 
14087 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14088                                     Expr *SubExpr, StringRef Shift) {
14089   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14090     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14091       StringRef Op = Bop->getOpcodeStr();
14092       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14093           << Bop->getSourceRange() << OpLoc << Shift << Op;
14094       SuggestParentheses(S, Bop->getOperatorLoc(),
14095           S.PDiag(diag::note_precedence_silence) << Op,
14096           Bop->getSourceRange());
14097     }
14098   }
14099 }
14100 
14101 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14102                                  Expr *LHSExpr, Expr *RHSExpr) {
14103   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14104   if (!OCE)
14105     return;
14106 
14107   FunctionDecl *FD = OCE->getDirectCallee();
14108   if (!FD || !FD->isOverloadedOperator())
14109     return;
14110 
14111   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14112   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14113     return;
14114 
14115   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14116       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14117       << (Kind == OO_LessLess);
14118   SuggestParentheses(S, OCE->getOperatorLoc(),
14119                      S.PDiag(diag::note_precedence_silence)
14120                          << (Kind == OO_LessLess ? "<<" : ">>"),
14121                      OCE->getSourceRange());
14122   SuggestParentheses(
14123       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14124       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14125 }
14126 
14127 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14128 /// precedence.
14129 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14130                                     SourceLocation OpLoc, Expr *LHSExpr,
14131                                     Expr *RHSExpr){
14132   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14133   if (BinaryOperator::isBitwiseOp(Opc))
14134     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14135 
14136   // Diagnose "arg1 & arg2 | arg3"
14137   if ((Opc == BO_Or || Opc == BO_Xor) &&
14138       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14139     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14140     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14141   }
14142 
14143   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14144   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14145   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14146     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14147     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14148   }
14149 
14150   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14151       || Opc == BO_Shr) {
14152     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14153     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14154     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14155   }
14156 
14157   // Warn on overloaded shift operators and comparisons, such as:
14158   // cout << 5 == 4;
14159   if (BinaryOperator::isComparisonOp(Opc))
14160     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14161 }
14162 
14163 // Binary Operators.  'Tok' is the token for the operator.
14164 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14165                             tok::TokenKind Kind,
14166                             Expr *LHSExpr, Expr *RHSExpr) {
14167   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14168   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14169   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14170 
14171   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14172   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14173 
14174   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14175 }
14176 
14177 /// Build an overloaded binary operator expression in the given scope.
14178 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14179                                        BinaryOperatorKind Opc,
14180                                        Expr *LHS, Expr *RHS) {
14181   switch (Opc) {
14182   case BO_Assign:
14183   case BO_DivAssign:
14184   case BO_RemAssign:
14185   case BO_SubAssign:
14186   case BO_AndAssign:
14187   case BO_OrAssign:
14188   case BO_XorAssign:
14189     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14190     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14191     break;
14192   default:
14193     break;
14194   }
14195 
14196   // Find all of the overloaded operators visible from this
14197   // point. We perform both an operator-name lookup from the local
14198   // scope and an argument-dependent lookup based on the types of
14199   // the arguments.
14200   UnresolvedSet<16> Functions;
14201   OverloadedOperatorKind OverOp
14202     = BinaryOperator::getOverloadedOperator(Opc);
14203   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14204     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14205                                    RHS->getType(), Functions);
14206 
14207   // In C++20 onwards, we may have a second operator to look up.
14208   if (S.getLangOpts().CPlusPlus20) {
14209     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14210       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14211                                      RHS->getType(), Functions);
14212   }
14213 
14214   // Build the (potentially-overloaded, potentially-dependent)
14215   // binary operation.
14216   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14217 }
14218 
14219 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14220                             BinaryOperatorKind Opc,
14221                             Expr *LHSExpr, Expr *RHSExpr) {
14222   ExprResult LHS, RHS;
14223   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14224   if (!LHS.isUsable() || !RHS.isUsable())
14225     return ExprError();
14226   LHSExpr = LHS.get();
14227   RHSExpr = RHS.get();
14228 
14229   // We want to end up calling one of checkPseudoObjectAssignment
14230   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14231   // both expressions are overloadable or either is type-dependent),
14232   // or CreateBuiltinBinOp (in any other case).  We also want to get
14233   // any placeholder types out of the way.
14234 
14235   // Handle pseudo-objects in the LHS.
14236   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14237     // Assignments with a pseudo-object l-value need special analysis.
14238     if (pty->getKind() == BuiltinType::PseudoObject &&
14239         BinaryOperator::isAssignmentOp(Opc))
14240       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14241 
14242     // Don't resolve overloads if the other type is overloadable.
14243     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14244       // We can't actually test that if we still have a placeholder,
14245       // though.  Fortunately, none of the exceptions we see in that
14246       // code below are valid when the LHS is an overload set.  Note
14247       // that an overload set can be dependently-typed, but it never
14248       // instantiates to having an overloadable type.
14249       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14250       if (resolvedRHS.isInvalid()) return ExprError();
14251       RHSExpr = resolvedRHS.get();
14252 
14253       if (RHSExpr->isTypeDependent() ||
14254           RHSExpr->getType()->isOverloadableType())
14255         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14256     }
14257 
14258     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14259     // template, diagnose the missing 'template' keyword instead of diagnosing
14260     // an invalid use of a bound member function.
14261     //
14262     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14263     // to C++1z [over.over]/1.4, but we already checked for that case above.
14264     if (Opc == BO_LT && inTemplateInstantiation() &&
14265         (pty->getKind() == BuiltinType::BoundMember ||
14266          pty->getKind() == BuiltinType::Overload)) {
14267       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14268       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14269           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14270             return isa<FunctionTemplateDecl>(ND);
14271           })) {
14272         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14273                                 : OE->getNameLoc(),
14274              diag::err_template_kw_missing)
14275           << OE->getName().getAsString() << "";
14276         return ExprError();
14277       }
14278     }
14279 
14280     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14281     if (LHS.isInvalid()) return ExprError();
14282     LHSExpr = LHS.get();
14283   }
14284 
14285   // Handle pseudo-objects in the RHS.
14286   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14287     // An overload in the RHS can potentially be resolved by the type
14288     // being assigned to.
14289     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14290       if (getLangOpts().CPlusPlus &&
14291           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14292            LHSExpr->getType()->isOverloadableType()))
14293         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14294 
14295       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14296     }
14297 
14298     // Don't resolve overloads if the other type is overloadable.
14299     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14300         LHSExpr->getType()->isOverloadableType())
14301       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14302 
14303     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14304     if (!resolvedRHS.isUsable()) return ExprError();
14305     RHSExpr = resolvedRHS.get();
14306   }
14307 
14308   if (getLangOpts().CPlusPlus) {
14309     // If either expression is type-dependent, always build an
14310     // overloaded op.
14311     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14312       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14313 
14314     // Otherwise, build an overloaded op if either expression has an
14315     // overloadable type.
14316     if (LHSExpr->getType()->isOverloadableType() ||
14317         RHSExpr->getType()->isOverloadableType())
14318       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14319   }
14320 
14321   // Build a built-in binary operation.
14322   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14323 }
14324 
14325 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14326   if (T.isNull() || T->isDependentType())
14327     return false;
14328 
14329   if (!T->isPromotableIntegerType())
14330     return true;
14331 
14332   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14333 }
14334 
14335 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14336                                       UnaryOperatorKind Opc,
14337                                       Expr *InputExpr) {
14338   ExprResult Input = InputExpr;
14339   ExprValueKind VK = VK_RValue;
14340   ExprObjectKind OK = OK_Ordinary;
14341   QualType resultType;
14342   bool CanOverflow = false;
14343 
14344   bool ConvertHalfVec = false;
14345   if (getLangOpts().OpenCL) {
14346     QualType Ty = InputExpr->getType();
14347     // The only legal unary operation for atomics is '&'.
14348     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14349     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14350     // only with a builtin functions and therefore should be disallowed here.
14351         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14352         || Ty->isBlockPointerType())) {
14353       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14354                        << InputExpr->getType()
14355                        << Input.get()->getSourceRange());
14356     }
14357   }
14358 
14359   switch (Opc) {
14360   case UO_PreInc:
14361   case UO_PreDec:
14362   case UO_PostInc:
14363   case UO_PostDec:
14364     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14365                                                 OpLoc,
14366                                                 Opc == UO_PreInc ||
14367                                                 Opc == UO_PostInc,
14368                                                 Opc == UO_PreInc ||
14369                                                 Opc == UO_PreDec);
14370     CanOverflow = isOverflowingIntegerType(Context, resultType);
14371     break;
14372   case UO_AddrOf:
14373     resultType = CheckAddressOfOperand(Input, OpLoc);
14374     CheckAddressOfNoDeref(InputExpr);
14375     RecordModifiableNonNullParam(*this, InputExpr);
14376     break;
14377   case UO_Deref: {
14378     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14379     if (Input.isInvalid()) return ExprError();
14380     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14381     break;
14382   }
14383   case UO_Plus:
14384   case UO_Minus:
14385     CanOverflow = Opc == UO_Minus &&
14386                   isOverflowingIntegerType(Context, Input.get()->getType());
14387     Input = UsualUnaryConversions(Input.get());
14388     if (Input.isInvalid()) return ExprError();
14389     // Unary plus and minus require promoting an operand of half vector to a
14390     // float vector and truncating the result back to a half vector. For now, we
14391     // do this only when HalfArgsAndReturns is set (that is, when the target is
14392     // arm or arm64).
14393     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14394 
14395     // If the operand is a half vector, promote it to a float vector.
14396     if (ConvertHalfVec)
14397       Input = convertVector(Input.get(), Context.FloatTy, *this);
14398     resultType = Input.get()->getType();
14399     if (resultType->isDependentType())
14400       break;
14401     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14402       break;
14403     else if (resultType->isVectorType() &&
14404              // The z vector extensions don't allow + or - with bool vectors.
14405              (!Context.getLangOpts().ZVector ||
14406               resultType->castAs<VectorType>()->getVectorKind() !=
14407               VectorType::AltiVecBool))
14408       break;
14409     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14410              Opc == UO_Plus &&
14411              resultType->isPointerType())
14412       break;
14413 
14414     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14415       << resultType << Input.get()->getSourceRange());
14416 
14417   case UO_Not: // bitwise complement
14418     Input = UsualUnaryConversions(Input.get());
14419     if (Input.isInvalid())
14420       return ExprError();
14421     resultType = Input.get()->getType();
14422     if (resultType->isDependentType())
14423       break;
14424     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14425     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14426       // C99 does not support '~' for complex conjugation.
14427       Diag(OpLoc, diag::ext_integer_complement_complex)
14428           << resultType << Input.get()->getSourceRange();
14429     else if (resultType->hasIntegerRepresentation())
14430       break;
14431     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14432       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14433       // on vector float types.
14434       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14435       if (!T->isIntegerType())
14436         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14437                           << resultType << Input.get()->getSourceRange());
14438     } else {
14439       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14440                        << resultType << Input.get()->getSourceRange());
14441     }
14442     break;
14443 
14444   case UO_LNot: // logical negation
14445     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14446     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14447     if (Input.isInvalid()) return ExprError();
14448     resultType = Input.get()->getType();
14449 
14450     // Though we still have to promote half FP to float...
14451     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14452       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14453       resultType = Context.FloatTy;
14454     }
14455 
14456     if (resultType->isDependentType())
14457       break;
14458     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14459       // C99 6.5.3.3p1: ok, fallthrough;
14460       if (Context.getLangOpts().CPlusPlus) {
14461         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14462         // operand contextually converted to bool.
14463         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14464                                   ScalarTypeToBooleanCastKind(resultType));
14465       } else if (Context.getLangOpts().OpenCL &&
14466                  Context.getLangOpts().OpenCLVersion < 120) {
14467         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14468         // operate on scalar float types.
14469         if (!resultType->isIntegerType() && !resultType->isPointerType())
14470           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14471                            << resultType << Input.get()->getSourceRange());
14472       }
14473     } else if (resultType->isExtVectorType()) {
14474       if (Context.getLangOpts().OpenCL &&
14475           Context.getLangOpts().OpenCLVersion < 120 &&
14476           !Context.getLangOpts().OpenCLCPlusPlus) {
14477         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14478         // operate on vector float types.
14479         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14480         if (!T->isIntegerType())
14481           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14482                            << resultType << Input.get()->getSourceRange());
14483       }
14484       // Vector logical not returns the signed variant of the operand type.
14485       resultType = GetSignedVectorType(resultType);
14486       break;
14487     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14488       const VectorType *VTy = resultType->castAs<VectorType>();
14489       if (VTy->getVectorKind() != VectorType::GenericVector)
14490         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14491                          << resultType << Input.get()->getSourceRange());
14492 
14493       // Vector logical not returns the signed variant of the operand type.
14494       resultType = GetSignedVectorType(resultType);
14495       break;
14496     } else {
14497       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14498         << resultType << Input.get()->getSourceRange());
14499     }
14500 
14501     // LNot always has type int. C99 6.5.3.3p5.
14502     // In C++, it's bool. C++ 5.3.1p8
14503     resultType = Context.getLogicalOperationType();
14504     break;
14505   case UO_Real:
14506   case UO_Imag:
14507     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14508     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14509     // complex l-values to ordinary l-values and all other values to r-values.
14510     if (Input.isInvalid()) return ExprError();
14511     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14512       if (Input.get()->getValueKind() != VK_RValue &&
14513           Input.get()->getObjectKind() == OK_Ordinary)
14514         VK = Input.get()->getValueKind();
14515     } else if (!getLangOpts().CPlusPlus) {
14516       // In C, a volatile scalar is read by __imag. In C++, it is not.
14517       Input = DefaultLvalueConversion(Input.get());
14518     }
14519     break;
14520   case UO_Extension:
14521     resultType = Input.get()->getType();
14522     VK = Input.get()->getValueKind();
14523     OK = Input.get()->getObjectKind();
14524     break;
14525   case UO_Coawait:
14526     // It's unnecessary to represent the pass-through operator co_await in the
14527     // AST; just return the input expression instead.
14528     assert(!Input.get()->getType()->isDependentType() &&
14529                    "the co_await expression must be non-dependant before "
14530                    "building operator co_await");
14531     return Input;
14532   }
14533   if (resultType.isNull() || Input.isInvalid())
14534     return ExprError();
14535 
14536   // Check for array bounds violations in the operand of the UnaryOperator,
14537   // except for the '*' and '&' operators that have to be handled specially
14538   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14539   // that are explicitly defined as valid by the standard).
14540   if (Opc != UO_AddrOf && Opc != UO_Deref)
14541     CheckArrayAccess(Input.get());
14542 
14543   auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK,
14544                                    OK, OpLoc, CanOverflow, CurFPFeatures);
14545 
14546   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14547       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14548     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14549 
14550   // Convert the result back to a half vector.
14551   if (ConvertHalfVec)
14552     return convertVector(UO, Context.HalfTy, *this);
14553   return UO;
14554 }
14555 
14556 /// Determine whether the given expression is a qualified member
14557 /// access expression, of a form that could be turned into a pointer to member
14558 /// with the address-of operator.
14559 bool Sema::isQualifiedMemberAccess(Expr *E) {
14560   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14561     if (!DRE->getQualifier())
14562       return false;
14563 
14564     ValueDecl *VD = DRE->getDecl();
14565     if (!VD->isCXXClassMember())
14566       return false;
14567 
14568     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14569       return true;
14570     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14571       return Method->isInstance();
14572 
14573     return false;
14574   }
14575 
14576   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14577     if (!ULE->getQualifier())
14578       return false;
14579 
14580     for (NamedDecl *D : ULE->decls()) {
14581       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14582         if (Method->isInstance())
14583           return true;
14584       } else {
14585         // Overload set does not contain methods.
14586         break;
14587       }
14588     }
14589 
14590     return false;
14591   }
14592 
14593   return false;
14594 }
14595 
14596 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14597                               UnaryOperatorKind Opc, Expr *Input) {
14598   // First things first: handle placeholders so that the
14599   // overloaded-operator check considers the right type.
14600   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14601     // Increment and decrement of pseudo-object references.
14602     if (pty->getKind() == BuiltinType::PseudoObject &&
14603         UnaryOperator::isIncrementDecrementOp(Opc))
14604       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14605 
14606     // extension is always a builtin operator.
14607     if (Opc == UO_Extension)
14608       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14609 
14610     // & gets special logic for several kinds of placeholder.
14611     // The builtin code knows what to do.
14612     if (Opc == UO_AddrOf &&
14613         (pty->getKind() == BuiltinType::Overload ||
14614          pty->getKind() == BuiltinType::UnknownAny ||
14615          pty->getKind() == BuiltinType::BoundMember))
14616       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14617 
14618     // Anything else needs to be handled now.
14619     ExprResult Result = CheckPlaceholderExpr(Input);
14620     if (Result.isInvalid()) return ExprError();
14621     Input = Result.get();
14622   }
14623 
14624   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14625       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14626       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14627     // Find all of the overloaded operators visible from this
14628     // point. We perform both an operator-name lookup from the local
14629     // scope and an argument-dependent lookup based on the types of
14630     // the arguments.
14631     UnresolvedSet<16> Functions;
14632     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14633     if (S && OverOp != OO_None)
14634       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14635                                    Functions);
14636 
14637     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14638   }
14639 
14640   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14641 }
14642 
14643 // Unary Operators.  'Tok' is the token for the operator.
14644 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14645                               tok::TokenKind Op, Expr *Input) {
14646   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14647 }
14648 
14649 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14650 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14651                                 LabelDecl *TheDecl) {
14652   TheDecl->markUsed(Context);
14653   // Create the AST node.  The address of a label always has type 'void*'.
14654   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14655                                      Context.getPointerType(Context.VoidTy));
14656 }
14657 
14658 void Sema::ActOnStartStmtExpr() {
14659   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14660 }
14661 
14662 void Sema::ActOnStmtExprError() {
14663   // Note that function is also called by TreeTransform when leaving a
14664   // StmtExpr scope without rebuilding anything.
14665 
14666   DiscardCleanupsInEvaluationContext();
14667   PopExpressionEvaluationContext();
14668 }
14669 
14670 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14671                                SourceLocation RPLoc) {
14672   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14673 }
14674 
14675 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14676                                SourceLocation RPLoc, unsigned TemplateDepth) {
14677   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14678   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14679 
14680   if (hasAnyUnrecoverableErrorsInThisFunction())
14681     DiscardCleanupsInEvaluationContext();
14682   assert(!Cleanup.exprNeedsCleanups() &&
14683          "cleanups within StmtExpr not correctly bound!");
14684   PopExpressionEvaluationContext();
14685 
14686   // FIXME: there are a variety of strange constraints to enforce here, for
14687   // example, it is not possible to goto into a stmt expression apparently.
14688   // More semantic analysis is needed.
14689 
14690   // If there are sub-stmts in the compound stmt, take the type of the last one
14691   // as the type of the stmtexpr.
14692   QualType Ty = Context.VoidTy;
14693   bool StmtExprMayBindToTemp = false;
14694   if (!Compound->body_empty()) {
14695     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14696     if (const auto *LastStmt =
14697             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14698       if (const Expr *Value = LastStmt->getExprStmt()) {
14699         StmtExprMayBindToTemp = true;
14700         Ty = Value->getType();
14701       }
14702     }
14703   }
14704 
14705   // FIXME: Check that expression type is complete/non-abstract; statement
14706   // expressions are not lvalues.
14707   Expr *ResStmtExpr =
14708       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14709   if (StmtExprMayBindToTemp)
14710     return MaybeBindToTemporary(ResStmtExpr);
14711   return ResStmtExpr;
14712 }
14713 
14714 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14715   if (ER.isInvalid())
14716     return ExprError();
14717 
14718   // Do function/array conversion on the last expression, but not
14719   // lvalue-to-rvalue.  However, initialize an unqualified type.
14720   ER = DefaultFunctionArrayConversion(ER.get());
14721   if (ER.isInvalid())
14722     return ExprError();
14723   Expr *E = ER.get();
14724 
14725   if (E->isTypeDependent())
14726     return E;
14727 
14728   // In ARC, if the final expression ends in a consume, splice
14729   // the consume out and bind it later.  In the alternate case
14730   // (when dealing with a retainable type), the result
14731   // initialization will create a produce.  In both cases the
14732   // result will be +1, and we'll need to balance that out with
14733   // a bind.
14734   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14735   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14736     return Cast->getSubExpr();
14737 
14738   // FIXME: Provide a better location for the initialization.
14739   return PerformCopyInitialization(
14740       InitializedEntity::InitializeStmtExprResult(
14741           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14742       SourceLocation(), E);
14743 }
14744 
14745 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14746                                       TypeSourceInfo *TInfo,
14747                                       ArrayRef<OffsetOfComponent> Components,
14748                                       SourceLocation RParenLoc) {
14749   QualType ArgTy = TInfo->getType();
14750   bool Dependent = ArgTy->isDependentType();
14751   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14752 
14753   // We must have at least one component that refers to the type, and the first
14754   // one is known to be a field designator.  Verify that the ArgTy represents
14755   // a struct/union/class.
14756   if (!Dependent && !ArgTy->isRecordType())
14757     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14758                        << ArgTy << TypeRange);
14759 
14760   // Type must be complete per C99 7.17p3 because a declaring a variable
14761   // with an incomplete type would be ill-formed.
14762   if (!Dependent
14763       && RequireCompleteType(BuiltinLoc, ArgTy,
14764                              diag::err_offsetof_incomplete_type, TypeRange))
14765     return ExprError();
14766 
14767   bool DidWarnAboutNonPOD = false;
14768   QualType CurrentType = ArgTy;
14769   SmallVector<OffsetOfNode, 4> Comps;
14770   SmallVector<Expr*, 4> Exprs;
14771   for (const OffsetOfComponent &OC : Components) {
14772     if (OC.isBrackets) {
14773       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14774       if (!CurrentType->isDependentType()) {
14775         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14776         if(!AT)
14777           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14778                            << CurrentType);
14779         CurrentType = AT->getElementType();
14780       } else
14781         CurrentType = Context.DependentTy;
14782 
14783       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14784       if (IdxRval.isInvalid())
14785         return ExprError();
14786       Expr *Idx = IdxRval.get();
14787 
14788       // The expression must be an integral expression.
14789       // FIXME: An integral constant expression?
14790       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14791           !Idx->getType()->isIntegerType())
14792         return ExprError(
14793             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14794             << Idx->getSourceRange());
14795 
14796       // Record this array index.
14797       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14798       Exprs.push_back(Idx);
14799       continue;
14800     }
14801 
14802     // Offset of a field.
14803     if (CurrentType->isDependentType()) {
14804       // We have the offset of a field, but we can't look into the dependent
14805       // type. Just record the identifier of the field.
14806       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14807       CurrentType = Context.DependentTy;
14808       continue;
14809     }
14810 
14811     // We need to have a complete type to look into.
14812     if (RequireCompleteType(OC.LocStart, CurrentType,
14813                             diag::err_offsetof_incomplete_type))
14814       return ExprError();
14815 
14816     // Look for the designated field.
14817     const RecordType *RC = CurrentType->getAs<RecordType>();
14818     if (!RC)
14819       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14820                        << CurrentType);
14821     RecordDecl *RD = RC->getDecl();
14822 
14823     // C++ [lib.support.types]p5:
14824     //   The macro offsetof accepts a restricted set of type arguments in this
14825     //   International Standard. type shall be a POD structure or a POD union
14826     //   (clause 9).
14827     // C++11 [support.types]p4:
14828     //   If type is not a standard-layout class (Clause 9), the results are
14829     //   undefined.
14830     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14831       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14832       unsigned DiagID =
14833         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14834                             : diag::ext_offsetof_non_pod_type;
14835 
14836       if (!IsSafe && !DidWarnAboutNonPOD &&
14837           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14838                               PDiag(DiagID)
14839                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14840                               << CurrentType))
14841         DidWarnAboutNonPOD = true;
14842     }
14843 
14844     // Look for the field.
14845     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14846     LookupQualifiedName(R, RD);
14847     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14848     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14849     if (!MemberDecl) {
14850       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14851         MemberDecl = IndirectMemberDecl->getAnonField();
14852     }
14853 
14854     if (!MemberDecl)
14855       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14856                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14857                                                               OC.LocEnd));
14858 
14859     // C99 7.17p3:
14860     //   (If the specified member is a bit-field, the behavior is undefined.)
14861     //
14862     // We diagnose this as an error.
14863     if (MemberDecl->isBitField()) {
14864       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14865         << MemberDecl->getDeclName()
14866         << SourceRange(BuiltinLoc, RParenLoc);
14867       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14868       return ExprError();
14869     }
14870 
14871     RecordDecl *Parent = MemberDecl->getParent();
14872     if (IndirectMemberDecl)
14873       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14874 
14875     // If the member was found in a base class, introduce OffsetOfNodes for
14876     // the base class indirections.
14877     CXXBasePaths Paths;
14878     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14879                       Paths)) {
14880       if (Paths.getDetectedVirtual()) {
14881         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14882           << MemberDecl->getDeclName()
14883           << SourceRange(BuiltinLoc, RParenLoc);
14884         return ExprError();
14885       }
14886 
14887       CXXBasePath &Path = Paths.front();
14888       for (const CXXBasePathElement &B : Path)
14889         Comps.push_back(OffsetOfNode(B.Base));
14890     }
14891 
14892     if (IndirectMemberDecl) {
14893       for (auto *FI : IndirectMemberDecl->chain()) {
14894         assert(isa<FieldDecl>(FI));
14895         Comps.push_back(OffsetOfNode(OC.LocStart,
14896                                      cast<FieldDecl>(FI), OC.LocEnd));
14897       }
14898     } else
14899       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14900 
14901     CurrentType = MemberDecl->getType().getNonReferenceType();
14902   }
14903 
14904   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14905                               Comps, Exprs, RParenLoc);
14906 }
14907 
14908 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14909                                       SourceLocation BuiltinLoc,
14910                                       SourceLocation TypeLoc,
14911                                       ParsedType ParsedArgTy,
14912                                       ArrayRef<OffsetOfComponent> Components,
14913                                       SourceLocation RParenLoc) {
14914 
14915   TypeSourceInfo *ArgTInfo;
14916   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14917   if (ArgTy.isNull())
14918     return ExprError();
14919 
14920   if (!ArgTInfo)
14921     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14922 
14923   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14924 }
14925 
14926 
14927 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14928                                  Expr *CondExpr,
14929                                  Expr *LHSExpr, Expr *RHSExpr,
14930                                  SourceLocation RPLoc) {
14931   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14932 
14933   ExprValueKind VK = VK_RValue;
14934   ExprObjectKind OK = OK_Ordinary;
14935   QualType resType;
14936   bool CondIsTrue = false;
14937   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14938     resType = Context.DependentTy;
14939   } else {
14940     // The conditional expression is required to be a constant expression.
14941     llvm::APSInt condEval(32);
14942     ExprResult CondICE
14943       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14944           diag::err_typecheck_choose_expr_requires_constant, false);
14945     if (CondICE.isInvalid())
14946       return ExprError();
14947     CondExpr = CondICE.get();
14948     CondIsTrue = condEval.getZExtValue();
14949 
14950     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14951     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14952 
14953     resType = ActiveExpr->getType();
14954     VK = ActiveExpr->getValueKind();
14955     OK = ActiveExpr->getObjectKind();
14956   }
14957 
14958   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14959                                   resType, VK, OK, RPLoc, CondIsTrue);
14960 }
14961 
14962 //===----------------------------------------------------------------------===//
14963 // Clang Extensions.
14964 //===----------------------------------------------------------------------===//
14965 
14966 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14967 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14968   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14969 
14970   if (LangOpts.CPlusPlus) {
14971     MangleNumberingContext *MCtx;
14972     Decl *ManglingContextDecl;
14973     std::tie(MCtx, ManglingContextDecl) =
14974         getCurrentMangleNumberContext(Block->getDeclContext());
14975     if (MCtx) {
14976       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14977       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14978     }
14979   }
14980 
14981   PushBlockScope(CurScope, Block);
14982   CurContext->addDecl(Block);
14983   if (CurScope)
14984     PushDeclContext(CurScope, Block);
14985   else
14986     CurContext = Block;
14987 
14988   getCurBlock()->HasImplicitReturnType = true;
14989 
14990   // Enter a new evaluation context to insulate the block from any
14991   // cleanups from the enclosing full-expression.
14992   PushExpressionEvaluationContext(
14993       ExpressionEvaluationContext::PotentiallyEvaluated);
14994 }
14995 
14996 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14997                                Scope *CurScope) {
14998   assert(ParamInfo.getIdentifier() == nullptr &&
14999          "block-id should have no identifier!");
15000   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15001   BlockScopeInfo *CurBlock = getCurBlock();
15002 
15003   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15004   QualType T = Sig->getType();
15005 
15006   // FIXME: We should allow unexpanded parameter packs here, but that would,
15007   // in turn, make the block expression contain unexpanded parameter packs.
15008   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15009     // Drop the parameters.
15010     FunctionProtoType::ExtProtoInfo EPI;
15011     EPI.HasTrailingReturn = false;
15012     EPI.TypeQuals.addConst();
15013     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15014     Sig = Context.getTrivialTypeSourceInfo(T);
15015   }
15016 
15017   // GetTypeForDeclarator always produces a function type for a block
15018   // literal signature.  Furthermore, it is always a FunctionProtoType
15019   // unless the function was written with a typedef.
15020   assert(T->isFunctionType() &&
15021          "GetTypeForDeclarator made a non-function block signature");
15022 
15023   // Look for an explicit signature in that function type.
15024   FunctionProtoTypeLoc ExplicitSignature;
15025 
15026   if ((ExplicitSignature = Sig->getTypeLoc()
15027                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15028 
15029     // Check whether that explicit signature was synthesized by
15030     // GetTypeForDeclarator.  If so, don't save that as part of the
15031     // written signature.
15032     if (ExplicitSignature.getLocalRangeBegin() ==
15033         ExplicitSignature.getLocalRangeEnd()) {
15034       // This would be much cheaper if we stored TypeLocs instead of
15035       // TypeSourceInfos.
15036       TypeLoc Result = ExplicitSignature.getReturnLoc();
15037       unsigned Size = Result.getFullDataSize();
15038       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15039       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15040 
15041       ExplicitSignature = FunctionProtoTypeLoc();
15042     }
15043   }
15044 
15045   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15046   CurBlock->FunctionType = T;
15047 
15048   const FunctionType *Fn = T->getAs<FunctionType>();
15049   QualType RetTy = Fn->getReturnType();
15050   bool isVariadic =
15051     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15052 
15053   CurBlock->TheDecl->setIsVariadic(isVariadic);
15054 
15055   // Context.DependentTy is used as a placeholder for a missing block
15056   // return type.  TODO:  what should we do with declarators like:
15057   //   ^ * { ... }
15058   // If the answer is "apply template argument deduction"....
15059   if (RetTy != Context.DependentTy) {
15060     CurBlock->ReturnType = RetTy;
15061     CurBlock->TheDecl->setBlockMissingReturnType(false);
15062     CurBlock->HasImplicitReturnType = false;
15063   }
15064 
15065   // Push block parameters from the declarator if we had them.
15066   SmallVector<ParmVarDecl*, 8> Params;
15067   if (ExplicitSignature) {
15068     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15069       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15070       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15071           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15072         // Diagnose this as an extension in C17 and earlier.
15073         if (!getLangOpts().C2x)
15074           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15075       }
15076       Params.push_back(Param);
15077     }
15078 
15079   // Fake up parameter variables if we have a typedef, like
15080   //   ^ fntype { ... }
15081   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15082     for (const auto &I : Fn->param_types()) {
15083       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15084           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15085       Params.push_back(Param);
15086     }
15087   }
15088 
15089   // Set the parameters on the block decl.
15090   if (!Params.empty()) {
15091     CurBlock->TheDecl->setParams(Params);
15092     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15093                              /*CheckParameterNames=*/false);
15094   }
15095 
15096   // Finally we can process decl attributes.
15097   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15098 
15099   // Put the parameter variables in scope.
15100   for (auto AI : CurBlock->TheDecl->parameters()) {
15101     AI->setOwningFunction(CurBlock->TheDecl);
15102 
15103     // If this has an identifier, add it to the scope stack.
15104     if (AI->getIdentifier()) {
15105       CheckShadow(CurBlock->TheScope, AI);
15106 
15107       PushOnScopeChains(AI, CurBlock->TheScope);
15108     }
15109   }
15110 }
15111 
15112 /// ActOnBlockError - If there is an error parsing a block, this callback
15113 /// is invoked to pop the information about the block from the action impl.
15114 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15115   // Leave the expression-evaluation context.
15116   DiscardCleanupsInEvaluationContext();
15117   PopExpressionEvaluationContext();
15118 
15119   // Pop off CurBlock, handle nested blocks.
15120   PopDeclContext();
15121   PopFunctionScopeInfo();
15122 }
15123 
15124 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15125 /// literal was successfully completed.  ^(int x){...}
15126 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15127                                     Stmt *Body, Scope *CurScope) {
15128   // If blocks are disabled, emit an error.
15129   if (!LangOpts.Blocks)
15130     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15131 
15132   // Leave the expression-evaluation context.
15133   if (hasAnyUnrecoverableErrorsInThisFunction())
15134     DiscardCleanupsInEvaluationContext();
15135   assert(!Cleanup.exprNeedsCleanups() &&
15136          "cleanups within block not correctly bound!");
15137   PopExpressionEvaluationContext();
15138 
15139   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15140   BlockDecl *BD = BSI->TheDecl;
15141 
15142   if (BSI->HasImplicitReturnType)
15143     deduceClosureReturnType(*BSI);
15144 
15145   QualType RetTy = Context.VoidTy;
15146   if (!BSI->ReturnType.isNull())
15147     RetTy = BSI->ReturnType;
15148 
15149   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15150   QualType BlockTy;
15151 
15152   // If the user wrote a function type in some form, try to use that.
15153   if (!BSI->FunctionType.isNull()) {
15154     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15155 
15156     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15157     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15158 
15159     // Turn protoless block types into nullary block types.
15160     if (isa<FunctionNoProtoType>(FTy)) {
15161       FunctionProtoType::ExtProtoInfo EPI;
15162       EPI.ExtInfo = Ext;
15163       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15164 
15165     // Otherwise, if we don't need to change anything about the function type,
15166     // preserve its sugar structure.
15167     } else if (FTy->getReturnType() == RetTy &&
15168                (!NoReturn || FTy->getNoReturnAttr())) {
15169       BlockTy = BSI->FunctionType;
15170 
15171     // Otherwise, make the minimal modifications to the function type.
15172     } else {
15173       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15174       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15175       EPI.TypeQuals = Qualifiers();
15176       EPI.ExtInfo = Ext;
15177       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15178     }
15179 
15180   // If we don't have a function type, just build one from nothing.
15181   } else {
15182     FunctionProtoType::ExtProtoInfo EPI;
15183     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15184     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15185   }
15186 
15187   DiagnoseUnusedParameters(BD->parameters());
15188   BlockTy = Context.getBlockPointerType(BlockTy);
15189 
15190   // If needed, diagnose invalid gotos and switches in the block.
15191   if (getCurFunction()->NeedsScopeChecking() &&
15192       !PP.isCodeCompletionEnabled())
15193     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15194 
15195   BD->setBody(cast<CompoundStmt>(Body));
15196 
15197   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15198     DiagnoseUnguardedAvailabilityViolations(BD);
15199 
15200   // Try to apply the named return value optimization. We have to check again
15201   // if we can do this, though, because blocks keep return statements around
15202   // to deduce an implicit return type.
15203   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15204       !BD->isDependentContext())
15205     computeNRVO(Body, BSI);
15206 
15207   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15208       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15209     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15210                           NTCUK_Destruct|NTCUK_Copy);
15211 
15212   PopDeclContext();
15213 
15214   // Pop the block scope now but keep it alive to the end of this function.
15215   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15216   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15217 
15218   // Set the captured variables on the block.
15219   SmallVector<BlockDecl::Capture, 4> Captures;
15220   for (Capture &Cap : BSI->Captures) {
15221     if (Cap.isInvalid() || Cap.isThisCapture())
15222       continue;
15223 
15224     VarDecl *Var = Cap.getVariable();
15225     Expr *CopyExpr = nullptr;
15226     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15227       if (const RecordType *Record =
15228               Cap.getCaptureType()->getAs<RecordType>()) {
15229         // The capture logic needs the destructor, so make sure we mark it.
15230         // Usually this is unnecessary because most local variables have
15231         // their destructors marked at declaration time, but parameters are
15232         // an exception because it's technically only the call site that
15233         // actually requires the destructor.
15234         if (isa<ParmVarDecl>(Var))
15235           FinalizeVarWithDestructor(Var, Record);
15236 
15237         // Enter a separate potentially-evaluated context while building block
15238         // initializers to isolate their cleanups from those of the block
15239         // itself.
15240         // FIXME: Is this appropriate even when the block itself occurs in an
15241         // unevaluated operand?
15242         EnterExpressionEvaluationContext EvalContext(
15243             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15244 
15245         SourceLocation Loc = Cap.getLocation();
15246 
15247         ExprResult Result = BuildDeclarationNameExpr(
15248             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15249 
15250         // According to the blocks spec, the capture of a variable from
15251         // the stack requires a const copy constructor.  This is not true
15252         // of the copy/move done to move a __block variable to the heap.
15253         if (!Result.isInvalid() &&
15254             !Result.get()->getType().isConstQualified()) {
15255           Result = ImpCastExprToType(Result.get(),
15256                                      Result.get()->getType().withConst(),
15257                                      CK_NoOp, VK_LValue);
15258         }
15259 
15260         if (!Result.isInvalid()) {
15261           Result = PerformCopyInitialization(
15262               InitializedEntity::InitializeBlock(Var->getLocation(),
15263                                                  Cap.getCaptureType(), false),
15264               Loc, Result.get());
15265         }
15266 
15267         // Build a full-expression copy expression if initialization
15268         // succeeded and used a non-trivial constructor.  Recover from
15269         // errors by pretending that the copy isn't necessary.
15270         if (!Result.isInvalid() &&
15271             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15272                 ->isTrivial()) {
15273           Result = MaybeCreateExprWithCleanups(Result);
15274           CopyExpr = Result.get();
15275         }
15276       }
15277     }
15278 
15279     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15280                               CopyExpr);
15281     Captures.push_back(NewCap);
15282   }
15283   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15284 
15285   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15286 
15287   // If the block isn't obviously global, i.e. it captures anything at
15288   // all, then we need to do a few things in the surrounding context:
15289   if (Result->getBlockDecl()->hasCaptures()) {
15290     // First, this expression has a new cleanup object.
15291     ExprCleanupObjects.push_back(Result->getBlockDecl());
15292     Cleanup.setExprNeedsCleanups(true);
15293 
15294     // It also gets a branch-protected scope if any of the captured
15295     // variables needs destruction.
15296     for (const auto &CI : Result->getBlockDecl()->captures()) {
15297       const VarDecl *var = CI.getVariable();
15298       if (var->getType().isDestructedType() != QualType::DK_none) {
15299         setFunctionHasBranchProtectedScope();
15300         break;
15301       }
15302     }
15303   }
15304 
15305   if (getCurFunction())
15306     getCurFunction()->addBlock(BD);
15307 
15308   return Result;
15309 }
15310 
15311 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15312                             SourceLocation RPLoc) {
15313   TypeSourceInfo *TInfo;
15314   GetTypeFromParser(Ty, &TInfo);
15315   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15316 }
15317 
15318 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15319                                 Expr *E, TypeSourceInfo *TInfo,
15320                                 SourceLocation RPLoc) {
15321   Expr *OrigExpr = E;
15322   bool IsMS = false;
15323 
15324   // CUDA device code does not support varargs.
15325   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15326     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15327       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15328       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15329         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15330     }
15331   }
15332 
15333   // NVPTX does not support va_arg expression.
15334   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15335       Context.getTargetInfo().getTriple().isNVPTX())
15336     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15337 
15338   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15339   // as Microsoft ABI on an actual Microsoft platform, where
15340   // __builtin_ms_va_list and __builtin_va_list are the same.)
15341   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15342       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15343     QualType MSVaListType = Context.getBuiltinMSVaListType();
15344     if (Context.hasSameType(MSVaListType, E->getType())) {
15345       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15346         return ExprError();
15347       IsMS = true;
15348     }
15349   }
15350 
15351   // Get the va_list type
15352   QualType VaListType = Context.getBuiltinVaListType();
15353   if (!IsMS) {
15354     if (VaListType->isArrayType()) {
15355       // Deal with implicit array decay; for example, on x86-64,
15356       // va_list is an array, but it's supposed to decay to
15357       // a pointer for va_arg.
15358       VaListType = Context.getArrayDecayedType(VaListType);
15359       // Make sure the input expression also decays appropriately.
15360       ExprResult Result = UsualUnaryConversions(E);
15361       if (Result.isInvalid())
15362         return ExprError();
15363       E = Result.get();
15364     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15365       // If va_list is a record type and we are compiling in C++ mode,
15366       // check the argument using reference binding.
15367       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15368           Context, Context.getLValueReferenceType(VaListType), false);
15369       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15370       if (Init.isInvalid())
15371         return ExprError();
15372       E = Init.getAs<Expr>();
15373     } else {
15374       // Otherwise, the va_list argument must be an l-value because
15375       // it is modified by va_arg.
15376       if (!E->isTypeDependent() &&
15377           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15378         return ExprError();
15379     }
15380   }
15381 
15382   if (!IsMS && !E->isTypeDependent() &&
15383       !Context.hasSameType(VaListType, E->getType()))
15384     return ExprError(
15385         Diag(E->getBeginLoc(),
15386              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15387         << OrigExpr->getType() << E->getSourceRange());
15388 
15389   if (!TInfo->getType()->isDependentType()) {
15390     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15391                             diag::err_second_parameter_to_va_arg_incomplete,
15392                             TInfo->getTypeLoc()))
15393       return ExprError();
15394 
15395     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15396                                TInfo->getType(),
15397                                diag::err_second_parameter_to_va_arg_abstract,
15398                                TInfo->getTypeLoc()))
15399       return ExprError();
15400 
15401     if (!TInfo->getType().isPODType(Context)) {
15402       Diag(TInfo->getTypeLoc().getBeginLoc(),
15403            TInfo->getType()->isObjCLifetimeType()
15404              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15405              : diag::warn_second_parameter_to_va_arg_not_pod)
15406         << TInfo->getType()
15407         << TInfo->getTypeLoc().getSourceRange();
15408     }
15409 
15410     // Check for va_arg where arguments of the given type will be promoted
15411     // (i.e. this va_arg is guaranteed to have undefined behavior).
15412     QualType PromoteType;
15413     if (TInfo->getType()->isPromotableIntegerType()) {
15414       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15415       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15416         PromoteType = QualType();
15417     }
15418     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15419       PromoteType = Context.DoubleTy;
15420     if (!PromoteType.isNull())
15421       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15422                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15423                           << TInfo->getType()
15424                           << PromoteType
15425                           << TInfo->getTypeLoc().getSourceRange());
15426   }
15427 
15428   QualType T = TInfo->getType().getNonLValueExprType(Context);
15429   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15430 }
15431 
15432 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15433   // The type of __null will be int or long, depending on the size of
15434   // pointers on the target.
15435   QualType Ty;
15436   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15437   if (pw == Context.getTargetInfo().getIntWidth())
15438     Ty = Context.IntTy;
15439   else if (pw == Context.getTargetInfo().getLongWidth())
15440     Ty = Context.LongTy;
15441   else if (pw == Context.getTargetInfo().getLongLongWidth())
15442     Ty = Context.LongLongTy;
15443   else {
15444     llvm_unreachable("I don't know size of pointer!");
15445   }
15446 
15447   return new (Context) GNUNullExpr(Ty, TokenLoc);
15448 }
15449 
15450 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15451                                     SourceLocation BuiltinLoc,
15452                                     SourceLocation RPLoc) {
15453   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15454 }
15455 
15456 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15457                                     SourceLocation BuiltinLoc,
15458                                     SourceLocation RPLoc,
15459                                     DeclContext *ParentContext) {
15460   return new (Context)
15461       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15462 }
15463 
15464 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15465                                         bool Diagnose) {
15466   if (!getLangOpts().ObjC)
15467     return false;
15468 
15469   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15470   if (!PT)
15471     return false;
15472   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15473 
15474   // Ignore any parens, implicit casts (should only be
15475   // array-to-pointer decays), and not-so-opaque values.  The last is
15476   // important for making this trigger for property assignments.
15477   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15478   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15479     if (OV->getSourceExpr())
15480       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15481 
15482   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15483     if (!PT->isObjCIdType() &&
15484         !(ID && ID->getIdentifier()->isStr("NSString")))
15485       return false;
15486     if (!SL->isAscii())
15487       return false;
15488 
15489     if (Diagnose) {
15490       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15491           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15492       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15493     }
15494     return true;
15495   }
15496 
15497   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15498       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15499       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15500       !SrcExpr->isNullPointerConstant(
15501           getASTContext(), Expr::NPC_NeverValueDependent)) {
15502     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15503       return false;
15504     if (Diagnose) {
15505       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15506           << /*number*/1
15507           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15508       Expr *NumLit =
15509           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15510       if (NumLit)
15511         Exp = NumLit;
15512     }
15513     return true;
15514   }
15515 
15516   return false;
15517 }
15518 
15519 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15520                                               const Expr *SrcExpr) {
15521   if (!DstType->isFunctionPointerType() ||
15522       !SrcExpr->getType()->isFunctionType())
15523     return false;
15524 
15525   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15526   if (!DRE)
15527     return false;
15528 
15529   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15530   if (!FD)
15531     return false;
15532 
15533   return !S.checkAddressOfFunctionIsAvailable(FD,
15534                                               /*Complain=*/true,
15535                                               SrcExpr->getBeginLoc());
15536 }
15537 
15538 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15539                                     SourceLocation Loc,
15540                                     QualType DstType, QualType SrcType,
15541                                     Expr *SrcExpr, AssignmentAction Action,
15542                                     bool *Complained) {
15543   if (Complained)
15544     *Complained = false;
15545 
15546   // Decode the result (notice that AST's are still created for extensions).
15547   bool CheckInferredResultType = false;
15548   bool isInvalid = false;
15549   unsigned DiagKind = 0;
15550   FixItHint Hint;
15551   ConversionFixItGenerator ConvHints;
15552   bool MayHaveConvFixit = false;
15553   bool MayHaveFunctionDiff = false;
15554   const ObjCInterfaceDecl *IFace = nullptr;
15555   const ObjCProtocolDecl *PDecl = nullptr;
15556 
15557   switch (ConvTy) {
15558   case Compatible:
15559       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15560       return false;
15561 
15562   case PointerToInt:
15563     if (getLangOpts().CPlusPlus) {
15564       DiagKind = diag::err_typecheck_convert_pointer_int;
15565       isInvalid = true;
15566     } else {
15567       DiagKind = diag::ext_typecheck_convert_pointer_int;
15568     }
15569     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15570     MayHaveConvFixit = true;
15571     break;
15572   case IntToPointer:
15573     if (getLangOpts().CPlusPlus) {
15574       DiagKind = diag::err_typecheck_convert_int_pointer;
15575       isInvalid = true;
15576     } else {
15577       DiagKind = diag::ext_typecheck_convert_int_pointer;
15578     }
15579     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15580     MayHaveConvFixit = true;
15581     break;
15582   case IncompatibleFunctionPointer:
15583     if (getLangOpts().CPlusPlus) {
15584       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15585       isInvalid = true;
15586     } else {
15587       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15588     }
15589     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15590     MayHaveConvFixit = true;
15591     break;
15592   case IncompatiblePointer:
15593     if (Action == AA_Passing_CFAudited) {
15594       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15595     } else if (getLangOpts().CPlusPlus) {
15596       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15597       isInvalid = true;
15598     } else {
15599       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15600     }
15601     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15602       SrcType->isObjCObjectPointerType();
15603     if (Hint.isNull() && !CheckInferredResultType) {
15604       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15605     }
15606     else if (CheckInferredResultType) {
15607       SrcType = SrcType.getUnqualifiedType();
15608       DstType = DstType.getUnqualifiedType();
15609     }
15610     MayHaveConvFixit = true;
15611     break;
15612   case IncompatiblePointerSign:
15613     if (getLangOpts().CPlusPlus) {
15614       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15615       isInvalid = true;
15616     } else {
15617       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15618     }
15619     break;
15620   case FunctionVoidPointer:
15621     if (getLangOpts().CPlusPlus) {
15622       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15623       isInvalid = true;
15624     } else {
15625       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15626     }
15627     break;
15628   case IncompatiblePointerDiscardsQualifiers: {
15629     // Perform array-to-pointer decay if necessary.
15630     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15631 
15632     isInvalid = true;
15633 
15634     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15635     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15636     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15637       DiagKind = diag::err_typecheck_incompatible_address_space;
15638       break;
15639 
15640     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15641       DiagKind = diag::err_typecheck_incompatible_ownership;
15642       break;
15643     }
15644 
15645     llvm_unreachable("unknown error case for discarding qualifiers!");
15646     // fallthrough
15647   }
15648   case CompatiblePointerDiscardsQualifiers:
15649     // If the qualifiers lost were because we were applying the
15650     // (deprecated) C++ conversion from a string literal to a char*
15651     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15652     // Ideally, this check would be performed in
15653     // checkPointerTypesForAssignment. However, that would require a
15654     // bit of refactoring (so that the second argument is an
15655     // expression, rather than a type), which should be done as part
15656     // of a larger effort to fix checkPointerTypesForAssignment for
15657     // C++ semantics.
15658     if (getLangOpts().CPlusPlus &&
15659         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15660       return false;
15661     if (getLangOpts().CPlusPlus) {
15662       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15663       isInvalid = true;
15664     } else {
15665       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15666     }
15667 
15668     break;
15669   case IncompatibleNestedPointerQualifiers:
15670     if (getLangOpts().CPlusPlus) {
15671       isInvalid = true;
15672       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15673     } else {
15674       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15675     }
15676     break;
15677   case IncompatibleNestedPointerAddressSpaceMismatch:
15678     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15679     isInvalid = true;
15680     break;
15681   case IntToBlockPointer:
15682     DiagKind = diag::err_int_to_block_pointer;
15683     isInvalid = true;
15684     break;
15685   case IncompatibleBlockPointer:
15686     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15687     isInvalid = true;
15688     break;
15689   case IncompatibleObjCQualifiedId: {
15690     if (SrcType->isObjCQualifiedIdType()) {
15691       const ObjCObjectPointerType *srcOPT =
15692                 SrcType->castAs<ObjCObjectPointerType>();
15693       for (auto *srcProto : srcOPT->quals()) {
15694         PDecl = srcProto;
15695         break;
15696       }
15697       if (const ObjCInterfaceType *IFaceT =
15698             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15699         IFace = IFaceT->getDecl();
15700     }
15701     else if (DstType->isObjCQualifiedIdType()) {
15702       const ObjCObjectPointerType *dstOPT =
15703         DstType->castAs<ObjCObjectPointerType>();
15704       for (auto *dstProto : dstOPT->quals()) {
15705         PDecl = dstProto;
15706         break;
15707       }
15708       if (const ObjCInterfaceType *IFaceT =
15709             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15710         IFace = IFaceT->getDecl();
15711     }
15712     if (getLangOpts().CPlusPlus) {
15713       DiagKind = diag::err_incompatible_qualified_id;
15714       isInvalid = true;
15715     } else {
15716       DiagKind = diag::warn_incompatible_qualified_id;
15717     }
15718     break;
15719   }
15720   case IncompatibleVectors:
15721     if (getLangOpts().CPlusPlus) {
15722       DiagKind = diag::err_incompatible_vectors;
15723       isInvalid = true;
15724     } else {
15725       DiagKind = diag::warn_incompatible_vectors;
15726     }
15727     break;
15728   case IncompatibleObjCWeakRef:
15729     DiagKind = diag::err_arc_weak_unavailable_assign;
15730     isInvalid = true;
15731     break;
15732   case Incompatible:
15733     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15734       if (Complained)
15735         *Complained = true;
15736       return true;
15737     }
15738 
15739     DiagKind = diag::err_typecheck_convert_incompatible;
15740     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15741     MayHaveConvFixit = true;
15742     isInvalid = true;
15743     MayHaveFunctionDiff = true;
15744     break;
15745   }
15746 
15747   QualType FirstType, SecondType;
15748   switch (Action) {
15749   case AA_Assigning:
15750   case AA_Initializing:
15751     // The destination type comes first.
15752     FirstType = DstType;
15753     SecondType = SrcType;
15754     break;
15755 
15756   case AA_Returning:
15757   case AA_Passing:
15758   case AA_Passing_CFAudited:
15759   case AA_Converting:
15760   case AA_Sending:
15761   case AA_Casting:
15762     // The source type comes first.
15763     FirstType = SrcType;
15764     SecondType = DstType;
15765     break;
15766   }
15767 
15768   PartialDiagnostic FDiag = PDiag(DiagKind);
15769   if (Action == AA_Passing_CFAudited)
15770     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15771   else
15772     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15773 
15774   // If we can fix the conversion, suggest the FixIts.
15775   assert(ConvHints.isNull() || Hint.isNull());
15776   if (!ConvHints.isNull()) {
15777     for (FixItHint &H : ConvHints.Hints)
15778       FDiag << H;
15779   } else {
15780     FDiag << Hint;
15781   }
15782   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15783 
15784   if (MayHaveFunctionDiff)
15785     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15786 
15787   Diag(Loc, FDiag);
15788   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15789        DiagKind == diag::err_incompatible_qualified_id) &&
15790       PDecl && IFace && !IFace->hasDefinition())
15791     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15792         << IFace << PDecl;
15793 
15794   if (SecondType == Context.OverloadTy)
15795     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15796                               FirstType, /*TakingAddress=*/true);
15797 
15798   if (CheckInferredResultType)
15799     EmitRelatedResultTypeNote(SrcExpr);
15800 
15801   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15802     EmitRelatedResultTypeNoteForReturn(DstType);
15803 
15804   if (Complained)
15805     *Complained = true;
15806   return isInvalid;
15807 }
15808 
15809 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15810                                                  llvm::APSInt *Result) {
15811   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15812   public:
15813     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15814       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15815     }
15816   } Diagnoser;
15817 
15818   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15819 }
15820 
15821 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15822                                                  llvm::APSInt *Result,
15823                                                  unsigned DiagID,
15824                                                  bool AllowFold) {
15825   class IDDiagnoser : public VerifyICEDiagnoser {
15826     unsigned DiagID;
15827 
15828   public:
15829     IDDiagnoser(unsigned DiagID)
15830       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15831 
15832     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15833       S.Diag(Loc, DiagID) << SR;
15834     }
15835   } Diagnoser(DiagID);
15836 
15837   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15838 }
15839 
15840 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15841                                             SourceRange SR) {
15842   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15843 }
15844 
15845 ExprResult
15846 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15847                                       VerifyICEDiagnoser &Diagnoser,
15848                                       bool AllowFold) {
15849   SourceLocation DiagLoc = E->getBeginLoc();
15850 
15851   if (getLangOpts().CPlusPlus11) {
15852     // C++11 [expr.const]p5:
15853     //   If an expression of literal class type is used in a context where an
15854     //   integral constant expression is required, then that class type shall
15855     //   have a single non-explicit conversion function to an integral or
15856     //   unscoped enumeration type
15857     ExprResult Converted;
15858     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15859     public:
15860       CXX11ConvertDiagnoser(bool Silent)
15861           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15862                                 Silent, true) {}
15863 
15864       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15865                                            QualType T) override {
15866         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15867       }
15868 
15869       SemaDiagnosticBuilder diagnoseIncomplete(
15870           Sema &S, SourceLocation Loc, QualType T) override {
15871         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15872       }
15873 
15874       SemaDiagnosticBuilder diagnoseExplicitConv(
15875           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15876         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15877       }
15878 
15879       SemaDiagnosticBuilder noteExplicitConv(
15880           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15881         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15882                  << ConvTy->isEnumeralType() << ConvTy;
15883       }
15884 
15885       SemaDiagnosticBuilder diagnoseAmbiguous(
15886           Sema &S, SourceLocation Loc, QualType T) override {
15887         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15888       }
15889 
15890       SemaDiagnosticBuilder noteAmbiguous(
15891           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15892         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15893                  << ConvTy->isEnumeralType() << ConvTy;
15894       }
15895 
15896       SemaDiagnosticBuilder diagnoseConversion(
15897           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15898         llvm_unreachable("conversion functions are permitted");
15899       }
15900     } ConvertDiagnoser(Diagnoser.Suppress);
15901 
15902     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15903                                                     ConvertDiagnoser);
15904     if (Converted.isInvalid())
15905       return Converted;
15906     E = Converted.get();
15907     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15908       return ExprError();
15909   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15910     // An ICE must be of integral or unscoped enumeration type.
15911     if (!Diagnoser.Suppress)
15912       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15913     return ExprError();
15914   }
15915 
15916   ExprResult RValueExpr = DefaultLvalueConversion(E);
15917   if (RValueExpr.isInvalid())
15918     return ExprError();
15919 
15920   E = RValueExpr.get();
15921 
15922   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15923   // in the non-ICE case.
15924   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15925     if (Result)
15926       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15927     if (!isa<ConstantExpr>(E))
15928       E = ConstantExpr::Create(Context, E);
15929     return E;
15930   }
15931 
15932   Expr::EvalResult EvalResult;
15933   SmallVector<PartialDiagnosticAt, 8> Notes;
15934   EvalResult.Diag = &Notes;
15935 
15936   // Try to evaluate the expression, and produce diagnostics explaining why it's
15937   // not a constant expression as a side-effect.
15938   bool Folded =
15939       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15940       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15941 
15942   if (!isa<ConstantExpr>(E))
15943     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15944 
15945   // In C++11, we can rely on diagnostics being produced for any expression
15946   // which is not a constant expression. If no diagnostics were produced, then
15947   // this is a constant expression.
15948   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15949     if (Result)
15950       *Result = EvalResult.Val.getInt();
15951     return E;
15952   }
15953 
15954   // If our only note is the usual "invalid subexpression" note, just point
15955   // the caret at its location rather than producing an essentially
15956   // redundant note.
15957   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15958         diag::note_invalid_subexpr_in_const_expr) {
15959     DiagLoc = Notes[0].first;
15960     Notes.clear();
15961   }
15962 
15963   if (!Folded || !AllowFold) {
15964     if (!Diagnoser.Suppress) {
15965       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15966       for (const PartialDiagnosticAt &Note : Notes)
15967         Diag(Note.first, Note.second);
15968     }
15969 
15970     return ExprError();
15971   }
15972 
15973   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15974   for (const PartialDiagnosticAt &Note : Notes)
15975     Diag(Note.first, Note.second);
15976 
15977   if (Result)
15978     *Result = EvalResult.Val.getInt();
15979   return E;
15980 }
15981 
15982 namespace {
15983   // Handle the case where we conclude a expression which we speculatively
15984   // considered to be unevaluated is actually evaluated.
15985   class TransformToPE : public TreeTransform<TransformToPE> {
15986     typedef TreeTransform<TransformToPE> BaseTransform;
15987 
15988   public:
15989     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15990 
15991     // Make sure we redo semantic analysis
15992     bool AlwaysRebuild() { return true; }
15993     bool ReplacingOriginal() { return true; }
15994 
15995     // We need to special-case DeclRefExprs referring to FieldDecls which
15996     // are not part of a member pointer formation; normal TreeTransforming
15997     // doesn't catch this case because of the way we represent them in the AST.
15998     // FIXME: This is a bit ugly; is it really the best way to handle this
15999     // case?
16000     //
16001     // Error on DeclRefExprs referring to FieldDecls.
16002     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16003       if (isa<FieldDecl>(E->getDecl()) &&
16004           !SemaRef.isUnevaluatedContext())
16005         return SemaRef.Diag(E->getLocation(),
16006                             diag::err_invalid_non_static_member_use)
16007             << E->getDecl() << E->getSourceRange();
16008 
16009       return BaseTransform::TransformDeclRefExpr(E);
16010     }
16011 
16012     // Exception: filter out member pointer formation
16013     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16014       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16015         return E;
16016 
16017       return BaseTransform::TransformUnaryOperator(E);
16018     }
16019 
16020     // The body of a lambda-expression is in a separate expression evaluation
16021     // context so never needs to be transformed.
16022     // FIXME: Ideally we wouldn't transform the closure type either, and would
16023     // just recreate the capture expressions and lambda expression.
16024     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16025       return SkipLambdaBody(E, Body);
16026     }
16027   };
16028 }
16029 
16030 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16031   assert(isUnevaluatedContext() &&
16032          "Should only transform unevaluated expressions");
16033   ExprEvalContexts.back().Context =
16034       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16035   if (isUnevaluatedContext())
16036     return E;
16037   return TransformToPE(*this).TransformExpr(E);
16038 }
16039 
16040 void
16041 Sema::PushExpressionEvaluationContext(
16042     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16043     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16044   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16045                                 LambdaContextDecl, ExprContext);
16046   Cleanup.reset();
16047   if (!MaybeODRUseExprs.empty())
16048     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16049 }
16050 
16051 void
16052 Sema::PushExpressionEvaluationContext(
16053     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16054     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16055   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16056   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16057 }
16058 
16059 namespace {
16060 
16061 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16062   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16063   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16064     if (E->getOpcode() == UO_Deref)
16065       return CheckPossibleDeref(S, E->getSubExpr());
16066   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16067     return CheckPossibleDeref(S, E->getBase());
16068   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16069     return CheckPossibleDeref(S, E->getBase());
16070   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16071     QualType Inner;
16072     QualType Ty = E->getType();
16073     if (const auto *Ptr = Ty->getAs<PointerType>())
16074       Inner = Ptr->getPointeeType();
16075     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16076       Inner = Arr->getElementType();
16077     else
16078       return nullptr;
16079 
16080     if (Inner->hasAttr(attr::NoDeref))
16081       return E;
16082   }
16083   return nullptr;
16084 }
16085 
16086 } // namespace
16087 
16088 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16089   for (const Expr *E : Rec.PossibleDerefs) {
16090     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16091     if (DeclRef) {
16092       const ValueDecl *Decl = DeclRef->getDecl();
16093       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16094           << Decl->getName() << E->getSourceRange();
16095       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16096     } else {
16097       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16098           << E->getSourceRange();
16099     }
16100   }
16101   Rec.PossibleDerefs.clear();
16102 }
16103 
16104 /// Check whether E, which is either a discarded-value expression or an
16105 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16106 /// and if so, remove it from the list of volatile-qualified assignments that
16107 /// we are going to warn are deprecated.
16108 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16109   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16110     return;
16111 
16112   // Note: ignoring parens here is not justified by the standard rules, but
16113   // ignoring parentheses seems like a more reasonable approach, and this only
16114   // drives a deprecation warning so doesn't affect conformance.
16115   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16116     if (BO->getOpcode() == BO_Assign) {
16117       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16118       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16119                  LHSs.end());
16120     }
16121   }
16122 }
16123 
16124 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16125   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16126       RebuildingImmediateInvocation)
16127     return E;
16128 
16129   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16130   /// It's OK if this fails; we'll also remove this in
16131   /// HandleImmediateInvocations, but catching it here allows us to avoid
16132   /// walking the AST looking for it in simple cases.
16133   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16134     if (auto *DeclRef =
16135             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16136       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16137 
16138   E = MaybeCreateExprWithCleanups(E);
16139 
16140   ConstantExpr *Res = ConstantExpr::Create(
16141       getASTContext(), E.get(),
16142       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
16143                                    getASTContext()),
16144       /*IsImmediateInvocation*/ true);
16145   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16146   return Res;
16147 }
16148 
16149 static void EvaluateAndDiagnoseImmediateInvocation(
16150     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16151   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16152   Expr::EvalResult Eval;
16153   Eval.Diag = &Notes;
16154   ConstantExpr *CE = Candidate.getPointer();
16155   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16156                                            SemaRef.getASTContext(), true);
16157   if (!Result || !Notes.empty()) {
16158     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16159     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16160       InnerExpr = FunctionalCast->getSubExpr();
16161     FunctionDecl *FD = nullptr;
16162     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16163       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16164     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16165       FD = Call->getConstructor();
16166     else
16167       llvm_unreachable("unhandled decl kind");
16168     assert(FD->isConsteval());
16169     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16170     for (auto &Note : Notes)
16171       SemaRef.Diag(Note.first, Note.second);
16172     return;
16173   }
16174   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16175 }
16176 
16177 static void RemoveNestedImmediateInvocation(
16178     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16179     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16180   struct ComplexRemove : TreeTransform<ComplexRemove> {
16181     using Base = TreeTransform<ComplexRemove>;
16182     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16183     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16184     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16185         CurrentII;
16186     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16187                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16188                   SmallVector<Sema::ImmediateInvocationCandidate,
16189                               4>::reverse_iterator Current)
16190         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16191     void RemoveImmediateInvocation(ConstantExpr* E) {
16192       auto It = std::find_if(CurrentII, IISet.rend(),
16193                              [E](Sema::ImmediateInvocationCandidate Elem) {
16194                                return Elem.getPointer() == E;
16195                              });
16196       assert(It != IISet.rend() &&
16197              "ConstantExpr marked IsImmediateInvocation should "
16198              "be present");
16199       It->setInt(1); // Mark as deleted
16200     }
16201     ExprResult TransformConstantExpr(ConstantExpr *E) {
16202       if (!E->isImmediateInvocation())
16203         return Base::TransformConstantExpr(E);
16204       RemoveImmediateInvocation(E);
16205       return Base::TransformExpr(E->getSubExpr());
16206     }
16207     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16208     /// we need to remove its DeclRefExpr from the DRSet.
16209     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16210       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16211       return Base::TransformCXXOperatorCallExpr(E);
16212     }
16213     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16214     /// here.
16215     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16216       if (!Init)
16217         return Init;
16218       /// ConstantExpr are the first layer of implicit node to be removed so if
16219       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16220       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16221         if (CE->isImmediateInvocation())
16222           RemoveImmediateInvocation(CE);
16223       return Base::TransformInitializer(Init, NotCopyInit);
16224     }
16225     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16226       DRSet.erase(E);
16227       return E;
16228     }
16229     bool AlwaysRebuild() { return false; }
16230     bool ReplacingOriginal() { return true; }
16231     bool AllowSkippingCXXConstructExpr() {
16232       bool Res = AllowSkippingFirstCXXConstructExpr;
16233       AllowSkippingFirstCXXConstructExpr = true;
16234       return Res;
16235     }
16236     bool AllowSkippingFirstCXXConstructExpr = true;
16237   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16238                 Rec.ImmediateInvocationCandidates, It);
16239 
16240   /// CXXConstructExpr with a single argument are getting skipped by
16241   /// TreeTransform in some situtation because they could be implicit. This
16242   /// can only occur for the top-level CXXConstructExpr because it is used
16243   /// nowhere in the expression being transformed therefore will not be rebuilt.
16244   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16245   /// skipping the first CXXConstructExpr.
16246   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16247     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16248 
16249   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16250   assert(Res.isUsable());
16251   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16252   It->getPointer()->setSubExpr(Res.get());
16253 }
16254 
16255 static void
16256 HandleImmediateInvocations(Sema &SemaRef,
16257                            Sema::ExpressionEvaluationContextRecord &Rec) {
16258   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16259        Rec.ReferenceToConsteval.size() == 0) ||
16260       SemaRef.RebuildingImmediateInvocation)
16261     return;
16262 
16263   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16264   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16265   /// need to remove ReferenceToConsteval in the immediate invocation.
16266   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16267 
16268     /// Prevent sema calls during the tree transform from adding pointers that
16269     /// are already in the sets.
16270     llvm::SaveAndRestore<bool> DisableIITracking(
16271         SemaRef.RebuildingImmediateInvocation, true);
16272 
16273     /// Prevent diagnostic during tree transfrom as they are duplicates
16274     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16275 
16276     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16277          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16278       if (!It->getInt())
16279         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16280   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16281              Rec.ReferenceToConsteval.size()) {
16282     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16283       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16284       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16285       bool VisitDeclRefExpr(DeclRefExpr *E) {
16286         DRSet.erase(E);
16287         return DRSet.size();
16288       }
16289     } Visitor(Rec.ReferenceToConsteval);
16290     Visitor.TraverseStmt(
16291         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16292   }
16293   for (auto CE : Rec.ImmediateInvocationCandidates)
16294     if (!CE.getInt())
16295       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16296   for (auto DR : Rec.ReferenceToConsteval) {
16297     auto *FD = cast<FunctionDecl>(DR->getDecl());
16298     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16299         << FD;
16300     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16301   }
16302 }
16303 
16304 void Sema::PopExpressionEvaluationContext() {
16305   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16306   unsigned NumTypos = Rec.NumTypos;
16307 
16308   if (!Rec.Lambdas.empty()) {
16309     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16310     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16311         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16312       unsigned D;
16313       if (Rec.isUnevaluated()) {
16314         // C++11 [expr.prim.lambda]p2:
16315         //   A lambda-expression shall not appear in an unevaluated operand
16316         //   (Clause 5).
16317         D = diag::err_lambda_unevaluated_operand;
16318       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16319         // C++1y [expr.const]p2:
16320         //   A conditional-expression e is a core constant expression unless the
16321         //   evaluation of e, following the rules of the abstract machine, would
16322         //   evaluate [...] a lambda-expression.
16323         D = diag::err_lambda_in_constant_expression;
16324       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16325         // C++17 [expr.prim.lamda]p2:
16326         // A lambda-expression shall not appear [...] in a template-argument.
16327         D = diag::err_lambda_in_invalid_context;
16328       } else
16329         llvm_unreachable("Couldn't infer lambda error message.");
16330 
16331       for (const auto *L : Rec.Lambdas)
16332         Diag(L->getBeginLoc(), D);
16333     }
16334   }
16335 
16336   WarnOnPendingNoDerefs(Rec);
16337   HandleImmediateInvocations(*this, Rec);
16338 
16339   // Warn on any volatile-qualified simple-assignments that are not discarded-
16340   // value expressions nor unevaluated operands (those cases get removed from
16341   // this list by CheckUnusedVolatileAssignment).
16342   for (auto *BO : Rec.VolatileAssignmentLHSs)
16343     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16344         << BO->getType();
16345 
16346   // When are coming out of an unevaluated context, clear out any
16347   // temporaries that we may have created as part of the evaluation of
16348   // the expression in that context: they aren't relevant because they
16349   // will never be constructed.
16350   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16351     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16352                              ExprCleanupObjects.end());
16353     Cleanup = Rec.ParentCleanup;
16354     CleanupVarDeclMarking();
16355     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16356   // Otherwise, merge the contexts together.
16357   } else {
16358     Cleanup.mergeFrom(Rec.ParentCleanup);
16359     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16360                             Rec.SavedMaybeODRUseExprs.end());
16361   }
16362 
16363   // Pop the current expression evaluation context off the stack.
16364   ExprEvalContexts.pop_back();
16365 
16366   // The global expression evaluation context record is never popped.
16367   ExprEvalContexts.back().NumTypos += NumTypos;
16368 }
16369 
16370 void Sema::DiscardCleanupsInEvaluationContext() {
16371   ExprCleanupObjects.erase(
16372          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16373          ExprCleanupObjects.end());
16374   Cleanup.reset();
16375   MaybeODRUseExprs.clear();
16376 }
16377 
16378 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16379   ExprResult Result = CheckPlaceholderExpr(E);
16380   if (Result.isInvalid())
16381     return ExprError();
16382   E = Result.get();
16383   if (!E->getType()->isVariablyModifiedType())
16384     return E;
16385   return TransformToPotentiallyEvaluated(E);
16386 }
16387 
16388 /// Are we in a context that is potentially constant evaluated per C++20
16389 /// [expr.const]p12?
16390 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16391   /// C++2a [expr.const]p12:
16392   //   An expression or conversion is potentially constant evaluated if it is
16393   switch (SemaRef.ExprEvalContexts.back().Context) {
16394     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16395       // -- a manifestly constant-evaluated expression,
16396     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16397     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16398     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16399       // -- a potentially-evaluated expression,
16400     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16401       // -- an immediate subexpression of a braced-init-list,
16402 
16403       // -- [FIXME] an expression of the form & cast-expression that occurs
16404       //    within a templated entity
16405       // -- a subexpression of one of the above that is not a subexpression of
16406       // a nested unevaluated operand.
16407       return true;
16408 
16409     case Sema::ExpressionEvaluationContext::Unevaluated:
16410     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16411       // Expressions in this context are never evaluated.
16412       return false;
16413   }
16414   llvm_unreachable("Invalid context");
16415 }
16416 
16417 /// Return true if this function has a calling convention that requires mangling
16418 /// in the size of the parameter pack.
16419 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16420   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16421   // we don't need parameter type sizes.
16422   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16423   if (!TT.isOSWindows() || !TT.isX86())
16424     return false;
16425 
16426   // If this is C++ and this isn't an extern "C" function, parameters do not
16427   // need to be complete. In this case, C++ mangling will apply, which doesn't
16428   // use the size of the parameters.
16429   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16430     return false;
16431 
16432   // Stdcall, fastcall, and vectorcall need this special treatment.
16433   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16434   switch (CC) {
16435   case CC_X86StdCall:
16436   case CC_X86FastCall:
16437   case CC_X86VectorCall:
16438     return true;
16439   default:
16440     break;
16441   }
16442   return false;
16443 }
16444 
16445 /// Require that all of the parameter types of function be complete. Normally,
16446 /// parameter types are only required to be complete when a function is called
16447 /// or defined, but to mangle functions with certain calling conventions, the
16448 /// mangler needs to know the size of the parameter list. In this situation,
16449 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16450 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16451 /// result in a linker error. Clang doesn't implement this behavior, and instead
16452 /// attempts to error at compile time.
16453 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16454                                                   SourceLocation Loc) {
16455   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16456     FunctionDecl *FD;
16457     ParmVarDecl *Param;
16458 
16459   public:
16460     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16461         : FD(FD), Param(Param) {}
16462 
16463     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16464       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16465       StringRef CCName;
16466       switch (CC) {
16467       case CC_X86StdCall:
16468         CCName = "stdcall";
16469         break;
16470       case CC_X86FastCall:
16471         CCName = "fastcall";
16472         break;
16473       case CC_X86VectorCall:
16474         CCName = "vectorcall";
16475         break;
16476       default:
16477         llvm_unreachable("CC does not need mangling");
16478       }
16479 
16480       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16481           << Param->getDeclName() << FD->getDeclName() << CCName;
16482     }
16483   };
16484 
16485   for (ParmVarDecl *Param : FD->parameters()) {
16486     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16487     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16488   }
16489 }
16490 
16491 namespace {
16492 enum class OdrUseContext {
16493   /// Declarations in this context are not odr-used.
16494   None,
16495   /// Declarations in this context are formally odr-used, but this is a
16496   /// dependent context.
16497   Dependent,
16498   /// Declarations in this context are odr-used but not actually used (yet).
16499   FormallyOdrUsed,
16500   /// Declarations in this context are used.
16501   Used
16502 };
16503 }
16504 
16505 /// Are we within a context in which references to resolved functions or to
16506 /// variables result in odr-use?
16507 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16508   OdrUseContext Result;
16509 
16510   switch (SemaRef.ExprEvalContexts.back().Context) {
16511     case Sema::ExpressionEvaluationContext::Unevaluated:
16512     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16513     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16514       return OdrUseContext::None;
16515 
16516     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16517     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16518       Result = OdrUseContext::Used;
16519       break;
16520 
16521     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16522       Result = OdrUseContext::FormallyOdrUsed;
16523       break;
16524 
16525     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16526       // A default argument formally results in odr-use, but doesn't actually
16527       // result in a use in any real sense until it itself is used.
16528       Result = OdrUseContext::FormallyOdrUsed;
16529       break;
16530   }
16531 
16532   if (SemaRef.CurContext->isDependentContext())
16533     return OdrUseContext::Dependent;
16534 
16535   return Result;
16536 }
16537 
16538 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16539   return Func->isConstexpr() &&
16540          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16541 }
16542 
16543 /// Mark a function referenced, and check whether it is odr-used
16544 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16545 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16546                                   bool MightBeOdrUse) {
16547   assert(Func && "No function?");
16548 
16549   Func->setReferenced();
16550 
16551   // Recursive functions aren't really used until they're used from some other
16552   // context.
16553   bool IsRecursiveCall = CurContext == Func;
16554 
16555   // C++11 [basic.def.odr]p3:
16556   //   A function whose name appears as a potentially-evaluated expression is
16557   //   odr-used if it is the unique lookup result or the selected member of a
16558   //   set of overloaded functions [...].
16559   //
16560   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16561   // can just check that here.
16562   OdrUseContext OdrUse =
16563       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16564   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16565     OdrUse = OdrUseContext::FormallyOdrUsed;
16566 
16567   // Trivial default constructors and destructors are never actually used.
16568   // FIXME: What about other special members?
16569   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16570       OdrUse == OdrUseContext::Used) {
16571     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16572       if (Constructor->isDefaultConstructor())
16573         OdrUse = OdrUseContext::FormallyOdrUsed;
16574     if (isa<CXXDestructorDecl>(Func))
16575       OdrUse = OdrUseContext::FormallyOdrUsed;
16576   }
16577 
16578   // C++20 [expr.const]p12:
16579   //   A function [...] is needed for constant evaluation if it is [...] a
16580   //   constexpr function that is named by an expression that is potentially
16581   //   constant evaluated
16582   bool NeededForConstantEvaluation =
16583       isPotentiallyConstantEvaluatedContext(*this) &&
16584       isImplicitlyDefinableConstexprFunction(Func);
16585 
16586   // Determine whether we require a function definition to exist, per
16587   // C++11 [temp.inst]p3:
16588   //   Unless a function template specialization has been explicitly
16589   //   instantiated or explicitly specialized, the function template
16590   //   specialization is implicitly instantiated when the specialization is
16591   //   referenced in a context that requires a function definition to exist.
16592   // C++20 [temp.inst]p7:
16593   //   The existence of a definition of a [...] function is considered to
16594   //   affect the semantics of the program if the [...] function is needed for
16595   //   constant evaluation by an expression
16596   // C++20 [basic.def.odr]p10:
16597   //   Every program shall contain exactly one definition of every non-inline
16598   //   function or variable that is odr-used in that program outside of a
16599   //   discarded statement
16600   // C++20 [special]p1:
16601   //   The implementation will implicitly define [defaulted special members]
16602   //   if they are odr-used or needed for constant evaluation.
16603   //
16604   // Note that we skip the implicit instantiation of templates that are only
16605   // used in unused default arguments or by recursive calls to themselves.
16606   // This is formally non-conforming, but seems reasonable in practice.
16607   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16608                                              NeededForConstantEvaluation);
16609 
16610   // C++14 [temp.expl.spec]p6:
16611   //   If a template [...] is explicitly specialized then that specialization
16612   //   shall be declared before the first use of that specialization that would
16613   //   cause an implicit instantiation to take place, in every translation unit
16614   //   in which such a use occurs
16615   if (NeedDefinition &&
16616       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16617        Func->getMemberSpecializationInfo()))
16618     checkSpecializationVisibility(Loc, Func);
16619 
16620   if (getLangOpts().CUDA)
16621     CheckCUDACall(Loc, Func);
16622 
16623   if (getLangOpts().SYCLIsDevice)
16624     checkSYCLDeviceFunction(Loc, Func);
16625 
16626   // If we need a definition, try to create one.
16627   if (NeedDefinition && !Func->getBody()) {
16628     runWithSufficientStackSpace(Loc, [&] {
16629       if (CXXConstructorDecl *Constructor =
16630               dyn_cast<CXXConstructorDecl>(Func)) {
16631         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16632         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16633           if (Constructor->isDefaultConstructor()) {
16634             if (Constructor->isTrivial() &&
16635                 !Constructor->hasAttr<DLLExportAttr>())
16636               return;
16637             DefineImplicitDefaultConstructor(Loc, Constructor);
16638           } else if (Constructor->isCopyConstructor()) {
16639             DefineImplicitCopyConstructor(Loc, Constructor);
16640           } else if (Constructor->isMoveConstructor()) {
16641             DefineImplicitMoveConstructor(Loc, Constructor);
16642           }
16643         } else if (Constructor->getInheritedConstructor()) {
16644           DefineInheritingConstructor(Loc, Constructor);
16645         }
16646       } else if (CXXDestructorDecl *Destructor =
16647                      dyn_cast<CXXDestructorDecl>(Func)) {
16648         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16649         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16650           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16651             return;
16652           DefineImplicitDestructor(Loc, Destructor);
16653         }
16654         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16655           MarkVTableUsed(Loc, Destructor->getParent());
16656       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16657         if (MethodDecl->isOverloadedOperator() &&
16658             MethodDecl->getOverloadedOperator() == OO_Equal) {
16659           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16660           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16661             if (MethodDecl->isCopyAssignmentOperator())
16662               DefineImplicitCopyAssignment(Loc, MethodDecl);
16663             else if (MethodDecl->isMoveAssignmentOperator())
16664               DefineImplicitMoveAssignment(Loc, MethodDecl);
16665           }
16666         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16667                    MethodDecl->getParent()->isLambda()) {
16668           CXXConversionDecl *Conversion =
16669               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16670           if (Conversion->isLambdaToBlockPointerConversion())
16671             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16672           else
16673             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16674         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16675           MarkVTableUsed(Loc, MethodDecl->getParent());
16676       }
16677 
16678       if (Func->isDefaulted() && !Func->isDeleted()) {
16679         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16680         if (DCK != DefaultedComparisonKind::None)
16681           DefineDefaultedComparison(Loc, Func, DCK);
16682       }
16683 
16684       // Implicit instantiation of function templates and member functions of
16685       // class templates.
16686       if (Func->isImplicitlyInstantiable()) {
16687         TemplateSpecializationKind TSK =
16688             Func->getTemplateSpecializationKindForInstantiation();
16689         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16690         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16691         if (FirstInstantiation) {
16692           PointOfInstantiation = Loc;
16693           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16694         } else if (TSK != TSK_ImplicitInstantiation) {
16695           // Use the point of use as the point of instantiation, instead of the
16696           // point of explicit instantiation (which we track as the actual point
16697           // of instantiation). This gives better backtraces in diagnostics.
16698           PointOfInstantiation = Loc;
16699         }
16700 
16701         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16702             Func->isConstexpr()) {
16703           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16704               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16705               CodeSynthesisContexts.size())
16706             PendingLocalImplicitInstantiations.push_back(
16707                 std::make_pair(Func, PointOfInstantiation));
16708           else if (Func->isConstexpr())
16709             // Do not defer instantiations of constexpr functions, to avoid the
16710             // expression evaluator needing to call back into Sema if it sees a
16711             // call to such a function.
16712             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16713           else {
16714             Func->setInstantiationIsPending(true);
16715             PendingInstantiations.push_back(
16716                 std::make_pair(Func, PointOfInstantiation));
16717             // Notify the consumer that a function was implicitly instantiated.
16718             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16719           }
16720         }
16721       } else {
16722         // Walk redefinitions, as some of them may be instantiable.
16723         for (auto i : Func->redecls()) {
16724           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16725             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16726         }
16727       }
16728     });
16729   }
16730 
16731   // C++14 [except.spec]p17:
16732   //   An exception-specification is considered to be needed when:
16733   //   - the function is odr-used or, if it appears in an unevaluated operand,
16734   //     would be odr-used if the expression were potentially-evaluated;
16735   //
16736   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16737   // function is a pure virtual function we're calling, and in that case the
16738   // function was selected by overload resolution and we need to resolve its
16739   // exception specification for a different reason.
16740   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16741   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16742     ResolveExceptionSpec(Loc, FPT);
16743 
16744   // If this is the first "real" use, act on that.
16745   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16746     // Keep track of used but undefined functions.
16747     if (!Func->isDefined()) {
16748       if (mightHaveNonExternalLinkage(Func))
16749         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16750       else if (Func->getMostRecentDecl()->isInlined() &&
16751                !LangOpts.GNUInline &&
16752                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16753         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16754       else if (isExternalWithNoLinkageType(Func))
16755         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16756     }
16757 
16758     // Some x86 Windows calling conventions mangle the size of the parameter
16759     // pack into the name. Computing the size of the parameters requires the
16760     // parameter types to be complete. Check that now.
16761     if (funcHasParameterSizeMangling(*this, Func))
16762       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16763 
16764     // In the MS C++ ABI, the compiler emits destructor variants where they are
16765     // used. If the destructor is used here but defined elsewhere, mark the
16766     // virtual base destructors referenced. If those virtual base destructors
16767     // are inline, this will ensure they are defined when emitting the complete
16768     // destructor variant. This checking may be redundant if the destructor is
16769     // provided later in this TU.
16770     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16771       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16772         CXXRecordDecl *Parent = Dtor->getParent();
16773         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16774           CheckCompleteDestructorVariant(Loc, Dtor);
16775       }
16776     }
16777 
16778     Func->markUsed(Context);
16779   }
16780 }
16781 
16782 /// Directly mark a variable odr-used. Given a choice, prefer to use
16783 /// MarkVariableReferenced since it does additional checks and then
16784 /// calls MarkVarDeclODRUsed.
16785 /// If the variable must be captured:
16786 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16787 ///  - else capture it in the DeclContext that maps to the
16788 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16789 static void
16790 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16791                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16792   // Keep track of used but undefined variables.
16793   // FIXME: We shouldn't suppress this warning for static data members.
16794   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16795       (!Var->isExternallyVisible() || Var->isInline() ||
16796        SemaRef.isExternalWithNoLinkageType(Var)) &&
16797       !(Var->isStaticDataMember() && Var->hasInit())) {
16798     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16799     if (old.isInvalid())
16800       old = Loc;
16801   }
16802   QualType CaptureType, DeclRefType;
16803   if (SemaRef.LangOpts.OpenMP)
16804     SemaRef.tryCaptureOpenMPLambdas(Var);
16805   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16806     /*EllipsisLoc*/ SourceLocation(),
16807     /*BuildAndDiagnose*/ true,
16808     CaptureType, DeclRefType,
16809     FunctionScopeIndexToStopAt);
16810 
16811   Var->markUsed(SemaRef.Context);
16812 }
16813 
16814 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16815                                              SourceLocation Loc,
16816                                              unsigned CapturingScopeIndex) {
16817   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16818 }
16819 
16820 static void
16821 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16822                                    ValueDecl *var, DeclContext *DC) {
16823   DeclContext *VarDC = var->getDeclContext();
16824 
16825   //  If the parameter still belongs to the translation unit, then
16826   //  we're actually just using one parameter in the declaration of
16827   //  the next.
16828   if (isa<ParmVarDecl>(var) &&
16829       isa<TranslationUnitDecl>(VarDC))
16830     return;
16831 
16832   // For C code, don't diagnose about capture if we're not actually in code
16833   // right now; it's impossible to write a non-constant expression outside of
16834   // function context, so we'll get other (more useful) diagnostics later.
16835   //
16836   // For C++, things get a bit more nasty... it would be nice to suppress this
16837   // diagnostic for certain cases like using a local variable in an array bound
16838   // for a member of a local class, but the correct predicate is not obvious.
16839   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16840     return;
16841 
16842   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16843   unsigned ContextKind = 3; // unknown
16844   if (isa<CXXMethodDecl>(VarDC) &&
16845       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16846     ContextKind = 2;
16847   } else if (isa<FunctionDecl>(VarDC)) {
16848     ContextKind = 0;
16849   } else if (isa<BlockDecl>(VarDC)) {
16850     ContextKind = 1;
16851   }
16852 
16853   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16854     << var << ValueKind << ContextKind << VarDC;
16855   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16856       << var;
16857 
16858   // FIXME: Add additional diagnostic info about class etc. which prevents
16859   // capture.
16860 }
16861 
16862 
16863 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16864                                       bool &SubCapturesAreNested,
16865                                       QualType &CaptureType,
16866                                       QualType &DeclRefType) {
16867    // Check whether we've already captured it.
16868   if (CSI->CaptureMap.count(Var)) {
16869     // If we found a capture, any subcaptures are nested.
16870     SubCapturesAreNested = true;
16871 
16872     // Retrieve the capture type for this variable.
16873     CaptureType = CSI->getCapture(Var).getCaptureType();
16874 
16875     // Compute the type of an expression that refers to this variable.
16876     DeclRefType = CaptureType.getNonReferenceType();
16877 
16878     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16879     // are mutable in the sense that user can change their value - they are
16880     // private instances of the captured declarations.
16881     const Capture &Cap = CSI->getCapture(Var);
16882     if (Cap.isCopyCapture() &&
16883         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16884         !(isa<CapturedRegionScopeInfo>(CSI) &&
16885           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16886       DeclRefType.addConst();
16887     return true;
16888   }
16889   return false;
16890 }
16891 
16892 // Only block literals, captured statements, and lambda expressions can
16893 // capture; other scopes don't work.
16894 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16895                                  SourceLocation Loc,
16896                                  const bool Diagnose, Sema &S) {
16897   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16898     return getLambdaAwareParentOfDeclContext(DC);
16899   else if (Var->hasLocalStorage()) {
16900     if (Diagnose)
16901        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16902   }
16903   return nullptr;
16904 }
16905 
16906 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16907 // certain types of variables (unnamed, variably modified types etc.)
16908 // so check for eligibility.
16909 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16910                                  SourceLocation Loc,
16911                                  const bool Diagnose, Sema &S) {
16912 
16913   bool IsBlock = isa<BlockScopeInfo>(CSI);
16914   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16915 
16916   // Lambdas are not allowed to capture unnamed variables
16917   // (e.g. anonymous unions).
16918   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16919   // assuming that's the intent.
16920   if (IsLambda && !Var->getDeclName()) {
16921     if (Diagnose) {
16922       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16923       S.Diag(Var->getLocation(), diag::note_declared_at);
16924     }
16925     return false;
16926   }
16927 
16928   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16929   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16930     if (Diagnose) {
16931       S.Diag(Loc, diag::err_ref_vm_type);
16932       S.Diag(Var->getLocation(), diag::note_previous_decl)
16933         << Var->getDeclName();
16934     }
16935     return false;
16936   }
16937   // Prohibit structs with flexible array members too.
16938   // We cannot capture what is in the tail end of the struct.
16939   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16940     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16941       if (Diagnose) {
16942         if (IsBlock)
16943           S.Diag(Loc, diag::err_ref_flexarray_type);
16944         else
16945           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16946             << Var->getDeclName();
16947         S.Diag(Var->getLocation(), diag::note_previous_decl)
16948           << Var->getDeclName();
16949       }
16950       return false;
16951     }
16952   }
16953   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16954   // Lambdas and captured statements are not allowed to capture __block
16955   // variables; they don't support the expected semantics.
16956   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16957     if (Diagnose) {
16958       S.Diag(Loc, diag::err_capture_block_variable)
16959         << Var->getDeclName() << !IsLambda;
16960       S.Diag(Var->getLocation(), diag::note_previous_decl)
16961         << Var->getDeclName();
16962     }
16963     return false;
16964   }
16965   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16966   if (S.getLangOpts().OpenCL && IsBlock &&
16967       Var->getType()->isBlockPointerType()) {
16968     if (Diagnose)
16969       S.Diag(Loc, diag::err_opencl_block_ref_block);
16970     return false;
16971   }
16972 
16973   return true;
16974 }
16975 
16976 // Returns true if the capture by block was successful.
16977 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16978                                  SourceLocation Loc,
16979                                  const bool BuildAndDiagnose,
16980                                  QualType &CaptureType,
16981                                  QualType &DeclRefType,
16982                                  const bool Nested,
16983                                  Sema &S, bool Invalid) {
16984   bool ByRef = false;
16985 
16986   // Blocks are not allowed to capture arrays, excepting OpenCL.
16987   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16988   // (decayed to pointers).
16989   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16990     if (BuildAndDiagnose) {
16991       S.Diag(Loc, diag::err_ref_array_type);
16992       S.Diag(Var->getLocation(), diag::note_previous_decl)
16993       << Var->getDeclName();
16994       Invalid = true;
16995     } else {
16996       return false;
16997     }
16998   }
16999 
17000   // Forbid the block-capture of autoreleasing variables.
17001   if (!Invalid &&
17002       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17003     if (BuildAndDiagnose) {
17004       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17005         << /*block*/ 0;
17006       S.Diag(Var->getLocation(), diag::note_previous_decl)
17007         << Var->getDeclName();
17008       Invalid = true;
17009     } else {
17010       return false;
17011     }
17012   }
17013 
17014   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17015   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17016     QualType PointeeTy = PT->getPointeeType();
17017 
17018     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17019         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17020         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17021       if (BuildAndDiagnose) {
17022         SourceLocation VarLoc = Var->getLocation();
17023         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17024         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17025       }
17026     }
17027   }
17028 
17029   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17030   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17031       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17032     // Block capture by reference does not change the capture or
17033     // declaration reference types.
17034     ByRef = true;
17035   } else {
17036     // Block capture by copy introduces 'const'.
17037     CaptureType = CaptureType.getNonReferenceType().withConst();
17038     DeclRefType = CaptureType;
17039   }
17040 
17041   // Actually capture the variable.
17042   if (BuildAndDiagnose)
17043     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17044                     CaptureType, Invalid);
17045 
17046   return !Invalid;
17047 }
17048 
17049 
17050 /// Capture the given variable in the captured region.
17051 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17052                                     VarDecl *Var,
17053                                     SourceLocation Loc,
17054                                     const bool BuildAndDiagnose,
17055                                     QualType &CaptureType,
17056                                     QualType &DeclRefType,
17057                                     const bool RefersToCapturedVariable,
17058                                     Sema &S, bool Invalid) {
17059   // By default, capture variables by reference.
17060   bool ByRef = true;
17061   // Using an LValue reference type is consistent with Lambdas (see below).
17062   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17063     if (S.isOpenMPCapturedDecl(Var)) {
17064       bool HasConst = DeclRefType.isConstQualified();
17065       DeclRefType = DeclRefType.getUnqualifiedType();
17066       // Don't lose diagnostics about assignments to const.
17067       if (HasConst)
17068         DeclRefType.addConst();
17069     }
17070     // Do not capture firstprivates in tasks.
17071     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17072         OMPC_unknown)
17073       return true;
17074     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17075                                     RSI->OpenMPCaptureLevel);
17076   }
17077 
17078   if (ByRef)
17079     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17080   else
17081     CaptureType = DeclRefType;
17082 
17083   // Actually capture the variable.
17084   if (BuildAndDiagnose)
17085     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17086                     Loc, SourceLocation(), CaptureType, Invalid);
17087 
17088   return !Invalid;
17089 }
17090 
17091 /// Capture the given variable in the lambda.
17092 static bool captureInLambda(LambdaScopeInfo *LSI,
17093                             VarDecl *Var,
17094                             SourceLocation Loc,
17095                             const bool BuildAndDiagnose,
17096                             QualType &CaptureType,
17097                             QualType &DeclRefType,
17098                             const bool RefersToCapturedVariable,
17099                             const Sema::TryCaptureKind Kind,
17100                             SourceLocation EllipsisLoc,
17101                             const bool IsTopScope,
17102                             Sema &S, bool Invalid) {
17103   // Determine whether we are capturing by reference or by value.
17104   bool ByRef = false;
17105   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17106     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17107   } else {
17108     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17109   }
17110 
17111   // Compute the type of the field that will capture this variable.
17112   if (ByRef) {
17113     // C++11 [expr.prim.lambda]p15:
17114     //   An entity is captured by reference if it is implicitly or
17115     //   explicitly captured but not captured by copy. It is
17116     //   unspecified whether additional unnamed non-static data
17117     //   members are declared in the closure type for entities
17118     //   captured by reference.
17119     //
17120     // FIXME: It is not clear whether we want to build an lvalue reference
17121     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17122     // to do the former, while EDG does the latter. Core issue 1249 will
17123     // clarify, but for now we follow GCC because it's a more permissive and
17124     // easily defensible position.
17125     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17126   } else {
17127     // C++11 [expr.prim.lambda]p14:
17128     //   For each entity captured by copy, an unnamed non-static
17129     //   data member is declared in the closure type. The
17130     //   declaration order of these members is unspecified. The type
17131     //   of such a data member is the type of the corresponding
17132     //   captured entity if the entity is not a reference to an
17133     //   object, or the referenced type otherwise. [Note: If the
17134     //   captured entity is a reference to a function, the
17135     //   corresponding data member is also a reference to a
17136     //   function. - end note ]
17137     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17138       if (!RefType->getPointeeType()->isFunctionType())
17139         CaptureType = RefType->getPointeeType();
17140     }
17141 
17142     // Forbid the lambda copy-capture of autoreleasing variables.
17143     if (!Invalid &&
17144         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17145       if (BuildAndDiagnose) {
17146         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17147         S.Diag(Var->getLocation(), diag::note_previous_decl)
17148           << Var->getDeclName();
17149         Invalid = true;
17150       } else {
17151         return false;
17152       }
17153     }
17154 
17155     // Make sure that by-copy captures are of a complete and non-abstract type.
17156     if (!Invalid && BuildAndDiagnose) {
17157       if (!CaptureType->isDependentType() &&
17158           S.RequireCompleteSizedType(
17159               Loc, CaptureType,
17160               diag::err_capture_of_incomplete_or_sizeless_type,
17161               Var->getDeclName()))
17162         Invalid = true;
17163       else if (S.RequireNonAbstractType(Loc, CaptureType,
17164                                         diag::err_capture_of_abstract_type))
17165         Invalid = true;
17166     }
17167   }
17168 
17169   // Compute the type of a reference to this captured variable.
17170   if (ByRef)
17171     DeclRefType = CaptureType.getNonReferenceType();
17172   else {
17173     // C++ [expr.prim.lambda]p5:
17174     //   The closure type for a lambda-expression has a public inline
17175     //   function call operator [...]. This function call operator is
17176     //   declared const (9.3.1) if and only if the lambda-expression's
17177     //   parameter-declaration-clause is not followed by mutable.
17178     DeclRefType = CaptureType.getNonReferenceType();
17179     if (!LSI->Mutable && !CaptureType->isReferenceType())
17180       DeclRefType.addConst();
17181   }
17182 
17183   // Add the capture.
17184   if (BuildAndDiagnose)
17185     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17186                     Loc, EllipsisLoc, CaptureType, Invalid);
17187 
17188   return !Invalid;
17189 }
17190 
17191 bool Sema::tryCaptureVariable(
17192     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17193     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17194     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17195   // An init-capture is notionally from the context surrounding its
17196   // declaration, but its parent DC is the lambda class.
17197   DeclContext *VarDC = Var->getDeclContext();
17198   if (Var->isInitCapture())
17199     VarDC = VarDC->getParent();
17200 
17201   DeclContext *DC = CurContext;
17202   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17203       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17204   // We need to sync up the Declaration Context with the
17205   // FunctionScopeIndexToStopAt
17206   if (FunctionScopeIndexToStopAt) {
17207     unsigned FSIndex = FunctionScopes.size() - 1;
17208     while (FSIndex != MaxFunctionScopesIndex) {
17209       DC = getLambdaAwareParentOfDeclContext(DC);
17210       --FSIndex;
17211     }
17212   }
17213 
17214 
17215   // If the variable is declared in the current context, there is no need to
17216   // capture it.
17217   if (VarDC == DC) return true;
17218 
17219   // Capture global variables if it is required to use private copy of this
17220   // variable.
17221   bool IsGlobal = !Var->hasLocalStorage();
17222   if (IsGlobal &&
17223       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17224                                                 MaxFunctionScopesIndex)))
17225     return true;
17226   Var = Var->getCanonicalDecl();
17227 
17228   // Walk up the stack to determine whether we can capture the variable,
17229   // performing the "simple" checks that don't depend on type. We stop when
17230   // we've either hit the declared scope of the variable or find an existing
17231   // capture of that variable.  We start from the innermost capturing-entity
17232   // (the DC) and ensure that all intervening capturing-entities
17233   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17234   // declcontext can either capture the variable or have already captured
17235   // the variable.
17236   CaptureType = Var->getType();
17237   DeclRefType = CaptureType.getNonReferenceType();
17238   bool Nested = false;
17239   bool Explicit = (Kind != TryCapture_Implicit);
17240   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17241   do {
17242     // Only block literals, captured statements, and lambda expressions can
17243     // capture; other scopes don't work.
17244     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17245                                                               ExprLoc,
17246                                                               BuildAndDiagnose,
17247                                                               *this);
17248     // We need to check for the parent *first* because, if we *have*
17249     // private-captured a global variable, we need to recursively capture it in
17250     // intermediate blocks, lambdas, etc.
17251     if (!ParentDC) {
17252       if (IsGlobal) {
17253         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17254         break;
17255       }
17256       return true;
17257     }
17258 
17259     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17260     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17261 
17262 
17263     // Check whether we've already captured it.
17264     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17265                                              DeclRefType)) {
17266       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17267       break;
17268     }
17269     // If we are instantiating a generic lambda call operator body,
17270     // we do not want to capture new variables.  What was captured
17271     // during either a lambdas transformation or initial parsing
17272     // should be used.
17273     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17274       if (BuildAndDiagnose) {
17275         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17276         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17277           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17278           Diag(Var->getLocation(), diag::note_previous_decl)
17279              << Var->getDeclName();
17280           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17281         } else
17282           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17283       }
17284       return true;
17285     }
17286 
17287     // Try to capture variable-length arrays types.
17288     if (Var->getType()->isVariablyModifiedType()) {
17289       // We're going to walk down into the type and look for VLA
17290       // expressions.
17291       QualType QTy = Var->getType();
17292       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17293         QTy = PVD->getOriginalType();
17294       captureVariablyModifiedType(Context, QTy, CSI);
17295     }
17296 
17297     if (getLangOpts().OpenMP) {
17298       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17299         // OpenMP private variables should not be captured in outer scope, so
17300         // just break here. Similarly, global variables that are captured in a
17301         // target region should not be captured outside the scope of the region.
17302         if (RSI->CapRegionKind == CR_OpenMP) {
17303           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17304               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17305           // If the variable is private (i.e. not captured) and has variably
17306           // modified type, we still need to capture the type for correct
17307           // codegen in all regions, associated with the construct. Currently,
17308           // it is captured in the innermost captured region only.
17309           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17310               Var->getType()->isVariablyModifiedType()) {
17311             QualType QTy = Var->getType();
17312             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17313               QTy = PVD->getOriginalType();
17314             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17315                  I < E; ++I) {
17316               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17317                   FunctionScopes[FunctionScopesIndex - I]);
17318               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17319                      "Wrong number of captured regions associated with the "
17320                      "OpenMP construct.");
17321               captureVariablyModifiedType(Context, QTy, OuterRSI);
17322             }
17323           }
17324           bool IsTargetCap =
17325               IsOpenMPPrivateDecl != OMPC_private &&
17326               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17327                                          RSI->OpenMPCaptureLevel);
17328           // Do not capture global if it is not privatized in outer regions.
17329           bool IsGlobalCap =
17330               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17331                                                      RSI->OpenMPCaptureLevel);
17332 
17333           // When we detect target captures we are looking from inside the
17334           // target region, therefore we need to propagate the capture from the
17335           // enclosing region. Therefore, the capture is not initially nested.
17336           if (IsTargetCap)
17337             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17338 
17339           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17340               (IsGlobal && !IsGlobalCap)) {
17341             Nested = !IsTargetCap;
17342             DeclRefType = DeclRefType.getUnqualifiedType();
17343             CaptureType = Context.getLValueReferenceType(DeclRefType);
17344             break;
17345           }
17346         }
17347       }
17348     }
17349     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17350       // No capture-default, and this is not an explicit capture
17351       // so cannot capture this variable.
17352       if (BuildAndDiagnose) {
17353         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17354         Diag(Var->getLocation(), diag::note_previous_decl)
17355           << Var->getDeclName();
17356         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17357           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17358                diag::note_lambda_decl);
17359         // FIXME: If we error out because an outer lambda can not implicitly
17360         // capture a variable that an inner lambda explicitly captures, we
17361         // should have the inner lambda do the explicit capture - because
17362         // it makes for cleaner diagnostics later.  This would purely be done
17363         // so that the diagnostic does not misleadingly claim that a variable
17364         // can not be captured by a lambda implicitly even though it is captured
17365         // explicitly.  Suggestion:
17366         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17367         //    at the function head
17368         //  - cache the StartingDeclContext - this must be a lambda
17369         //  - captureInLambda in the innermost lambda the variable.
17370       }
17371       return true;
17372     }
17373 
17374     FunctionScopesIndex--;
17375     DC = ParentDC;
17376     Explicit = false;
17377   } while (!VarDC->Equals(DC));
17378 
17379   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17380   // computing the type of the capture at each step, checking type-specific
17381   // requirements, and adding captures if requested.
17382   // If the variable had already been captured previously, we start capturing
17383   // at the lambda nested within that one.
17384   bool Invalid = false;
17385   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17386        ++I) {
17387     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17388 
17389     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17390     // certain types of variables (unnamed, variably modified types etc.)
17391     // so check for eligibility.
17392     if (!Invalid)
17393       Invalid =
17394           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17395 
17396     // After encountering an error, if we're actually supposed to capture, keep
17397     // capturing in nested contexts to suppress any follow-on diagnostics.
17398     if (Invalid && !BuildAndDiagnose)
17399       return true;
17400 
17401     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17402       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17403                                DeclRefType, Nested, *this, Invalid);
17404       Nested = true;
17405     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17406       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17407                                          CaptureType, DeclRefType, Nested,
17408                                          *this, Invalid);
17409       Nested = true;
17410     } else {
17411       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17412       Invalid =
17413           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17414                            DeclRefType, Nested, Kind, EllipsisLoc,
17415                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17416       Nested = true;
17417     }
17418 
17419     if (Invalid && !BuildAndDiagnose)
17420       return true;
17421   }
17422   return Invalid;
17423 }
17424 
17425 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17426                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17427   QualType CaptureType;
17428   QualType DeclRefType;
17429   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17430                             /*BuildAndDiagnose=*/true, CaptureType,
17431                             DeclRefType, nullptr);
17432 }
17433 
17434 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17435   QualType CaptureType;
17436   QualType DeclRefType;
17437   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17438                              /*BuildAndDiagnose=*/false, CaptureType,
17439                              DeclRefType, nullptr);
17440 }
17441 
17442 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17443   QualType CaptureType;
17444   QualType DeclRefType;
17445 
17446   // Determine whether we can capture this variable.
17447   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17448                          /*BuildAndDiagnose=*/false, CaptureType,
17449                          DeclRefType, nullptr))
17450     return QualType();
17451 
17452   return DeclRefType;
17453 }
17454 
17455 namespace {
17456 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17457 // The produced TemplateArgumentListInfo* points to data stored within this
17458 // object, so should only be used in contexts where the pointer will not be
17459 // used after the CopiedTemplateArgs object is destroyed.
17460 class CopiedTemplateArgs {
17461   bool HasArgs;
17462   TemplateArgumentListInfo TemplateArgStorage;
17463 public:
17464   template<typename RefExpr>
17465   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17466     if (HasArgs)
17467       E->copyTemplateArgumentsInto(TemplateArgStorage);
17468   }
17469   operator TemplateArgumentListInfo*()
17470 #ifdef __has_cpp_attribute
17471 #if __has_cpp_attribute(clang::lifetimebound)
17472   [[clang::lifetimebound]]
17473 #endif
17474 #endif
17475   {
17476     return HasArgs ? &TemplateArgStorage : nullptr;
17477   }
17478 };
17479 }
17480 
17481 /// Walk the set of potential results of an expression and mark them all as
17482 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17483 ///
17484 /// \return A new expression if we found any potential results, ExprEmpty() if
17485 ///         not, and ExprError() if we diagnosed an error.
17486 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17487                                                       NonOdrUseReason NOUR) {
17488   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17489   // an object that satisfies the requirements for appearing in a
17490   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17491   // is immediately applied."  This function handles the lvalue-to-rvalue
17492   // conversion part.
17493   //
17494   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17495   // transform it into the relevant kind of non-odr-use node and rebuild the
17496   // tree of nodes leading to it.
17497   //
17498   // This is a mini-TreeTransform that only transforms a restricted subset of
17499   // nodes (and only certain operands of them).
17500 
17501   // Rebuild a subexpression.
17502   auto Rebuild = [&](Expr *Sub) {
17503     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17504   };
17505 
17506   // Check whether a potential result satisfies the requirements of NOUR.
17507   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17508     // Any entity other than a VarDecl is always odr-used whenever it's named
17509     // in a potentially-evaluated expression.
17510     auto *VD = dyn_cast<VarDecl>(D);
17511     if (!VD)
17512       return true;
17513 
17514     // C++2a [basic.def.odr]p4:
17515     //   A variable x whose name appears as a potentially-evalauted expression
17516     //   e is odr-used by e unless
17517     //   -- x is a reference that is usable in constant expressions, or
17518     //   -- x is a variable of non-reference type that is usable in constant
17519     //      expressions and has no mutable subobjects, and e is an element of
17520     //      the set of potential results of an expression of
17521     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17522     //      conversion is applied, or
17523     //   -- x is a variable of non-reference type, and e is an element of the
17524     //      set of potential results of a discarded-value expression to which
17525     //      the lvalue-to-rvalue conversion is not applied
17526     //
17527     // We check the first bullet and the "potentially-evaluated" condition in
17528     // BuildDeclRefExpr. We check the type requirements in the second bullet
17529     // in CheckLValueToRValueConversionOperand below.
17530     switch (NOUR) {
17531     case NOUR_None:
17532     case NOUR_Unevaluated:
17533       llvm_unreachable("unexpected non-odr-use-reason");
17534 
17535     case NOUR_Constant:
17536       // Constant references were handled when they were built.
17537       if (VD->getType()->isReferenceType())
17538         return true;
17539       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17540         if (RD->hasMutableFields())
17541           return true;
17542       if (!VD->isUsableInConstantExpressions(S.Context))
17543         return true;
17544       break;
17545 
17546     case NOUR_Discarded:
17547       if (VD->getType()->isReferenceType())
17548         return true;
17549       break;
17550     }
17551     return false;
17552   };
17553 
17554   // Mark that this expression does not constitute an odr-use.
17555   auto MarkNotOdrUsed = [&] {
17556     S.MaybeODRUseExprs.erase(E);
17557     if (LambdaScopeInfo *LSI = S.getCurLambda())
17558       LSI->markVariableExprAsNonODRUsed(E);
17559   };
17560 
17561   // C++2a [basic.def.odr]p2:
17562   //   The set of potential results of an expression e is defined as follows:
17563   switch (E->getStmtClass()) {
17564   //   -- If e is an id-expression, ...
17565   case Expr::DeclRefExprClass: {
17566     auto *DRE = cast<DeclRefExpr>(E);
17567     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17568       break;
17569 
17570     // Rebuild as a non-odr-use DeclRefExpr.
17571     MarkNotOdrUsed();
17572     return DeclRefExpr::Create(
17573         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17574         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17575         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17576         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17577   }
17578 
17579   case Expr::FunctionParmPackExprClass: {
17580     auto *FPPE = cast<FunctionParmPackExpr>(E);
17581     // If any of the declarations in the pack is odr-used, then the expression
17582     // as a whole constitutes an odr-use.
17583     for (VarDecl *D : *FPPE)
17584       if (IsPotentialResultOdrUsed(D))
17585         return ExprEmpty();
17586 
17587     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17588     // nothing cares about whether we marked this as an odr-use, but it might
17589     // be useful for non-compiler tools.
17590     MarkNotOdrUsed();
17591     break;
17592   }
17593 
17594   //   -- If e is a subscripting operation with an array operand...
17595   case Expr::ArraySubscriptExprClass: {
17596     auto *ASE = cast<ArraySubscriptExpr>(E);
17597     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17598     if (!OldBase->getType()->isArrayType())
17599       break;
17600     ExprResult Base = Rebuild(OldBase);
17601     if (!Base.isUsable())
17602       return Base;
17603     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17604     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17605     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17606     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17607                                      ASE->getRBracketLoc());
17608   }
17609 
17610   case Expr::MemberExprClass: {
17611     auto *ME = cast<MemberExpr>(E);
17612     // -- If e is a class member access expression [...] naming a non-static
17613     //    data member...
17614     if (isa<FieldDecl>(ME->getMemberDecl())) {
17615       ExprResult Base = Rebuild(ME->getBase());
17616       if (!Base.isUsable())
17617         return Base;
17618       return MemberExpr::Create(
17619           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17620           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17621           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17622           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17623           ME->getObjectKind(), ME->isNonOdrUse());
17624     }
17625 
17626     if (ME->getMemberDecl()->isCXXInstanceMember())
17627       break;
17628 
17629     // -- If e is a class member access expression naming a static data member,
17630     //    ...
17631     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17632       break;
17633 
17634     // Rebuild as a non-odr-use MemberExpr.
17635     MarkNotOdrUsed();
17636     return MemberExpr::Create(
17637         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17638         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17639         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17640         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17641     return ExprEmpty();
17642   }
17643 
17644   case Expr::BinaryOperatorClass: {
17645     auto *BO = cast<BinaryOperator>(E);
17646     Expr *LHS = BO->getLHS();
17647     Expr *RHS = BO->getRHS();
17648     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17649     if (BO->getOpcode() == BO_PtrMemD) {
17650       ExprResult Sub = Rebuild(LHS);
17651       if (!Sub.isUsable())
17652         return Sub;
17653       LHS = Sub.get();
17654     //   -- If e is a comma expression, ...
17655     } else if (BO->getOpcode() == BO_Comma) {
17656       ExprResult Sub = Rebuild(RHS);
17657       if (!Sub.isUsable())
17658         return Sub;
17659       RHS = Sub.get();
17660     } else {
17661       break;
17662     }
17663     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17664                         LHS, RHS);
17665   }
17666 
17667   //   -- If e has the form (e1)...
17668   case Expr::ParenExprClass: {
17669     auto *PE = cast<ParenExpr>(E);
17670     ExprResult Sub = Rebuild(PE->getSubExpr());
17671     if (!Sub.isUsable())
17672       return Sub;
17673     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17674   }
17675 
17676   //   -- If e is a glvalue conditional expression, ...
17677   // We don't apply this to a binary conditional operator. FIXME: Should we?
17678   case Expr::ConditionalOperatorClass: {
17679     auto *CO = cast<ConditionalOperator>(E);
17680     ExprResult LHS = Rebuild(CO->getLHS());
17681     if (LHS.isInvalid())
17682       return ExprError();
17683     ExprResult RHS = Rebuild(CO->getRHS());
17684     if (RHS.isInvalid())
17685       return ExprError();
17686     if (!LHS.isUsable() && !RHS.isUsable())
17687       return ExprEmpty();
17688     if (!LHS.isUsable())
17689       LHS = CO->getLHS();
17690     if (!RHS.isUsable())
17691       RHS = CO->getRHS();
17692     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17693                                 CO->getCond(), LHS.get(), RHS.get());
17694   }
17695 
17696   // [Clang extension]
17697   //   -- If e has the form __extension__ e1...
17698   case Expr::UnaryOperatorClass: {
17699     auto *UO = cast<UnaryOperator>(E);
17700     if (UO->getOpcode() != UO_Extension)
17701       break;
17702     ExprResult Sub = Rebuild(UO->getSubExpr());
17703     if (!Sub.isUsable())
17704       return Sub;
17705     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17706                           Sub.get());
17707   }
17708 
17709   // [Clang extension]
17710   //   -- If e has the form _Generic(...), the set of potential results is the
17711   //      union of the sets of potential results of the associated expressions.
17712   case Expr::GenericSelectionExprClass: {
17713     auto *GSE = cast<GenericSelectionExpr>(E);
17714 
17715     SmallVector<Expr *, 4> AssocExprs;
17716     bool AnyChanged = false;
17717     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17718       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17719       if (AssocExpr.isInvalid())
17720         return ExprError();
17721       if (AssocExpr.isUsable()) {
17722         AssocExprs.push_back(AssocExpr.get());
17723         AnyChanged = true;
17724       } else {
17725         AssocExprs.push_back(OrigAssocExpr);
17726       }
17727     }
17728 
17729     return AnyChanged ? S.CreateGenericSelectionExpr(
17730                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17731                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17732                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17733                       : ExprEmpty();
17734   }
17735 
17736   // [Clang extension]
17737   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17738   //      results is the union of the sets of potential results of the
17739   //      second and third subexpressions.
17740   case Expr::ChooseExprClass: {
17741     auto *CE = cast<ChooseExpr>(E);
17742 
17743     ExprResult LHS = Rebuild(CE->getLHS());
17744     if (LHS.isInvalid())
17745       return ExprError();
17746 
17747     ExprResult RHS = Rebuild(CE->getLHS());
17748     if (RHS.isInvalid())
17749       return ExprError();
17750 
17751     if (!LHS.get() && !RHS.get())
17752       return ExprEmpty();
17753     if (!LHS.isUsable())
17754       LHS = CE->getLHS();
17755     if (!RHS.isUsable())
17756       RHS = CE->getRHS();
17757 
17758     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17759                              RHS.get(), CE->getRParenLoc());
17760   }
17761 
17762   // Step through non-syntactic nodes.
17763   case Expr::ConstantExprClass: {
17764     auto *CE = cast<ConstantExpr>(E);
17765     ExprResult Sub = Rebuild(CE->getSubExpr());
17766     if (!Sub.isUsable())
17767       return Sub;
17768     return ConstantExpr::Create(S.Context, Sub.get());
17769   }
17770 
17771   // We could mostly rely on the recursive rebuilding to rebuild implicit
17772   // casts, but not at the top level, so rebuild them here.
17773   case Expr::ImplicitCastExprClass: {
17774     auto *ICE = cast<ImplicitCastExpr>(E);
17775     // Only step through the narrow set of cast kinds we expect to encounter.
17776     // Anything else suggests we've left the region in which potential results
17777     // can be found.
17778     switch (ICE->getCastKind()) {
17779     case CK_NoOp:
17780     case CK_DerivedToBase:
17781     case CK_UncheckedDerivedToBase: {
17782       ExprResult Sub = Rebuild(ICE->getSubExpr());
17783       if (!Sub.isUsable())
17784         return Sub;
17785       CXXCastPath Path(ICE->path());
17786       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17787                                  ICE->getValueKind(), &Path);
17788     }
17789 
17790     default:
17791       break;
17792     }
17793     break;
17794   }
17795 
17796   default:
17797     break;
17798   }
17799 
17800   // Can't traverse through this node. Nothing to do.
17801   return ExprEmpty();
17802 }
17803 
17804 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17805   // Check whether the operand is or contains an object of non-trivial C union
17806   // type.
17807   if (E->getType().isVolatileQualified() &&
17808       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17809        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17810     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17811                           Sema::NTCUC_LValueToRValueVolatile,
17812                           NTCUK_Destruct|NTCUK_Copy);
17813 
17814   // C++2a [basic.def.odr]p4:
17815   //   [...] an expression of non-volatile-qualified non-class type to which
17816   //   the lvalue-to-rvalue conversion is applied [...]
17817   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17818     return E;
17819 
17820   ExprResult Result =
17821       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17822   if (Result.isInvalid())
17823     return ExprError();
17824   return Result.get() ? Result : E;
17825 }
17826 
17827 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17828   Res = CorrectDelayedTyposInExpr(Res);
17829 
17830   if (!Res.isUsable())
17831     return Res;
17832 
17833   // If a constant-expression is a reference to a variable where we delay
17834   // deciding whether it is an odr-use, just assume we will apply the
17835   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17836   // (a non-type template argument), we have special handling anyway.
17837   return CheckLValueToRValueConversionOperand(Res.get());
17838 }
17839 
17840 void Sema::CleanupVarDeclMarking() {
17841   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17842   // call.
17843   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17844   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17845 
17846   for (Expr *E : LocalMaybeODRUseExprs) {
17847     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17848       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17849                          DRE->getLocation(), *this);
17850     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17851       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17852                          *this);
17853     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17854       for (VarDecl *VD : *FP)
17855         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17856     } else {
17857       llvm_unreachable("Unexpected expression");
17858     }
17859   }
17860 
17861   assert(MaybeODRUseExprs.empty() &&
17862          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17863 }
17864 
17865 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17866                                     VarDecl *Var, Expr *E) {
17867   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17868           isa<FunctionParmPackExpr>(E)) &&
17869          "Invalid Expr argument to DoMarkVarDeclReferenced");
17870   Var->setReferenced();
17871 
17872   if (Var->isInvalidDecl())
17873     return;
17874 
17875   auto *MSI = Var->getMemberSpecializationInfo();
17876   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17877                                        : Var->getTemplateSpecializationKind();
17878 
17879   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17880   bool UsableInConstantExpr =
17881       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17882 
17883   // C++20 [expr.const]p12:
17884   //   A variable [...] is needed for constant evaluation if it is [...] a
17885   //   variable whose name appears as a potentially constant evaluated
17886   //   expression that is either a contexpr variable or is of non-volatile
17887   //   const-qualified integral type or of reference type
17888   bool NeededForConstantEvaluation =
17889       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17890 
17891   bool NeedDefinition =
17892       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17893 
17894   VarTemplateSpecializationDecl *VarSpec =
17895       dyn_cast<VarTemplateSpecializationDecl>(Var);
17896   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17897          "Can't instantiate a partial template specialization.");
17898 
17899   // If this might be a member specialization of a static data member, check
17900   // the specialization is visible. We already did the checks for variable
17901   // template specializations when we created them.
17902   if (NeedDefinition && TSK != TSK_Undeclared &&
17903       !isa<VarTemplateSpecializationDecl>(Var))
17904     SemaRef.checkSpecializationVisibility(Loc, Var);
17905 
17906   // Perform implicit instantiation of static data members, static data member
17907   // templates of class templates, and variable template specializations. Delay
17908   // instantiations of variable templates, except for those that could be used
17909   // in a constant expression.
17910   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17911     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17912     // instantiation declaration if a variable is usable in a constant
17913     // expression (among other cases).
17914     bool TryInstantiating =
17915         TSK == TSK_ImplicitInstantiation ||
17916         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17917 
17918     if (TryInstantiating) {
17919       SourceLocation PointOfInstantiation =
17920           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17921       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17922       if (FirstInstantiation) {
17923         PointOfInstantiation = Loc;
17924         if (MSI)
17925           MSI->setPointOfInstantiation(PointOfInstantiation);
17926         else
17927           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17928       }
17929 
17930       bool InstantiationDependent = false;
17931       bool IsNonDependent =
17932           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17933                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17934                   : true;
17935 
17936       // Do not instantiate specializations that are still type-dependent.
17937       if (IsNonDependent) {
17938         if (UsableInConstantExpr) {
17939           // Do not defer instantiations of variables that could be used in a
17940           // constant expression.
17941           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17942             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17943           });
17944         } else if (FirstInstantiation ||
17945                    isa<VarTemplateSpecializationDecl>(Var)) {
17946           // FIXME: For a specialization of a variable template, we don't
17947           // distinguish between "declaration and type implicitly instantiated"
17948           // and "implicit instantiation of definition requested", so we have
17949           // no direct way to avoid enqueueing the pending instantiation
17950           // multiple times.
17951           SemaRef.PendingInstantiations
17952               .push_back(std::make_pair(Var, PointOfInstantiation));
17953         }
17954       }
17955     }
17956   }
17957 
17958   // C++2a [basic.def.odr]p4:
17959   //   A variable x whose name appears as a potentially-evaluated expression e
17960   //   is odr-used by e unless
17961   //   -- x is a reference that is usable in constant expressions
17962   //   -- x is a variable of non-reference type that is usable in constant
17963   //      expressions and has no mutable subobjects [FIXME], and e is an
17964   //      element of the set of potential results of an expression of
17965   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17966   //      conversion is applied
17967   //   -- x is a variable of non-reference type, and e is an element of the set
17968   //      of potential results of a discarded-value expression to which the
17969   //      lvalue-to-rvalue conversion is not applied [FIXME]
17970   //
17971   // We check the first part of the second bullet here, and
17972   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17973   // FIXME: To get the third bullet right, we need to delay this even for
17974   // variables that are not usable in constant expressions.
17975 
17976   // If we already know this isn't an odr-use, there's nothing more to do.
17977   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17978     if (DRE->isNonOdrUse())
17979       return;
17980   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17981     if (ME->isNonOdrUse())
17982       return;
17983 
17984   switch (OdrUse) {
17985   case OdrUseContext::None:
17986     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17987            "missing non-odr-use marking for unevaluated decl ref");
17988     break;
17989 
17990   case OdrUseContext::FormallyOdrUsed:
17991     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17992     // behavior.
17993     break;
17994 
17995   case OdrUseContext::Used:
17996     // If we might later find that this expression isn't actually an odr-use,
17997     // delay the marking.
17998     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17999       SemaRef.MaybeODRUseExprs.insert(E);
18000     else
18001       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18002     break;
18003 
18004   case OdrUseContext::Dependent:
18005     // If this is a dependent context, we don't need to mark variables as
18006     // odr-used, but we may still need to track them for lambda capture.
18007     // FIXME: Do we also need to do this inside dependent typeid expressions
18008     // (which are modeled as unevaluated at this point)?
18009     const bool RefersToEnclosingScope =
18010         (SemaRef.CurContext != Var->getDeclContext() &&
18011          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18012     if (RefersToEnclosingScope) {
18013       LambdaScopeInfo *const LSI =
18014           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18015       if (LSI && (!LSI->CallOperator ||
18016                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18017         // If a variable could potentially be odr-used, defer marking it so
18018         // until we finish analyzing the full expression for any
18019         // lvalue-to-rvalue
18020         // or discarded value conversions that would obviate odr-use.
18021         // Add it to the list of potential captures that will be analyzed
18022         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18023         // unless the variable is a reference that was initialized by a constant
18024         // expression (this will never need to be captured or odr-used).
18025         //
18026         // FIXME: We can simplify this a lot after implementing P0588R1.
18027         assert(E && "Capture variable should be used in an expression.");
18028         if (!Var->getType()->isReferenceType() ||
18029             !Var->isUsableInConstantExpressions(SemaRef.Context))
18030           LSI->addPotentialCapture(E->IgnoreParens());
18031       }
18032     }
18033     break;
18034   }
18035 }
18036 
18037 /// Mark a variable referenced, and check whether it is odr-used
18038 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18039 /// used directly for normal expressions referring to VarDecl.
18040 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18041   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18042 }
18043 
18044 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18045                                Decl *D, Expr *E, bool MightBeOdrUse) {
18046   if (SemaRef.isInOpenMPDeclareTargetContext())
18047     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18048 
18049   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18050     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18051     return;
18052   }
18053 
18054   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18055 
18056   // If this is a call to a method via a cast, also mark the method in the
18057   // derived class used in case codegen can devirtualize the call.
18058   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18059   if (!ME)
18060     return;
18061   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18062   if (!MD)
18063     return;
18064   // Only attempt to devirtualize if this is truly a virtual call.
18065   bool IsVirtualCall = MD->isVirtual() &&
18066                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18067   if (!IsVirtualCall)
18068     return;
18069 
18070   // If it's possible to devirtualize the call, mark the called function
18071   // referenced.
18072   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18073       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18074   if (DM)
18075     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18076 }
18077 
18078 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18079 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18080   // TODO: update this with DR# once a defect report is filed.
18081   // C++11 defect. The address of a pure member should not be an ODR use, even
18082   // if it's a qualified reference.
18083   bool OdrUse = true;
18084   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18085     if (Method->isVirtual() &&
18086         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18087       OdrUse = false;
18088 
18089   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18090     if (!isConstantEvaluated() && FD->isConsteval() &&
18091         !RebuildingImmediateInvocation)
18092       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18093   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18094 }
18095 
18096 /// Perform reference-marking and odr-use handling for a MemberExpr.
18097 void Sema::MarkMemberReferenced(MemberExpr *E) {
18098   // C++11 [basic.def.odr]p2:
18099   //   A non-overloaded function whose name appears as a potentially-evaluated
18100   //   expression or a member of a set of candidate functions, if selected by
18101   //   overload resolution when referred to from a potentially-evaluated
18102   //   expression, is odr-used, unless it is a pure virtual function and its
18103   //   name is not explicitly qualified.
18104   bool MightBeOdrUse = true;
18105   if (E->performsVirtualDispatch(getLangOpts())) {
18106     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18107       if (Method->isPure())
18108         MightBeOdrUse = false;
18109   }
18110   SourceLocation Loc =
18111       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18112   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18113 }
18114 
18115 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18116 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18117   for (VarDecl *VD : *E)
18118     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18119 }
18120 
18121 /// Perform marking for a reference to an arbitrary declaration.  It
18122 /// marks the declaration referenced, and performs odr-use checking for
18123 /// functions and variables. This method should not be used when building a
18124 /// normal expression which refers to a variable.
18125 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18126                                  bool MightBeOdrUse) {
18127   if (MightBeOdrUse) {
18128     if (auto *VD = dyn_cast<VarDecl>(D)) {
18129       MarkVariableReferenced(Loc, VD);
18130       return;
18131     }
18132   }
18133   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18134     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18135     return;
18136   }
18137   D->setReferenced();
18138 }
18139 
18140 namespace {
18141   // Mark all of the declarations used by a type as referenced.
18142   // FIXME: Not fully implemented yet! We need to have a better understanding
18143   // of when we're entering a context we should not recurse into.
18144   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18145   // TreeTransforms rebuilding the type in a new context. Rather than
18146   // duplicating the TreeTransform logic, we should consider reusing it here.
18147   // Currently that causes problems when rebuilding LambdaExprs.
18148   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18149     Sema &S;
18150     SourceLocation Loc;
18151 
18152   public:
18153     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18154 
18155     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18156 
18157     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18158   };
18159 }
18160 
18161 bool MarkReferencedDecls::TraverseTemplateArgument(
18162     const TemplateArgument &Arg) {
18163   {
18164     // A non-type template argument is a constant-evaluated context.
18165     EnterExpressionEvaluationContext Evaluated(
18166         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18167     if (Arg.getKind() == TemplateArgument::Declaration) {
18168       if (Decl *D = Arg.getAsDecl())
18169         S.MarkAnyDeclReferenced(Loc, D, true);
18170     } else if (Arg.getKind() == TemplateArgument::Expression) {
18171       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18172     }
18173   }
18174 
18175   return Inherited::TraverseTemplateArgument(Arg);
18176 }
18177 
18178 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18179   MarkReferencedDecls Marker(*this, Loc);
18180   Marker.TraverseType(T);
18181 }
18182 
18183 namespace {
18184 /// Helper class that marks all of the declarations referenced by
18185 /// potentially-evaluated subexpressions as "referenced".
18186 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18187 public:
18188   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18189   bool SkipLocalVariables;
18190 
18191   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18192       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18193 
18194   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18195     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18196   }
18197 
18198   void VisitDeclRefExpr(DeclRefExpr *E) {
18199     // If we were asked not to visit local variables, don't.
18200     if (SkipLocalVariables) {
18201       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18202         if (VD->hasLocalStorage())
18203           return;
18204     }
18205     S.MarkDeclRefReferenced(E);
18206   }
18207 
18208   void VisitMemberExpr(MemberExpr *E) {
18209     S.MarkMemberReferenced(E);
18210     Visit(E->getBase());
18211   }
18212 };
18213 } // namespace
18214 
18215 /// Mark any declarations that appear within this expression or any
18216 /// potentially-evaluated subexpressions as "referenced".
18217 ///
18218 /// \param SkipLocalVariables If true, don't mark local variables as
18219 /// 'referenced'.
18220 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18221                                             bool SkipLocalVariables) {
18222   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18223 }
18224 
18225 /// Emit a diagnostic that describes an effect on the run-time behavior
18226 /// of the program being compiled.
18227 ///
18228 /// This routine emits the given diagnostic when the code currently being
18229 /// type-checked is "potentially evaluated", meaning that there is a
18230 /// possibility that the code will actually be executable. Code in sizeof()
18231 /// expressions, code used only during overload resolution, etc., are not
18232 /// potentially evaluated. This routine will suppress such diagnostics or,
18233 /// in the absolutely nutty case of potentially potentially evaluated
18234 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18235 /// later.
18236 ///
18237 /// This routine should be used for all diagnostics that describe the run-time
18238 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18239 /// Failure to do so will likely result in spurious diagnostics or failures
18240 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18241 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18242                                const PartialDiagnostic &PD) {
18243   switch (ExprEvalContexts.back().Context) {
18244   case ExpressionEvaluationContext::Unevaluated:
18245   case ExpressionEvaluationContext::UnevaluatedList:
18246   case ExpressionEvaluationContext::UnevaluatedAbstract:
18247   case ExpressionEvaluationContext::DiscardedStatement:
18248     // The argument will never be evaluated, so don't complain.
18249     break;
18250 
18251   case ExpressionEvaluationContext::ConstantEvaluated:
18252     // Relevant diagnostics should be produced by constant evaluation.
18253     break;
18254 
18255   case ExpressionEvaluationContext::PotentiallyEvaluated:
18256   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18257     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18258       FunctionScopes.back()->PossiblyUnreachableDiags.
18259         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18260       return true;
18261     }
18262 
18263     // The initializer of a constexpr variable or of the first declaration of a
18264     // static data member is not syntactically a constant evaluated constant,
18265     // but nonetheless is always required to be a constant expression, so we
18266     // can skip diagnosing.
18267     // FIXME: Using the mangling context here is a hack.
18268     if (auto *VD = dyn_cast_or_null<VarDecl>(
18269             ExprEvalContexts.back().ManglingContextDecl)) {
18270       if (VD->isConstexpr() ||
18271           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18272         break;
18273       // FIXME: For any other kind of variable, we should build a CFG for its
18274       // initializer and check whether the context in question is reachable.
18275     }
18276 
18277     Diag(Loc, PD);
18278     return true;
18279   }
18280 
18281   return false;
18282 }
18283 
18284 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18285                                const PartialDiagnostic &PD) {
18286   return DiagRuntimeBehavior(
18287       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18288 }
18289 
18290 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18291                                CallExpr *CE, FunctionDecl *FD) {
18292   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18293     return false;
18294 
18295   // If we're inside a decltype's expression, don't check for a valid return
18296   // type or construct temporaries until we know whether this is the last call.
18297   if (ExprEvalContexts.back().ExprContext ==
18298       ExpressionEvaluationContextRecord::EK_Decltype) {
18299     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18300     return false;
18301   }
18302 
18303   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18304     FunctionDecl *FD;
18305     CallExpr *CE;
18306 
18307   public:
18308     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18309       : FD(FD), CE(CE) { }
18310 
18311     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18312       if (!FD) {
18313         S.Diag(Loc, diag::err_call_incomplete_return)
18314           << T << CE->getSourceRange();
18315         return;
18316       }
18317 
18318       S.Diag(Loc, diag::err_call_function_incomplete_return)
18319         << CE->getSourceRange() << FD->getDeclName() << T;
18320       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18321           << FD->getDeclName();
18322     }
18323   } Diagnoser(FD, CE);
18324 
18325   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18326     return true;
18327 
18328   return false;
18329 }
18330 
18331 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18332 // will prevent this condition from triggering, which is what we want.
18333 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18334   SourceLocation Loc;
18335 
18336   unsigned diagnostic = diag::warn_condition_is_assignment;
18337   bool IsOrAssign = false;
18338 
18339   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18340     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18341       return;
18342 
18343     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18344 
18345     // Greylist some idioms by putting them into a warning subcategory.
18346     if (ObjCMessageExpr *ME
18347           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18348       Selector Sel = ME->getSelector();
18349 
18350       // self = [<foo> init...]
18351       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18352         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18353 
18354       // <foo> = [<bar> nextObject]
18355       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18356         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18357     }
18358 
18359     Loc = Op->getOperatorLoc();
18360   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18361     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18362       return;
18363 
18364     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18365     Loc = Op->getOperatorLoc();
18366   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18367     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18368   else {
18369     // Not an assignment.
18370     return;
18371   }
18372 
18373   Diag(Loc, diagnostic) << E->getSourceRange();
18374 
18375   SourceLocation Open = E->getBeginLoc();
18376   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18377   Diag(Loc, diag::note_condition_assign_silence)
18378         << FixItHint::CreateInsertion(Open, "(")
18379         << FixItHint::CreateInsertion(Close, ")");
18380 
18381   if (IsOrAssign)
18382     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18383       << FixItHint::CreateReplacement(Loc, "!=");
18384   else
18385     Diag(Loc, diag::note_condition_assign_to_comparison)
18386       << FixItHint::CreateReplacement(Loc, "==");
18387 }
18388 
18389 /// Redundant parentheses over an equality comparison can indicate
18390 /// that the user intended an assignment used as condition.
18391 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18392   // Don't warn if the parens came from a macro.
18393   SourceLocation parenLoc = ParenE->getBeginLoc();
18394   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18395     return;
18396   // Don't warn for dependent expressions.
18397   if (ParenE->isTypeDependent())
18398     return;
18399 
18400   Expr *E = ParenE->IgnoreParens();
18401 
18402   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18403     if (opE->getOpcode() == BO_EQ &&
18404         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18405                                                            == Expr::MLV_Valid) {
18406       SourceLocation Loc = opE->getOperatorLoc();
18407 
18408       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18409       SourceRange ParenERange = ParenE->getSourceRange();
18410       Diag(Loc, diag::note_equality_comparison_silence)
18411         << FixItHint::CreateRemoval(ParenERange.getBegin())
18412         << FixItHint::CreateRemoval(ParenERange.getEnd());
18413       Diag(Loc, diag::note_equality_comparison_to_assign)
18414         << FixItHint::CreateReplacement(Loc, "=");
18415     }
18416 }
18417 
18418 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18419                                        bool IsConstexpr) {
18420   DiagnoseAssignmentAsCondition(E);
18421   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18422     DiagnoseEqualityWithExtraParens(parenE);
18423 
18424   ExprResult result = CheckPlaceholderExpr(E);
18425   if (result.isInvalid()) return ExprError();
18426   E = result.get();
18427 
18428   if (!E->isTypeDependent()) {
18429     if (getLangOpts().CPlusPlus)
18430       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18431 
18432     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18433     if (ERes.isInvalid())
18434       return ExprError();
18435     E = ERes.get();
18436 
18437     QualType T = E->getType();
18438     if (!T->isScalarType()) { // C99 6.8.4.1p1
18439       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18440         << T << E->getSourceRange();
18441       return ExprError();
18442     }
18443     CheckBoolLikeConversion(E, Loc);
18444   }
18445 
18446   return E;
18447 }
18448 
18449 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18450                                            Expr *SubExpr, ConditionKind CK) {
18451   // Empty conditions are valid in for-statements.
18452   if (!SubExpr)
18453     return ConditionResult();
18454 
18455   ExprResult Cond;
18456   switch (CK) {
18457   case ConditionKind::Boolean:
18458     Cond = CheckBooleanCondition(Loc, SubExpr);
18459     break;
18460 
18461   case ConditionKind::ConstexprIf:
18462     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18463     break;
18464 
18465   case ConditionKind::Switch:
18466     Cond = CheckSwitchCondition(Loc, SubExpr);
18467     break;
18468   }
18469   if (Cond.isInvalid())
18470     return ConditionError();
18471 
18472   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18473   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18474   if (!FullExpr.get())
18475     return ConditionError();
18476 
18477   return ConditionResult(*this, nullptr, FullExpr,
18478                          CK == ConditionKind::ConstexprIf);
18479 }
18480 
18481 namespace {
18482   /// A visitor for rebuilding a call to an __unknown_any expression
18483   /// to have an appropriate type.
18484   struct RebuildUnknownAnyFunction
18485     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18486 
18487     Sema &S;
18488 
18489     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18490 
18491     ExprResult VisitStmt(Stmt *S) {
18492       llvm_unreachable("unexpected statement!");
18493     }
18494 
18495     ExprResult VisitExpr(Expr *E) {
18496       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18497         << E->getSourceRange();
18498       return ExprError();
18499     }
18500 
18501     /// Rebuild an expression which simply semantically wraps another
18502     /// expression which it shares the type and value kind of.
18503     template <class T> ExprResult rebuildSugarExpr(T *E) {
18504       ExprResult SubResult = Visit(E->getSubExpr());
18505       if (SubResult.isInvalid()) return ExprError();
18506 
18507       Expr *SubExpr = SubResult.get();
18508       E->setSubExpr(SubExpr);
18509       E->setType(SubExpr->getType());
18510       E->setValueKind(SubExpr->getValueKind());
18511       assert(E->getObjectKind() == OK_Ordinary);
18512       return E;
18513     }
18514 
18515     ExprResult VisitParenExpr(ParenExpr *E) {
18516       return rebuildSugarExpr(E);
18517     }
18518 
18519     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18520       return rebuildSugarExpr(E);
18521     }
18522 
18523     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18524       ExprResult SubResult = Visit(E->getSubExpr());
18525       if (SubResult.isInvalid()) return ExprError();
18526 
18527       Expr *SubExpr = SubResult.get();
18528       E->setSubExpr(SubExpr);
18529       E->setType(S.Context.getPointerType(SubExpr->getType()));
18530       assert(E->getValueKind() == VK_RValue);
18531       assert(E->getObjectKind() == OK_Ordinary);
18532       return E;
18533     }
18534 
18535     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18536       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18537 
18538       E->setType(VD->getType());
18539 
18540       assert(E->getValueKind() == VK_RValue);
18541       if (S.getLangOpts().CPlusPlus &&
18542           !(isa<CXXMethodDecl>(VD) &&
18543             cast<CXXMethodDecl>(VD)->isInstance()))
18544         E->setValueKind(VK_LValue);
18545 
18546       return E;
18547     }
18548 
18549     ExprResult VisitMemberExpr(MemberExpr *E) {
18550       return resolveDecl(E, E->getMemberDecl());
18551     }
18552 
18553     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18554       return resolveDecl(E, E->getDecl());
18555     }
18556   };
18557 }
18558 
18559 /// Given a function expression of unknown-any type, try to rebuild it
18560 /// to have a function type.
18561 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18562   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18563   if (Result.isInvalid()) return ExprError();
18564   return S.DefaultFunctionArrayConversion(Result.get());
18565 }
18566 
18567 namespace {
18568   /// A visitor for rebuilding an expression of type __unknown_anytype
18569   /// into one which resolves the type directly on the referring
18570   /// expression.  Strict preservation of the original source
18571   /// structure is not a goal.
18572   struct RebuildUnknownAnyExpr
18573     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18574 
18575     Sema &S;
18576 
18577     /// The current destination type.
18578     QualType DestType;
18579 
18580     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18581       : S(S), DestType(CastType) {}
18582 
18583     ExprResult VisitStmt(Stmt *S) {
18584       llvm_unreachable("unexpected statement!");
18585     }
18586 
18587     ExprResult VisitExpr(Expr *E) {
18588       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18589         << E->getSourceRange();
18590       return ExprError();
18591     }
18592 
18593     ExprResult VisitCallExpr(CallExpr *E);
18594     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18595 
18596     /// Rebuild an expression which simply semantically wraps another
18597     /// expression which it shares the type and value kind of.
18598     template <class T> ExprResult rebuildSugarExpr(T *E) {
18599       ExprResult SubResult = Visit(E->getSubExpr());
18600       if (SubResult.isInvalid()) return ExprError();
18601       Expr *SubExpr = SubResult.get();
18602       E->setSubExpr(SubExpr);
18603       E->setType(SubExpr->getType());
18604       E->setValueKind(SubExpr->getValueKind());
18605       assert(E->getObjectKind() == OK_Ordinary);
18606       return E;
18607     }
18608 
18609     ExprResult VisitParenExpr(ParenExpr *E) {
18610       return rebuildSugarExpr(E);
18611     }
18612 
18613     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18614       return rebuildSugarExpr(E);
18615     }
18616 
18617     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18618       const PointerType *Ptr = DestType->getAs<PointerType>();
18619       if (!Ptr) {
18620         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18621           << E->getSourceRange();
18622         return ExprError();
18623       }
18624 
18625       if (isa<CallExpr>(E->getSubExpr())) {
18626         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18627           << E->getSourceRange();
18628         return ExprError();
18629       }
18630 
18631       assert(E->getValueKind() == VK_RValue);
18632       assert(E->getObjectKind() == OK_Ordinary);
18633       E->setType(DestType);
18634 
18635       // Build the sub-expression as if it were an object of the pointee type.
18636       DestType = Ptr->getPointeeType();
18637       ExprResult SubResult = Visit(E->getSubExpr());
18638       if (SubResult.isInvalid()) return ExprError();
18639       E->setSubExpr(SubResult.get());
18640       return E;
18641     }
18642 
18643     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18644 
18645     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18646 
18647     ExprResult VisitMemberExpr(MemberExpr *E) {
18648       return resolveDecl(E, E->getMemberDecl());
18649     }
18650 
18651     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18652       return resolveDecl(E, E->getDecl());
18653     }
18654   };
18655 }
18656 
18657 /// Rebuilds a call expression which yielded __unknown_anytype.
18658 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18659   Expr *CalleeExpr = E->getCallee();
18660 
18661   enum FnKind {
18662     FK_MemberFunction,
18663     FK_FunctionPointer,
18664     FK_BlockPointer
18665   };
18666 
18667   FnKind Kind;
18668   QualType CalleeType = CalleeExpr->getType();
18669   if (CalleeType == S.Context.BoundMemberTy) {
18670     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18671     Kind = FK_MemberFunction;
18672     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18673   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18674     CalleeType = Ptr->getPointeeType();
18675     Kind = FK_FunctionPointer;
18676   } else {
18677     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18678     Kind = FK_BlockPointer;
18679   }
18680   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18681 
18682   // Verify that this is a legal result type of a function.
18683   if (DestType->isArrayType() || DestType->isFunctionType()) {
18684     unsigned diagID = diag::err_func_returning_array_function;
18685     if (Kind == FK_BlockPointer)
18686       diagID = diag::err_block_returning_array_function;
18687 
18688     S.Diag(E->getExprLoc(), diagID)
18689       << DestType->isFunctionType() << DestType;
18690     return ExprError();
18691   }
18692 
18693   // Otherwise, go ahead and set DestType as the call's result.
18694   E->setType(DestType.getNonLValueExprType(S.Context));
18695   E->setValueKind(Expr::getValueKindForType(DestType));
18696   assert(E->getObjectKind() == OK_Ordinary);
18697 
18698   // Rebuild the function type, replacing the result type with DestType.
18699   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18700   if (Proto) {
18701     // __unknown_anytype(...) is a special case used by the debugger when
18702     // it has no idea what a function's signature is.
18703     //
18704     // We want to build this call essentially under the K&R
18705     // unprototyped rules, but making a FunctionNoProtoType in C++
18706     // would foul up all sorts of assumptions.  However, we cannot
18707     // simply pass all arguments as variadic arguments, nor can we
18708     // portably just call the function under a non-variadic type; see
18709     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18710     // However, it turns out that in practice it is generally safe to
18711     // call a function declared as "A foo(B,C,D);" under the prototype
18712     // "A foo(B,C,D,...);".  The only known exception is with the
18713     // Windows ABI, where any variadic function is implicitly cdecl
18714     // regardless of its normal CC.  Therefore we change the parameter
18715     // types to match the types of the arguments.
18716     //
18717     // This is a hack, but it is far superior to moving the
18718     // corresponding target-specific code from IR-gen to Sema/AST.
18719 
18720     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18721     SmallVector<QualType, 8> ArgTypes;
18722     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18723       ArgTypes.reserve(E->getNumArgs());
18724       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18725         Expr *Arg = E->getArg(i);
18726         QualType ArgType = Arg->getType();
18727         if (E->isLValue()) {
18728           ArgType = S.Context.getLValueReferenceType(ArgType);
18729         } else if (E->isXValue()) {
18730           ArgType = S.Context.getRValueReferenceType(ArgType);
18731         }
18732         ArgTypes.push_back(ArgType);
18733       }
18734       ParamTypes = ArgTypes;
18735     }
18736     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18737                                          Proto->getExtProtoInfo());
18738   } else {
18739     DestType = S.Context.getFunctionNoProtoType(DestType,
18740                                                 FnType->getExtInfo());
18741   }
18742 
18743   // Rebuild the appropriate pointer-to-function type.
18744   switch (Kind) {
18745   case FK_MemberFunction:
18746     // Nothing to do.
18747     break;
18748 
18749   case FK_FunctionPointer:
18750     DestType = S.Context.getPointerType(DestType);
18751     break;
18752 
18753   case FK_BlockPointer:
18754     DestType = S.Context.getBlockPointerType(DestType);
18755     break;
18756   }
18757 
18758   // Finally, we can recurse.
18759   ExprResult CalleeResult = Visit(CalleeExpr);
18760   if (!CalleeResult.isUsable()) return ExprError();
18761   E->setCallee(CalleeResult.get());
18762 
18763   // Bind a temporary if necessary.
18764   return S.MaybeBindToTemporary(E);
18765 }
18766 
18767 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18768   // Verify that this is a legal result type of a call.
18769   if (DestType->isArrayType() || DestType->isFunctionType()) {
18770     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18771       << DestType->isFunctionType() << DestType;
18772     return ExprError();
18773   }
18774 
18775   // Rewrite the method result type if available.
18776   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18777     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18778     Method->setReturnType(DestType);
18779   }
18780 
18781   // Change the type of the message.
18782   E->setType(DestType.getNonReferenceType());
18783   E->setValueKind(Expr::getValueKindForType(DestType));
18784 
18785   return S.MaybeBindToTemporary(E);
18786 }
18787 
18788 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18789   // The only case we should ever see here is a function-to-pointer decay.
18790   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18791     assert(E->getValueKind() == VK_RValue);
18792     assert(E->getObjectKind() == OK_Ordinary);
18793 
18794     E->setType(DestType);
18795 
18796     // Rebuild the sub-expression as the pointee (function) type.
18797     DestType = DestType->castAs<PointerType>()->getPointeeType();
18798 
18799     ExprResult Result = Visit(E->getSubExpr());
18800     if (!Result.isUsable()) return ExprError();
18801 
18802     E->setSubExpr(Result.get());
18803     return E;
18804   } else if (E->getCastKind() == CK_LValueToRValue) {
18805     assert(E->getValueKind() == VK_RValue);
18806     assert(E->getObjectKind() == OK_Ordinary);
18807 
18808     assert(isa<BlockPointerType>(E->getType()));
18809 
18810     E->setType(DestType);
18811 
18812     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18813     DestType = S.Context.getLValueReferenceType(DestType);
18814 
18815     ExprResult Result = Visit(E->getSubExpr());
18816     if (!Result.isUsable()) return ExprError();
18817 
18818     E->setSubExpr(Result.get());
18819     return E;
18820   } else {
18821     llvm_unreachable("Unhandled cast type!");
18822   }
18823 }
18824 
18825 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18826   ExprValueKind ValueKind = VK_LValue;
18827   QualType Type = DestType;
18828 
18829   // We know how to make this work for certain kinds of decls:
18830 
18831   //  - functions
18832   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18833     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18834       DestType = Ptr->getPointeeType();
18835       ExprResult Result = resolveDecl(E, VD);
18836       if (Result.isInvalid()) return ExprError();
18837       return S.ImpCastExprToType(Result.get(), Type,
18838                                  CK_FunctionToPointerDecay, VK_RValue);
18839     }
18840 
18841     if (!Type->isFunctionType()) {
18842       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18843         << VD << E->getSourceRange();
18844       return ExprError();
18845     }
18846     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18847       // We must match the FunctionDecl's type to the hack introduced in
18848       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18849       // type. See the lengthy commentary in that routine.
18850       QualType FDT = FD->getType();
18851       const FunctionType *FnType = FDT->castAs<FunctionType>();
18852       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18853       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18854       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18855         SourceLocation Loc = FD->getLocation();
18856         FunctionDecl *NewFD = FunctionDecl::Create(
18857             S.Context, FD->getDeclContext(), Loc, Loc,
18858             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18859             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18860             /*ConstexprKind*/ CSK_unspecified);
18861 
18862         if (FD->getQualifier())
18863           NewFD->setQualifierInfo(FD->getQualifierLoc());
18864 
18865         SmallVector<ParmVarDecl*, 16> Params;
18866         for (const auto &AI : FT->param_types()) {
18867           ParmVarDecl *Param =
18868             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18869           Param->setScopeInfo(0, Params.size());
18870           Params.push_back(Param);
18871         }
18872         NewFD->setParams(Params);
18873         DRE->setDecl(NewFD);
18874         VD = DRE->getDecl();
18875       }
18876     }
18877 
18878     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18879       if (MD->isInstance()) {
18880         ValueKind = VK_RValue;
18881         Type = S.Context.BoundMemberTy;
18882       }
18883 
18884     // Function references aren't l-values in C.
18885     if (!S.getLangOpts().CPlusPlus)
18886       ValueKind = VK_RValue;
18887 
18888   //  - variables
18889   } else if (isa<VarDecl>(VD)) {
18890     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18891       Type = RefTy->getPointeeType();
18892     } else if (Type->isFunctionType()) {
18893       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18894         << VD << E->getSourceRange();
18895       return ExprError();
18896     }
18897 
18898   //  - nothing else
18899   } else {
18900     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18901       << VD << E->getSourceRange();
18902     return ExprError();
18903   }
18904 
18905   // Modifying the declaration like this is friendly to IR-gen but
18906   // also really dangerous.
18907   VD->setType(DestType);
18908   E->setType(Type);
18909   E->setValueKind(ValueKind);
18910   return E;
18911 }
18912 
18913 /// Check a cast of an unknown-any type.  We intentionally only
18914 /// trigger this for C-style casts.
18915 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18916                                      Expr *CastExpr, CastKind &CastKind,
18917                                      ExprValueKind &VK, CXXCastPath &Path) {
18918   // The type we're casting to must be either void or complete.
18919   if (!CastType->isVoidType() &&
18920       RequireCompleteType(TypeRange.getBegin(), CastType,
18921                           diag::err_typecheck_cast_to_incomplete))
18922     return ExprError();
18923 
18924   // Rewrite the casted expression from scratch.
18925   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18926   if (!result.isUsable()) return ExprError();
18927 
18928   CastExpr = result.get();
18929   VK = CastExpr->getValueKind();
18930   CastKind = CK_NoOp;
18931 
18932   return CastExpr;
18933 }
18934 
18935 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18936   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18937 }
18938 
18939 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18940                                     Expr *arg, QualType &paramType) {
18941   // If the syntactic form of the argument is not an explicit cast of
18942   // any sort, just do default argument promotion.
18943   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18944   if (!castArg) {
18945     ExprResult result = DefaultArgumentPromotion(arg);
18946     if (result.isInvalid()) return ExprError();
18947     paramType = result.get()->getType();
18948     return result;
18949   }
18950 
18951   // Otherwise, use the type that was written in the explicit cast.
18952   assert(!arg->hasPlaceholderType());
18953   paramType = castArg->getTypeAsWritten();
18954 
18955   // Copy-initialize a parameter of that type.
18956   InitializedEntity entity =
18957     InitializedEntity::InitializeParameter(Context, paramType,
18958                                            /*consumed*/ false);
18959   return PerformCopyInitialization(entity, callLoc, arg);
18960 }
18961 
18962 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18963   Expr *orig = E;
18964   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18965   while (true) {
18966     E = E->IgnoreParenImpCasts();
18967     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18968       E = call->getCallee();
18969       diagID = diag::err_uncasted_call_of_unknown_any;
18970     } else {
18971       break;
18972     }
18973   }
18974 
18975   SourceLocation loc;
18976   NamedDecl *d;
18977   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18978     loc = ref->getLocation();
18979     d = ref->getDecl();
18980   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18981     loc = mem->getMemberLoc();
18982     d = mem->getMemberDecl();
18983   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18984     diagID = diag::err_uncasted_call_of_unknown_any;
18985     loc = msg->getSelectorStartLoc();
18986     d = msg->getMethodDecl();
18987     if (!d) {
18988       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18989         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18990         << orig->getSourceRange();
18991       return ExprError();
18992     }
18993   } else {
18994     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18995       << E->getSourceRange();
18996     return ExprError();
18997   }
18998 
18999   S.Diag(loc, diagID) << d << orig->getSourceRange();
19000 
19001   // Never recoverable.
19002   return ExprError();
19003 }
19004 
19005 /// Check for operands with placeholder types and complain if found.
19006 /// Returns ExprError() if there was an error and no recovery was possible.
19007 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19008   if (!getLangOpts().CPlusPlus) {
19009     // C cannot handle TypoExpr nodes on either side of a binop because it
19010     // doesn't handle dependent types properly, so make sure any TypoExprs have
19011     // been dealt with before checking the operands.
19012     ExprResult Result = CorrectDelayedTyposInExpr(E);
19013     if (!Result.isUsable()) return ExprError();
19014     E = Result.get();
19015   }
19016 
19017   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19018   if (!placeholderType) return E;
19019 
19020   switch (placeholderType->getKind()) {
19021 
19022   // Overloaded expressions.
19023   case BuiltinType::Overload: {
19024     // Try to resolve a single function template specialization.
19025     // This is obligatory.
19026     ExprResult Result = E;
19027     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19028       return Result;
19029 
19030     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19031     // leaves Result unchanged on failure.
19032     Result = E;
19033     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19034       return Result;
19035 
19036     // If that failed, try to recover with a call.
19037     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19038                          /*complain*/ true);
19039     return Result;
19040   }
19041 
19042   // Bound member functions.
19043   case BuiltinType::BoundMember: {
19044     ExprResult result = E;
19045     const Expr *BME = E->IgnoreParens();
19046     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19047     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19048     if (isa<CXXPseudoDestructorExpr>(BME)) {
19049       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19050     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19051       if (ME->getMemberNameInfo().getName().getNameKind() ==
19052           DeclarationName::CXXDestructorName)
19053         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19054     }
19055     tryToRecoverWithCall(result, PD,
19056                          /*complain*/ true);
19057     return result;
19058   }
19059 
19060   // ARC unbridged casts.
19061   case BuiltinType::ARCUnbridgedCast: {
19062     Expr *realCast = stripARCUnbridgedCast(E);
19063     diagnoseARCUnbridgedCast(realCast);
19064     return realCast;
19065   }
19066 
19067   // Expressions of unknown type.
19068   case BuiltinType::UnknownAny:
19069     return diagnoseUnknownAnyExpr(*this, E);
19070 
19071   // Pseudo-objects.
19072   case BuiltinType::PseudoObject:
19073     return checkPseudoObjectRValue(E);
19074 
19075   case BuiltinType::BuiltinFn: {
19076     // Accept __noop without parens by implicitly converting it to a call expr.
19077     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19078     if (DRE) {
19079       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19080       if (FD->getBuiltinID() == Builtin::BI__noop) {
19081         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19082                               CK_BuiltinFnToFnPtr)
19083                 .get();
19084         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19085                                 VK_RValue, SourceLocation());
19086       }
19087     }
19088 
19089     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19090     return ExprError();
19091   }
19092 
19093   case BuiltinType::IncompleteMatrixIdx:
19094     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19095              ->getRowIdx()
19096              ->getBeginLoc(),
19097          diag::err_matrix_incomplete_index);
19098     return ExprError();
19099 
19100   // Expressions of unknown type.
19101   case BuiltinType::OMPArraySection:
19102     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19103     return ExprError();
19104 
19105   // Expressions of unknown type.
19106   case BuiltinType::OMPArrayShaping:
19107     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19108 
19109   case BuiltinType::OMPIterator:
19110     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19111 
19112   // Everything else should be impossible.
19113 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19114   case BuiltinType::Id:
19115 #include "clang/Basic/OpenCLImageTypes.def"
19116 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19117   case BuiltinType::Id:
19118 #include "clang/Basic/OpenCLExtensionTypes.def"
19119 #define SVE_TYPE(Name, Id, SingletonId) \
19120   case BuiltinType::Id:
19121 #include "clang/Basic/AArch64SVEACLETypes.def"
19122 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19123 #define PLACEHOLDER_TYPE(Id, SingletonId)
19124 #include "clang/AST/BuiltinTypes.def"
19125     break;
19126   }
19127 
19128   llvm_unreachable("invalid placeholder type!");
19129 }
19130 
19131 bool Sema::CheckCaseExpression(Expr *E) {
19132   if (E->isTypeDependent())
19133     return true;
19134   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19135     return E->getType()->isIntegralOrEnumerationType();
19136   return false;
19137 }
19138 
19139 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19140 ExprResult
19141 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19142   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19143          "Unknown Objective-C Boolean value!");
19144   QualType BoolT = Context.ObjCBuiltinBoolTy;
19145   if (!Context.getBOOLDecl()) {
19146     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19147                         Sema::LookupOrdinaryName);
19148     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19149       NamedDecl *ND = Result.getFoundDecl();
19150       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19151         Context.setBOOLDecl(TD);
19152     }
19153   }
19154   if (Context.getBOOLDecl())
19155     BoolT = Context.getBOOLType();
19156   return new (Context)
19157       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19158 }
19159 
19160 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19161     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19162     SourceLocation RParen) {
19163 
19164   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19165 
19166   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19167     return Spec.getPlatform() == Platform;
19168   });
19169 
19170   VersionTuple Version;
19171   if (Spec != AvailSpecs.end())
19172     Version = Spec->getVersion();
19173 
19174   // The use of `@available` in the enclosing function should be analyzed to
19175   // warn when it's used inappropriately (i.e. not if(@available)).
19176   if (getCurFunctionOrMethodDecl())
19177     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19178   else if (getCurBlock() || getCurLambda())
19179     getCurFunction()->HasPotentialAvailabilityViolations = true;
19180 
19181   return new (Context)
19182       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19183 }
19184 
19185 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19186                                     ArrayRef<Expr *> SubExprs, QualType T) {
19187   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
19188   // bogus diagnostics and this trick does not work in C.
19189   // FIXME: use containsErrors() to suppress unwanted diags in C.
19190   if (!Context.getLangOpts().RecoveryAST)
19191     return ExprError();
19192 
19193   if (isSFINAEContext())
19194     return ExprError();
19195 
19196   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19197     // We don't know the concrete type, fallback to dependent type.
19198     T = Context.DependentTy;
19199   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19200 }
19201