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/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 #include "llvm/Support/SaveAndRestore.h"
50 using namespace clang;
51 using namespace sema;
52 using llvm::RoundingMode;
53 
54 /// Determine whether the use of this declaration is valid, without
55 /// emitting diagnostics.
56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
57   // See if this is an auto-typed variable whose initializer we are parsing.
58   if (ParsingInitForAutoVars.count(D))
59     return false;
60 
61   // See if this is a deleted function.
62   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63     if (FD->isDeleted())
64       return false;
65 
66     // If the function has a deduced return type, and we can't deduce it,
67     // then we can't use it either.
68     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
69         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70       return false;
71 
72     // See if this is an aligned allocation/deallocation function that is
73     // unavailable.
74     if (TreatUnavailableAsInvalid &&
75         isUnavailableAlignedAllocationFunction(*FD))
76       return false;
77   }
78 
79   // See if this function is unavailable.
80   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
81       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
82     return false;
83 
84   return true;
85 }
86 
87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
88   // Warn if this is used but marked unused.
89   if (const auto *A = D->getAttr<UnusedAttr>()) {
90     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
91     // should diagnose them.
92     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
93         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
94       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
95       if (DC && !DC->hasAttr<UnusedAttr>())
96         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
97     }
98   }
99 }
100 
101 /// Emit a note explaining that this function is deleted.
102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
103   assert(Decl && Decl->isDeleted());
104 
105   if (Decl->isDefaulted()) {
106     // If the method was explicitly defaulted, point at that declaration.
107     if (!Decl->isImplicit())
108       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109 
110     // Try to diagnose why this special member function was implicitly
111     // deleted. This might fail, if that reason no longer applies.
112     DiagnoseDeletedDefaultedFunction(Decl);
113     return;
114   }
115 
116   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
117   if (Ctor && Ctor->isInheritingConstructor())
118     return NoteDeletedInheritingConstructor(Ctor);
119 
120   Diag(Decl->getLocation(), diag::note_availability_specified_here)
121     << Decl << 1;
122 }
123 
124 /// Determine whether a FunctionDecl was ever declared with an
125 /// explicit storage class.
126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
127   for (auto I : D->redecls()) {
128     if (I->getStorageClass() != SC_None)
129       return true;
130   }
131   return false;
132 }
133 
134 /// Check whether we're in an extern inline function and referring to a
135 /// variable or function with internal linkage (C11 6.7.4p3).
136 ///
137 /// This is only a warning because we used to silently accept this code, but
138 /// in many cases it will not behave correctly. This is not enabled in C++ mode
139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
140 /// and so while there may still be user mistakes, most of the time we can't
141 /// prove that there are errors.
142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
143                                                       const NamedDecl *D,
144                                                       SourceLocation Loc) {
145   // This is disabled under C++; there are too many ways for this to fire in
146   // contexts where the warning is a false positive, or where it is technically
147   // correct but benign.
148   if (S.getLangOpts().CPlusPlus)
149     return;
150 
151   // Check if this is an inlined function or method.
152   FunctionDecl *Current = S.getCurFunctionDecl();
153   if (!Current)
154     return;
155   if (!Current->isInlined())
156     return;
157   if (!Current->isExternallyVisible())
158     return;
159 
160   // Check if the decl has internal linkage.
161   if (D->getFormalLinkage() != InternalLinkage)
162     return;
163 
164   // Downgrade from ExtWarn to Extension if
165   //  (1) the supposedly external inline function is in the main file,
166   //      and probably won't be included anywhere else.
167   //  (2) the thing we're referencing is a pure function.
168   //  (3) the thing we're referencing is another inline function.
169   // This last can give us false negatives, but it's better than warning on
170   // wrappers for simple C library functions.
171   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
172   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
173   if (!DowngradeWarning && UsedFn)
174     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
175 
176   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
177                                : diag::ext_internal_in_extern_inline)
178     << /*IsVar=*/!UsedFn << D;
179 
180   S.MaybeSuggestAddingStaticToDecl(Current);
181 
182   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
183       << D;
184 }
185 
186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
187   const FunctionDecl *First = Cur->getFirstDecl();
188 
189   // Suggest "static" on the function, if possible.
190   if (!hasAnyExplicitStorageClass(First)) {
191     SourceLocation DeclBegin = First->getSourceRange().getBegin();
192     Diag(DeclBegin, diag::note_convert_inline_to_static)
193       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
194   }
195 }
196 
197 /// Determine whether the use of this declaration is valid, and
198 /// emit any corresponding diagnostics.
199 ///
200 /// This routine diagnoses various problems with referencing
201 /// declarations that can occur when using a declaration. For example,
202 /// it might warn if a deprecated or unavailable declaration is being
203 /// used, or produce an error (and return true) if a C++0x deleted
204 /// function is being used.
205 ///
206 /// \returns true if there was an error (this declaration cannot be
207 /// referenced), false otherwise.
208 ///
209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
210                              const ObjCInterfaceDecl *UnknownObjCClass,
211                              bool ObjCPropertyAccess,
212                              bool AvoidPartialAvailabilityChecks,
213                              ObjCInterfaceDecl *ClassReceiver) {
214   SourceLocation Loc = Locs.front();
215   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
216     // If there were any diagnostics suppressed by template argument deduction,
217     // emit them now.
218     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
219     if (Pos != SuppressedDiagnostics.end()) {
220       for (const PartialDiagnosticAt &Suppressed : Pos->second)
221         Diag(Suppressed.first, Suppressed.second);
222 
223       // Clear out the list of suppressed diagnostics, so that we don't emit
224       // them again for this specialization. However, we don't obsolete this
225       // entry from the table, because we want to avoid ever emitting these
226       // diagnostics again.
227       Pos->second.clear();
228     }
229 
230     // C++ [basic.start.main]p3:
231     //   The function 'main' shall not be used within a program.
232     if (cast<FunctionDecl>(D)->isMain())
233       Diag(Loc, diag::ext_main_used);
234 
235     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
236   }
237 
238   // See if this is an auto-typed variable whose initializer we are parsing.
239   if (ParsingInitForAutoVars.count(D)) {
240     if (isa<BindingDecl>(D)) {
241       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
242         << D->getDeclName();
243     } else {
244       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
245         << D->getDeclName() << cast<VarDecl>(D)->getType();
246     }
247     return true;
248   }
249 
250   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
251     // See if this is a deleted function.
252     if (FD->isDeleted()) {
253       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
254       if (Ctor && Ctor->isInheritingConstructor())
255         Diag(Loc, diag::err_deleted_inherited_ctor_use)
256             << Ctor->getParent()
257             << Ctor->getInheritedConstructor().getConstructor()->getParent();
258       else
259         Diag(Loc, diag::err_deleted_function_use);
260       NoteDeletedFunction(FD);
261       return true;
262     }
263 
264     // [expr.prim.id]p4
265     //   A program that refers explicitly or implicitly to a function with a
266     //   trailing requires-clause whose constraint-expression is not satisfied,
267     //   other than to declare it, is ill-formed. [...]
268     //
269     // See if this is a function with constraints that need to be satisfied.
270     // Check this before deducing the return type, as it might instantiate the
271     // definition.
272     if (FD->getTrailingRequiresClause()) {
273       ConstraintSatisfaction Satisfaction;
274       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
275         // A diagnostic will have already been generated (non-constant
276         // constraint expression, for example)
277         return true;
278       if (!Satisfaction.IsSatisfied) {
279         Diag(Loc,
280              diag::err_reference_to_function_with_unsatisfied_constraints)
281             << D;
282         DiagnoseUnsatisfiedConstraint(Satisfaction);
283         return true;
284       }
285     }
286 
287     // If the function has a deduced return type, and we can't deduce it,
288     // then we can't use it either.
289     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
290         DeduceReturnType(FD, Loc))
291       return true;
292 
293     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
294       return true;
295 
296     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
297       return true;
298   }
299 
300   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
301     // Lambdas are only default-constructible or assignable in C++2a onwards.
302     if (MD->getParent()->isLambda() &&
303         ((isa<CXXConstructorDecl>(MD) &&
304           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
305          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
306       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
307         << !isa<CXXConstructorDecl>(MD);
308     }
309   }
310 
311   auto getReferencedObjCProp = [](const NamedDecl *D) ->
312                                       const ObjCPropertyDecl * {
313     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
314       return MD->findPropertyDecl();
315     return nullptr;
316   };
317   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
318     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
319       return true;
320   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
321       return true;
322   }
323 
324   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
325   // Only the variables omp_in and omp_out are allowed in the combiner.
326   // Only the variables omp_priv and omp_orig are allowed in the
327   // initializer-clause.
328   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
329   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
330       isa<VarDecl>(D)) {
331     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
332         << getCurFunction()->HasOMPDeclareReductionCombiner;
333     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
334     return true;
335   }
336 
337   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
338   //  List-items in map clauses on this construct may only refer to the declared
339   //  variable var and entities that could be referenced by a procedure defined
340   //  at the same location
341   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
342       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
343     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
344         << getOpenMPDeclareMapperVarName();
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
350                              AvoidPartialAvailabilityChecks, ClassReceiver);
351 
352   DiagnoseUnusedOfDecl(*this, D, Loc);
353 
354   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
355 
356   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
357     if (const auto *VD = dyn_cast<ValueDecl>(D))
358       checkDeviceDecl(VD, Loc);
359 
360     if (!Context.getTargetInfo().isTLSSupported())
361       if (const auto *VD = dyn_cast<VarDecl>(D))
362         if (VD->getTLSKind() != VarDecl::TLS_None)
363           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
364   }
365 
366   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
367       !isUnevaluatedContext()) {
368     // C++ [expr.prim.req.nested] p3
369     //   A local parameter shall only appear as an unevaluated operand
370     //   (Clause 8) within the constraint-expression.
371     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
372         << D;
373     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
374     return true;
375   }
376 
377   return false;
378 }
379 
380 /// DiagnoseSentinelCalls - This routine checks whether a call or
381 /// message-send is to a declaration with the sentinel attribute, and
382 /// if so, it checks that the requirements of the sentinel are
383 /// satisfied.
384 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
385                                  ArrayRef<Expr *> Args) {
386   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
387   if (!attr)
388     return;
389 
390   // The number of formal parameters of the declaration.
391   unsigned numFormalParams;
392 
393   // The kind of declaration.  This is also an index into a %select in
394   // the diagnostic.
395   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
396 
397   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
398     numFormalParams = MD->param_size();
399     calleeType = CT_Method;
400   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
401     numFormalParams = FD->param_size();
402     calleeType = CT_Function;
403   } else if (isa<VarDecl>(D)) {
404     QualType type = cast<ValueDecl>(D)->getType();
405     const FunctionType *fn = nullptr;
406     if (const PointerType *ptr = type->getAs<PointerType>()) {
407       fn = ptr->getPointeeType()->getAs<FunctionType>();
408       if (!fn) return;
409       calleeType = CT_Function;
410     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
411       fn = ptr->getPointeeType()->castAs<FunctionType>();
412       calleeType = CT_Block;
413     } else {
414       return;
415     }
416 
417     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
418       numFormalParams = proto->getNumParams();
419     } else {
420       numFormalParams = 0;
421     }
422   } else {
423     return;
424   }
425 
426   // "nullPos" is the number of formal parameters at the end which
427   // effectively count as part of the variadic arguments.  This is
428   // useful if you would prefer to not have *any* formal parameters,
429   // but the language forces you to have at least one.
430   unsigned nullPos = attr->getNullPos();
431   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
432   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
433 
434   // The number of arguments which should follow the sentinel.
435   unsigned numArgsAfterSentinel = attr->getSentinel();
436 
437   // If there aren't enough arguments for all the formal parameters,
438   // the sentinel, and the args after the sentinel, complain.
439   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
440     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
441     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
442     return;
443   }
444 
445   // Otherwise, find the sentinel expression.
446   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
447   if (!sentinelExpr) return;
448   if (sentinelExpr->isValueDependent()) return;
449   if (Context.isSentinelNullExpr(sentinelExpr)) return;
450 
451   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
452   // or 'NULL' if those are actually defined in the context.  Only use
453   // 'nil' for ObjC methods, where it's much more likely that the
454   // variadic arguments form a list of object pointers.
455   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
456   std::string NullValue;
457   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
458     NullValue = "nil";
459   else if (getLangOpts().CPlusPlus11)
460     NullValue = "nullptr";
461   else if (PP.isMacroDefined("NULL"))
462     NullValue = "NULL";
463   else
464     NullValue = "(void*) 0";
465 
466   if (MissingNilLoc.isInvalid())
467     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
468   else
469     Diag(MissingNilLoc, diag::warn_missing_sentinel)
470       << int(calleeType)
471       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
472   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
473 }
474 
475 SourceRange Sema::getExprRange(Expr *E) const {
476   return E ? E->getSourceRange() : SourceRange();
477 }
478 
479 //===----------------------------------------------------------------------===//
480 //  Standard Promotions and Conversions
481 //===----------------------------------------------------------------------===//
482 
483 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
484 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
485   // Handle any placeholder expressions which made it here.
486   if (E->getType()->isPlaceholderType()) {
487     ExprResult result = CheckPlaceholderExpr(E);
488     if (result.isInvalid()) return ExprError();
489     E = result.get();
490   }
491 
492   QualType Ty = E->getType();
493   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
494 
495   if (Ty->isFunctionType()) {
496     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
497       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
498         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
499           return ExprError();
500 
501     E = ImpCastExprToType(E, Context.getPointerType(Ty),
502                           CK_FunctionToPointerDecay).get();
503   } else if (Ty->isArrayType()) {
504     // In C90 mode, arrays only promote to pointers if the array expression is
505     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
506     // type 'array of type' is converted to an expression that has type 'pointer
507     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
508     // that has type 'array of type' ...".  The relevant change is "an lvalue"
509     // (C90) to "an expression" (C99).
510     //
511     // C++ 4.2p1:
512     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
513     // T" can be converted to an rvalue of type "pointer to T".
514     //
515     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
516       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
517                             CK_ArrayToPointerDecay).get();
518   }
519   return E;
520 }
521 
522 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
523   // Check to see if we are dereferencing a null pointer.  If so,
524   // and if not volatile-qualified, this is undefined behavior that the
525   // optimizer will delete, so warn about it.  People sometimes try to use this
526   // to get a deterministic trap and are surprised by clang's behavior.  This
527   // only handles the pattern "*null", which is a very syntactic check.
528   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
529   if (UO && UO->getOpcode() == UO_Deref &&
530       UO->getSubExpr()->getType()->isPointerType()) {
531     const LangAS AS =
532         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
533     if ((!isTargetAddressSpace(AS) ||
534          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
535         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
536             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
537         !UO->getType().isVolatileQualified()) {
538       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
539                             S.PDiag(diag::warn_indirection_through_null)
540                                 << UO->getSubExpr()->getSourceRange());
541       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
542                             S.PDiag(diag::note_indirection_through_null));
543     }
544   }
545 }
546 
547 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
548                                     SourceLocation AssignLoc,
549                                     const Expr* RHS) {
550   const ObjCIvarDecl *IV = OIRE->getDecl();
551   if (!IV)
552     return;
553 
554   DeclarationName MemberName = IV->getDeclName();
555   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
556   if (!Member || !Member->isStr("isa"))
557     return;
558 
559   const Expr *Base = OIRE->getBase();
560   QualType BaseType = Base->getType();
561   if (OIRE->isArrow())
562     BaseType = BaseType->getPointeeType();
563   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
564     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
565       ObjCInterfaceDecl *ClassDeclared = nullptr;
566       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
567       if (!ClassDeclared->getSuperClass()
568           && (*ClassDeclared->ivar_begin()) == IV) {
569         if (RHS) {
570           NamedDecl *ObjectSetClass =
571             S.LookupSingleName(S.TUScope,
572                                &S.Context.Idents.get("object_setClass"),
573                                SourceLocation(), S.LookupOrdinaryName);
574           if (ObjectSetClass) {
575             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
576             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
577                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
578                                               "object_setClass(")
579                 << FixItHint::CreateReplacement(
580                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
581                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
582           }
583           else
584             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
585         } else {
586           NamedDecl *ObjectGetClass =
587             S.LookupSingleName(S.TUScope,
588                                &S.Context.Idents.get("object_getClass"),
589                                SourceLocation(), S.LookupOrdinaryName);
590           if (ObjectGetClass)
591             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
592                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
593                                               "object_getClass(")
594                 << FixItHint::CreateReplacement(
595                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
596           else
597             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
598         }
599         S.Diag(IV->getLocation(), diag::note_ivar_decl);
600       }
601     }
602 }
603 
604 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
605   // Handle any placeholder expressions which made it here.
606   if (E->getType()->isPlaceholderType()) {
607     ExprResult result = CheckPlaceholderExpr(E);
608     if (result.isInvalid()) return ExprError();
609     E = result.get();
610   }
611 
612   // C++ [conv.lval]p1:
613   //   A glvalue of a non-function, non-array type T can be
614   //   converted to a prvalue.
615   if (!E->isGLValue()) return E;
616 
617   QualType T = E->getType();
618   assert(!T.isNull() && "r-value conversion on typeless expression?");
619 
620   // lvalue-to-rvalue conversion cannot be applied to function or array types.
621   if (T->isFunctionType() || T->isArrayType())
622     return E;
623 
624   // We don't want to throw lvalue-to-rvalue casts on top of
625   // expressions of certain types in C++.
626   if (getLangOpts().CPlusPlus &&
627       (E->getType() == Context.OverloadTy ||
628        T->isDependentType() ||
629        T->isRecordType()))
630     return E;
631 
632   // The C standard is actually really unclear on this point, and
633   // DR106 tells us what the result should be but not why.  It's
634   // generally best to say that void types just doesn't undergo
635   // lvalue-to-rvalue at all.  Note that expressions of unqualified
636   // 'void' type are never l-values, but qualified void can be.
637   if (T->isVoidType())
638     return E;
639 
640   // OpenCL usually rejects direct accesses to values of 'half' type.
641   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
642       T->isHalfType()) {
643     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
644       << 0 << T;
645     return ExprError();
646   }
647 
648   CheckForNullPointerDereference(*this, E);
649   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
650     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
651                                      &Context.Idents.get("object_getClass"),
652                                      SourceLocation(), LookupOrdinaryName);
653     if (ObjectGetClass)
654       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
655           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
656           << FixItHint::CreateReplacement(
657                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
658     else
659       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
660   }
661   else if (const ObjCIvarRefExpr *OIRE =
662             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
663     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
664 
665   // C++ [conv.lval]p1:
666   //   [...] If T is a non-class type, the type of the prvalue is the
667   //   cv-unqualified version of T. Otherwise, the type of the
668   //   rvalue is T.
669   //
670   // C99 6.3.2.1p2:
671   //   If the lvalue has qualified type, the value has the unqualified
672   //   version of the type of the lvalue; otherwise, the value has the
673   //   type of the lvalue.
674   if (T.hasQualifiers())
675     T = T.getUnqualifiedType();
676 
677   // Under the MS ABI, lock down the inheritance model now.
678   if (T->isMemberPointerType() &&
679       Context.getTargetInfo().getCXXABI().isMicrosoft())
680     (void)isCompleteType(E->getExprLoc(), T);
681 
682   ExprResult Res = CheckLValueToRValueConversionOperand(E);
683   if (Res.isInvalid())
684     return Res;
685   E = Res.get();
686 
687   // Loading a __weak object implicitly retains the value, so we need a cleanup to
688   // balance that.
689   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
690     Cleanup.setExprNeedsCleanups(true);
691 
692   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
693     Cleanup.setExprNeedsCleanups(true);
694 
695   // C++ [conv.lval]p3:
696   //   If T is cv std::nullptr_t, the result is a null pointer constant.
697   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
698   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
699 
700   // C11 6.3.2.1p2:
701   //   ... if the lvalue has atomic type, the value has the non-atomic version
702   //   of the type of the lvalue ...
703   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
704     T = Atomic->getValueType().getUnqualifiedType();
705     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
706                                    nullptr, VK_RValue);
707   }
708 
709   return Res;
710 }
711 
712 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
713   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
714   if (Res.isInvalid())
715     return ExprError();
716   Res = DefaultLvalueConversion(Res.get());
717   if (Res.isInvalid())
718     return ExprError();
719   return Res;
720 }
721 
722 /// CallExprUnaryConversions - a special case of an unary conversion
723 /// performed on a function designator of a call expression.
724 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
725   QualType Ty = E->getType();
726   ExprResult Res = E;
727   // Only do implicit cast for a function type, but not for a pointer
728   // to function type.
729   if (Ty->isFunctionType()) {
730     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
731                             CK_FunctionToPointerDecay);
732     if (Res.isInvalid())
733       return ExprError();
734   }
735   Res = DefaultLvalueConversion(Res.get());
736   if (Res.isInvalid())
737     return ExprError();
738   return Res.get();
739 }
740 
741 /// UsualUnaryConversions - Performs various conversions that are common to most
742 /// operators (C99 6.3). The conversions of array and function types are
743 /// sometimes suppressed. For example, the array->pointer conversion doesn't
744 /// apply if the array is an argument to the sizeof or address (&) operators.
745 /// In these instances, this routine should *not* be called.
746 ExprResult Sema::UsualUnaryConversions(Expr *E) {
747   // First, convert to an r-value.
748   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
749   if (Res.isInvalid())
750     return ExprError();
751   E = Res.get();
752 
753   QualType Ty = E->getType();
754   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
755 
756   // Half FP have to be promoted to float unless it is natively supported
757   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
758     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
759 
760   // Try to perform integral promotions if the object has a theoretically
761   // promotable type.
762   if (Ty->isIntegralOrUnscopedEnumerationType()) {
763     // C99 6.3.1.1p2:
764     //
765     //   The following may be used in an expression wherever an int or
766     //   unsigned int may be used:
767     //     - an object or expression with an integer type whose integer
768     //       conversion rank is less than or equal to the rank of int
769     //       and unsigned int.
770     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
771     //
772     //   If an int can represent all values of the original type, the
773     //   value is converted to an int; otherwise, it is converted to an
774     //   unsigned int. These are called the integer promotions. All
775     //   other types are unchanged by the integer promotions.
776 
777     QualType PTy = Context.isPromotableBitField(E);
778     if (!PTy.isNull()) {
779       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
780       return E;
781     }
782     if (Ty->isPromotableIntegerType()) {
783       QualType PT = Context.getPromotedIntegerType(Ty);
784       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
785       return E;
786     }
787   }
788   return E;
789 }
790 
791 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
792 /// do not have a prototype. Arguments that have type float or __fp16
793 /// are promoted to double. All other argument types are converted by
794 /// UsualUnaryConversions().
795 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
796   QualType Ty = E->getType();
797   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
798 
799   ExprResult Res = UsualUnaryConversions(E);
800   if (Res.isInvalid())
801     return ExprError();
802   E = Res.get();
803 
804   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
805   // promote to double.
806   // Note that default argument promotion applies only to float (and
807   // half/fp16); it does not apply to _Float16.
808   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
809   if (BTy && (BTy->getKind() == BuiltinType::Half ||
810               BTy->getKind() == BuiltinType::Float)) {
811     if (getLangOpts().OpenCL &&
812         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
813         if (BTy->getKind() == BuiltinType::Half) {
814             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
815         }
816     } else {
817       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
818     }
819   }
820 
821   // C++ performs lvalue-to-rvalue conversion as a default argument
822   // promotion, even on class types, but note:
823   //   C++11 [conv.lval]p2:
824   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
825   //     operand or a subexpression thereof the value contained in the
826   //     referenced object is not accessed. Otherwise, if the glvalue
827   //     has a class type, the conversion copy-initializes a temporary
828   //     of type T from the glvalue and the result of the conversion
829   //     is a prvalue for the temporary.
830   // FIXME: add some way to gate this entire thing for correctness in
831   // potentially potentially evaluated contexts.
832   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
833     ExprResult Temp = PerformCopyInitialization(
834                        InitializedEntity::InitializeTemporary(E->getType()),
835                                                 E->getExprLoc(), E);
836     if (Temp.isInvalid())
837       return ExprError();
838     E = Temp.get();
839   }
840 
841   return E;
842 }
843 
844 /// Determine the degree of POD-ness for an expression.
845 /// Incomplete types are considered POD, since this check can be performed
846 /// when we're in an unevaluated context.
847 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
848   if (Ty->isIncompleteType()) {
849     // C++11 [expr.call]p7:
850     //   After these conversions, if the argument does not have arithmetic,
851     //   enumeration, pointer, pointer to member, or class type, the program
852     //   is ill-formed.
853     //
854     // Since we've already performed array-to-pointer and function-to-pointer
855     // decay, the only such type in C++ is cv void. This also handles
856     // initializer lists as variadic arguments.
857     if (Ty->isVoidType())
858       return VAK_Invalid;
859 
860     if (Ty->isObjCObjectType())
861       return VAK_Invalid;
862     return VAK_Valid;
863   }
864 
865   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
866     return VAK_Invalid;
867 
868   if (Ty.isCXX98PODType(Context))
869     return VAK_Valid;
870 
871   // C++11 [expr.call]p7:
872   //   Passing a potentially-evaluated argument of class type (Clause 9)
873   //   having a non-trivial copy constructor, a non-trivial move constructor,
874   //   or a non-trivial destructor, with no corresponding parameter,
875   //   is conditionally-supported with implementation-defined semantics.
876   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
877     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
878       if (!Record->hasNonTrivialCopyConstructor() &&
879           !Record->hasNonTrivialMoveConstructor() &&
880           !Record->hasNonTrivialDestructor())
881         return VAK_ValidInCXX11;
882 
883   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
884     return VAK_Valid;
885 
886   if (Ty->isObjCObjectType())
887     return VAK_Invalid;
888 
889   if (getLangOpts().MSVCCompat)
890     return VAK_MSVCUndefined;
891 
892   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
893   // permitted to reject them. We should consider doing so.
894   return VAK_Undefined;
895 }
896 
897 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
898   // Don't allow one to pass an Objective-C interface to a vararg.
899   const QualType &Ty = E->getType();
900   VarArgKind VAK = isValidVarArgType(Ty);
901 
902   // Complain about passing non-POD types through varargs.
903   switch (VAK) {
904   case VAK_ValidInCXX11:
905     DiagRuntimeBehavior(
906         E->getBeginLoc(), nullptr,
907         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
908     LLVM_FALLTHROUGH;
909   case VAK_Valid:
910     if (Ty->isRecordType()) {
911       // This is unlikely to be what the user intended. If the class has a
912       // 'c_str' member function, the user probably meant to call that.
913       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
914                           PDiag(diag::warn_pass_class_arg_to_vararg)
915                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
916     }
917     break;
918 
919   case VAK_Undefined:
920   case VAK_MSVCUndefined:
921     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
922                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
923                             << getLangOpts().CPlusPlus11 << Ty << CT);
924     break;
925 
926   case VAK_Invalid:
927     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
928       Diag(E->getBeginLoc(),
929            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
930           << Ty << CT;
931     else if (Ty->isObjCObjectType())
932       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
933                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
934                               << Ty << CT);
935     else
936       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
937           << isa<InitListExpr>(E) << Ty << CT;
938     break;
939   }
940 }
941 
942 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
943 /// will create a trap if the resulting type is not a POD type.
944 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
945                                                   FunctionDecl *FDecl) {
946   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
947     // Strip the unbridged-cast placeholder expression off, if applicable.
948     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
949         (CT == VariadicMethod ||
950          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
951       E = stripARCUnbridgedCast(E);
952 
953     // Otherwise, do normal placeholder checking.
954     } else {
955       ExprResult ExprRes = CheckPlaceholderExpr(E);
956       if (ExprRes.isInvalid())
957         return ExprError();
958       E = ExprRes.get();
959     }
960   }
961 
962   ExprResult ExprRes = DefaultArgumentPromotion(E);
963   if (ExprRes.isInvalid())
964     return ExprError();
965 
966   // Copy blocks to the heap.
967   if (ExprRes.get()->getType()->isBlockPointerType())
968     maybeExtendBlockObject(ExprRes);
969 
970   E = ExprRes.get();
971 
972   // Diagnostics regarding non-POD argument types are
973   // emitted along with format string checking in Sema::CheckFunctionCall().
974   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
975     // Turn this into a trap.
976     CXXScopeSpec SS;
977     SourceLocation TemplateKWLoc;
978     UnqualifiedId Name;
979     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
980                        E->getBeginLoc());
981     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
982                                           /*HasTrailingLParen=*/true,
983                                           /*IsAddressOfOperand=*/false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
988                                     None, E->getEndLoc());
989     if (Call.isInvalid())
990       return ExprError();
991 
992     ExprResult Comma =
993         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
994     if (Comma.isInvalid())
995       return ExprError();
996     return Comma.get();
997   }
998 
999   if (!getLangOpts().CPlusPlus &&
1000       RequireCompleteType(E->getExprLoc(), E->getType(),
1001                           diag::err_call_incomplete_argument))
1002     return ExprError();
1003 
1004   return E;
1005 }
1006 
1007 /// Converts an integer to complex float type.  Helper function of
1008 /// UsualArithmeticConversions()
1009 ///
1010 /// \return false if the integer expression is an integer type and is
1011 /// successfully converted to the complex type.
1012 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1013                                                   ExprResult &ComplexExpr,
1014                                                   QualType IntTy,
1015                                                   QualType ComplexTy,
1016                                                   bool SkipCast) {
1017   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1018   if (SkipCast) return false;
1019   if (IntTy->isIntegerType()) {
1020     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1023                                   CK_FloatingRealToComplex);
1024   } else {
1025     assert(IntTy->isComplexIntegerType());
1026     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1027                                   CK_IntegralComplexToFloatingComplex);
1028   }
1029   return false;
1030 }
1031 
1032 /// Handle arithmetic conversion with complex types.  Helper function of
1033 /// UsualArithmeticConversions()
1034 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1035                                              ExprResult &RHS, QualType LHSType,
1036                                              QualType RHSType,
1037                                              bool IsCompAssign) {
1038   // if we have an integer operand, the result is the complex type.
1039   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1040                                              /*skipCast*/false))
1041     return LHSType;
1042   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1043                                              /*skipCast*/IsCompAssign))
1044     return RHSType;
1045 
1046   // This handles complex/complex, complex/float, or float/complex.
1047   // When both operands are complex, the shorter operand is converted to the
1048   // type of the longer, and that is the type of the result. This corresponds
1049   // to what is done when combining two real floating-point operands.
1050   // The fun begins when size promotion occur across type domains.
1051   // From H&S 6.3.4: When one operand is complex and the other is a real
1052   // floating-point type, the less precise type is converted, within it's
1053   // real or complex domain, to the precision of the other type. For example,
1054   // when combining a "long double" with a "double _Complex", the
1055   // "double _Complex" is promoted to "long double _Complex".
1056 
1057   // Compute the rank of the two types, regardless of whether they are complex.
1058   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1059 
1060   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1061   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1062   QualType LHSElementType =
1063       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1064   QualType RHSElementType =
1065       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1066 
1067   QualType ResultType = S.Context.getComplexType(LHSElementType);
1068   if (Order < 0) {
1069     // Promote the precision of the LHS if not an assignment.
1070     ResultType = S.Context.getComplexType(RHSElementType);
1071     if (!IsCompAssign) {
1072       if (LHSComplexType)
1073         LHS =
1074             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1075       else
1076         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1077     }
1078   } else if (Order > 0) {
1079     // Promote the precision of the RHS.
1080     if (RHSComplexType)
1081       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1082     else
1083       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1084   }
1085   return ResultType;
1086 }
1087 
1088 /// Handle arithmetic conversion from integer to float.  Helper function
1089 /// of UsualArithmeticConversions()
1090 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1091                                            ExprResult &IntExpr,
1092                                            QualType FloatTy, QualType IntTy,
1093                                            bool ConvertFloat, bool ConvertInt) {
1094   if (IntTy->isIntegerType()) {
1095     if (ConvertInt)
1096       // Convert intExpr to the lhs floating point type.
1097       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1098                                     CK_IntegralToFloating);
1099     return FloatTy;
1100   }
1101 
1102   // Convert both sides to the appropriate complex float.
1103   assert(IntTy->isComplexIntegerType());
1104   QualType result = S.Context.getComplexType(FloatTy);
1105 
1106   // _Complex int -> _Complex float
1107   if (ConvertInt)
1108     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1109                                   CK_IntegralComplexToFloatingComplex);
1110 
1111   // float -> _Complex float
1112   if (ConvertFloat)
1113     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1114                                     CK_FloatingRealToComplex);
1115 
1116   return result;
1117 }
1118 
1119 /// Handle arithmethic conversion with floating point types.  Helper
1120 /// function of UsualArithmeticConversions()
1121 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1122                                       ExprResult &RHS, QualType LHSType,
1123                                       QualType RHSType, bool IsCompAssign) {
1124   bool LHSFloat = LHSType->isRealFloatingType();
1125   bool RHSFloat = RHSType->isRealFloatingType();
1126 
1127   // FIXME: Implement floating to fixed point conversion.(Bug 46268)
1128   // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions).
1129   if ((LHSType->isFixedPointType() && RHSFloat) ||
1130       (LHSFloat && RHSType->isFixedPointType()))
1131     return QualType();
1132   // If we have two real floating types, convert the smaller operand
1133   // to the bigger result.
1134   if (LHSFloat && RHSFloat) {
1135     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1136     if (order > 0) {
1137       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138       return LHSType;
1139     }
1140 
1141     assert(order < 0 && "illegal float comparison");
1142     if (!IsCompAssign)
1143       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1144     return RHSType;
1145   }
1146 
1147   if (LHSFloat) {
1148     // Half FP has to be promoted to float unless it is natively supported
1149     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1150       LHSType = S.Context.FloatTy;
1151 
1152     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153                                       /*ConvertFloat=*/!IsCompAssign,
1154                                       /*ConvertInt=*/ true);
1155   }
1156   assert(RHSFloat);
1157   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1158                                     /*ConvertFloat=*/ true,
1159                                     /*ConvertInt=*/!IsCompAssign);
1160 }
1161 
1162 /// Diagnose attempts to convert between __float128 and long double if
1163 /// there is no support for such conversion. Helper function of
1164 /// UsualArithmeticConversions().
1165 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1166                                       QualType RHSType) {
1167   /*  No issue converting if at least one of the types is not a floating point
1168       type or the two types have the same rank.
1169   */
1170   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1171       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1172     return false;
1173 
1174   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1175          "The remaining types must be floating point types.");
1176 
1177   auto *LHSComplex = LHSType->getAs<ComplexType>();
1178   auto *RHSComplex = RHSType->getAs<ComplexType>();
1179 
1180   QualType LHSElemType = LHSComplex ?
1181     LHSComplex->getElementType() : LHSType;
1182   QualType RHSElemType = RHSComplex ?
1183     RHSComplex->getElementType() : RHSType;
1184 
1185   // No issue if the two types have the same representation
1186   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1187       &S.Context.getFloatTypeSemantics(RHSElemType))
1188     return false;
1189 
1190   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1191                                 RHSElemType == S.Context.LongDoubleTy);
1192   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1193                             RHSElemType == S.Context.Float128Ty);
1194 
1195   // We've handled the situation where __float128 and long double have the same
1196   // representation. We allow all conversions for all possible long double types
1197   // except PPC's double double.
1198   return Float128AndLongDouble &&
1199     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1200      &llvm::APFloat::PPCDoubleDouble());
1201 }
1202 
1203 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1204 
1205 namespace {
1206 /// These helper callbacks are placed in an anonymous namespace to
1207 /// permit their use as function template parameters.
1208 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1209   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1210 }
1211 
1212 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1213   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1214                              CK_IntegralComplexCast);
1215 }
1216 }
1217 
1218 /// Handle integer arithmetic conversions.  Helper function of
1219 /// UsualArithmeticConversions()
1220 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1221 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1222                                         ExprResult &RHS, QualType LHSType,
1223                                         QualType RHSType, bool IsCompAssign) {
1224   // The rules for this case are in C99 6.3.1.8
1225   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1226   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1227   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1228   if (LHSSigned == RHSSigned) {
1229     // Same signedness; use the higher-ranked type
1230     if (order >= 0) {
1231       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1232       return LHSType;
1233     } else if (!IsCompAssign)
1234       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1235     return RHSType;
1236   } else if (order != (LHSSigned ? 1 : -1)) {
1237     // The unsigned type has greater than or equal rank to the
1238     // signed type, so use the unsigned type
1239     if (RHSSigned) {
1240       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1241       return LHSType;
1242     } else if (!IsCompAssign)
1243       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1244     return RHSType;
1245   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1246     // The two types are different widths; if we are here, that
1247     // means the signed type is larger than the unsigned type, so
1248     // use the signed type.
1249     if (LHSSigned) {
1250       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1251       return LHSType;
1252     } else if (!IsCompAssign)
1253       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1254     return RHSType;
1255   } else {
1256     // The signed type is higher-ranked than the unsigned type,
1257     // but isn't actually any bigger (like unsigned int and long
1258     // on most 32-bit systems).  Use the unsigned type corresponding
1259     // to the signed type.
1260     QualType result =
1261       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1262     RHS = (*doRHSCast)(S, RHS.get(), result);
1263     if (!IsCompAssign)
1264       LHS = (*doLHSCast)(S, LHS.get(), result);
1265     return result;
1266   }
1267 }
1268 
1269 /// Handle conversions with GCC complex int extension.  Helper function
1270 /// of UsualArithmeticConversions()
1271 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1272                                            ExprResult &RHS, QualType LHSType,
1273                                            QualType RHSType,
1274                                            bool IsCompAssign) {
1275   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1276   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1277 
1278   if (LHSComplexInt && RHSComplexInt) {
1279     QualType LHSEltType = LHSComplexInt->getElementType();
1280     QualType RHSEltType = RHSComplexInt->getElementType();
1281     QualType ScalarType =
1282       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1283         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1284 
1285     return S.Context.getComplexType(ScalarType);
1286   }
1287 
1288   if (LHSComplexInt) {
1289     QualType LHSEltType = LHSComplexInt->getElementType();
1290     QualType ScalarType =
1291       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1292         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1293     QualType ComplexType = S.Context.getComplexType(ScalarType);
1294     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1295                               CK_IntegralRealToComplex);
1296 
1297     return ComplexType;
1298   }
1299 
1300   assert(RHSComplexInt);
1301 
1302   QualType RHSEltType = RHSComplexInt->getElementType();
1303   QualType ScalarType =
1304     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1305       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1306   QualType ComplexType = S.Context.getComplexType(ScalarType);
1307 
1308   if (!IsCompAssign)
1309     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1310                               CK_IntegralRealToComplex);
1311   return ComplexType;
1312 }
1313 
1314 /// Return the rank of a given fixed point or integer type. The value itself
1315 /// doesn't matter, but the values must be increasing with proper increasing
1316 /// rank as described in N1169 4.1.1.
1317 static unsigned GetFixedPointRank(QualType Ty) {
1318   const auto *BTy = Ty->getAs<BuiltinType>();
1319   assert(BTy && "Expected a builtin type.");
1320 
1321   switch (BTy->getKind()) {
1322   case BuiltinType::ShortFract:
1323   case BuiltinType::UShortFract:
1324   case BuiltinType::SatShortFract:
1325   case BuiltinType::SatUShortFract:
1326     return 1;
1327   case BuiltinType::Fract:
1328   case BuiltinType::UFract:
1329   case BuiltinType::SatFract:
1330   case BuiltinType::SatUFract:
1331     return 2;
1332   case BuiltinType::LongFract:
1333   case BuiltinType::ULongFract:
1334   case BuiltinType::SatLongFract:
1335   case BuiltinType::SatULongFract:
1336     return 3;
1337   case BuiltinType::ShortAccum:
1338   case BuiltinType::UShortAccum:
1339   case BuiltinType::SatShortAccum:
1340   case BuiltinType::SatUShortAccum:
1341     return 4;
1342   case BuiltinType::Accum:
1343   case BuiltinType::UAccum:
1344   case BuiltinType::SatAccum:
1345   case BuiltinType::SatUAccum:
1346     return 5;
1347   case BuiltinType::LongAccum:
1348   case BuiltinType::ULongAccum:
1349   case BuiltinType::SatLongAccum:
1350   case BuiltinType::SatULongAccum:
1351     return 6;
1352   default:
1353     if (BTy->isInteger())
1354       return 0;
1355     llvm_unreachable("Unexpected fixed point or integer type");
1356   }
1357 }
1358 
1359 /// handleFixedPointConversion - Fixed point operations between fixed
1360 /// point types and integers or other fixed point types do not fall under
1361 /// usual arithmetic conversion since these conversions could result in loss
1362 /// of precsision (N1169 4.1.4). These operations should be calculated with
1363 /// the full precision of their result type (N1169 4.1.6.2.1).
1364 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1365                                            QualType RHSTy) {
1366   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1367          "Expected at least one of the operands to be a fixed point type");
1368   assert((LHSTy->isFixedPointOrIntegerType() ||
1369           RHSTy->isFixedPointOrIntegerType()) &&
1370          "Special fixed point arithmetic operation conversions are only "
1371          "applied to ints or other fixed point types");
1372 
1373   // If one operand has signed fixed-point type and the other operand has
1374   // unsigned fixed-point type, then the unsigned fixed-point operand is
1375   // converted to its corresponding signed fixed-point type and the resulting
1376   // type is the type of the converted operand.
1377   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1378     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1379   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1380     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1381 
1382   // The result type is the type with the highest rank, whereby a fixed-point
1383   // conversion rank is always greater than an integer conversion rank; if the
1384   // type of either of the operands is a saturating fixedpoint type, the result
1385   // type shall be the saturating fixed-point type corresponding to the type
1386   // with the highest rank; the resulting value is converted (taking into
1387   // account rounding and overflow) to the precision of the resulting type.
1388   // Same ranks between signed and unsigned types are resolved earlier, so both
1389   // types are either signed or both unsigned at this point.
1390   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1391   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1392 
1393   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1394 
1395   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1396     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1397 
1398   return ResultTy;
1399 }
1400 
1401 /// Check that the usual arithmetic conversions can be performed on this pair of
1402 /// expressions that might be of enumeration type.
1403 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1404                                            SourceLocation Loc,
1405                                            Sema::ArithConvKind ACK) {
1406   // C++2a [expr.arith.conv]p1:
1407   //   If one operand is of enumeration type and the other operand is of a
1408   //   different enumeration type or a floating-point type, this behavior is
1409   //   deprecated ([depr.arith.conv.enum]).
1410   //
1411   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1412   // Eventually we will presumably reject these cases (in C++23 onwards?).
1413   QualType L = LHS->getType(), R = RHS->getType();
1414   bool LEnum = L->isUnscopedEnumerationType(),
1415        REnum = R->isUnscopedEnumerationType();
1416   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1417   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1418       (REnum && L->isFloatingType())) {
1419     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1420                     ? diag::warn_arith_conv_enum_float_cxx20
1421                     : diag::warn_arith_conv_enum_float)
1422         << LHS->getSourceRange() << RHS->getSourceRange()
1423         << (int)ACK << LEnum << L << R;
1424   } else if (!IsCompAssign && LEnum && REnum &&
1425              !S.Context.hasSameUnqualifiedType(L, R)) {
1426     unsigned DiagID;
1427     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1428         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1429       // If either enumeration type is unnamed, it's less likely that the
1430       // user cares about this, but this situation is still deprecated in
1431       // C++2a. Use a different warning group.
1432       DiagID = S.getLangOpts().CPlusPlus20
1433                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1434                     : diag::warn_arith_conv_mixed_anon_enum_types;
1435     } else if (ACK == Sema::ACK_Conditional) {
1436       // Conditional expressions are separated out because they have
1437       // historically had a different warning flag.
1438       DiagID = S.getLangOpts().CPlusPlus20
1439                    ? diag::warn_conditional_mixed_enum_types_cxx20
1440                    : diag::warn_conditional_mixed_enum_types;
1441     } else if (ACK == Sema::ACK_Comparison) {
1442       // Comparison expressions are separated out because they have
1443       // historically had a different warning flag.
1444       DiagID = S.getLangOpts().CPlusPlus20
1445                    ? diag::warn_comparison_mixed_enum_types_cxx20
1446                    : diag::warn_comparison_mixed_enum_types;
1447     } else {
1448       DiagID = S.getLangOpts().CPlusPlus20
1449                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1450                    : diag::warn_arith_conv_mixed_enum_types;
1451     }
1452     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1453                         << (int)ACK << L << R;
1454   }
1455 }
1456 
1457 /// UsualArithmeticConversions - Performs various conversions that are common to
1458 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1459 /// routine returns the first non-arithmetic type found. The client is
1460 /// responsible for emitting appropriate error diagnostics.
1461 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1462                                           SourceLocation Loc,
1463                                           ArithConvKind ACK) {
1464   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1465 
1466   if (ACK != ACK_CompAssign) {
1467     LHS = UsualUnaryConversions(LHS.get());
1468     if (LHS.isInvalid())
1469       return QualType();
1470   }
1471 
1472   RHS = UsualUnaryConversions(RHS.get());
1473   if (RHS.isInvalid())
1474     return QualType();
1475 
1476   // For conversion purposes, we ignore any qualifiers.
1477   // For example, "const float" and "float" are equivalent.
1478   QualType LHSType =
1479     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1480   QualType RHSType =
1481     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1482 
1483   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1484   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1485     LHSType = AtomicLHS->getValueType();
1486 
1487   // If both types are identical, no conversion is needed.
1488   if (LHSType == RHSType)
1489     return LHSType;
1490 
1491   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1492   // The caller can deal with this (e.g. pointer + int).
1493   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1494     return QualType();
1495 
1496   // Apply unary and bitfield promotions to the LHS's type.
1497   QualType LHSUnpromotedType = LHSType;
1498   if (LHSType->isPromotableIntegerType())
1499     LHSType = Context.getPromotedIntegerType(LHSType);
1500   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1501   if (!LHSBitfieldPromoteTy.isNull())
1502     LHSType = LHSBitfieldPromoteTy;
1503   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1504     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1505 
1506   // If both types are identical, no conversion is needed.
1507   if (LHSType == RHSType)
1508     return LHSType;
1509 
1510   // ExtInt types aren't subject to conversions between them or normal integers,
1511   // so this fails.
1512   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1513     return QualType();
1514 
1515   // At this point, we have two different arithmetic types.
1516 
1517   // Diagnose attempts to convert between __float128 and long double where
1518   // such conversions currently can't be handled.
1519   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1520     return QualType();
1521 
1522   // Handle complex types first (C99 6.3.1.8p1).
1523   if (LHSType->isComplexType() || RHSType->isComplexType())
1524     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1525                                         ACK == ACK_CompAssign);
1526 
1527   // Now handle "real" floating types (i.e. float, double, long double).
1528   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1529     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1530                                  ACK == ACK_CompAssign);
1531 
1532   // Handle GCC complex int extension.
1533   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1534     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1535                                       ACK == ACK_CompAssign);
1536 
1537   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1538     return handleFixedPointConversion(*this, LHSType, RHSType);
1539 
1540   // Finally, we have two differing integer types.
1541   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1542            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1543 }
1544 
1545 //===----------------------------------------------------------------------===//
1546 //  Semantic Analysis for various Expression Types
1547 //===----------------------------------------------------------------------===//
1548 
1549 
1550 ExprResult
1551 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1552                                 SourceLocation DefaultLoc,
1553                                 SourceLocation RParenLoc,
1554                                 Expr *ControllingExpr,
1555                                 ArrayRef<ParsedType> ArgTypes,
1556                                 ArrayRef<Expr *> ArgExprs) {
1557   unsigned NumAssocs = ArgTypes.size();
1558   assert(NumAssocs == ArgExprs.size());
1559 
1560   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1561   for (unsigned i = 0; i < NumAssocs; ++i) {
1562     if (ArgTypes[i])
1563       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1564     else
1565       Types[i] = nullptr;
1566   }
1567 
1568   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1569                                              ControllingExpr,
1570                                              llvm::makeArrayRef(Types, NumAssocs),
1571                                              ArgExprs);
1572   delete [] Types;
1573   return ER;
1574 }
1575 
1576 ExprResult
1577 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1578                                  SourceLocation DefaultLoc,
1579                                  SourceLocation RParenLoc,
1580                                  Expr *ControllingExpr,
1581                                  ArrayRef<TypeSourceInfo *> Types,
1582                                  ArrayRef<Expr *> Exprs) {
1583   unsigned NumAssocs = Types.size();
1584   assert(NumAssocs == Exprs.size());
1585 
1586   // Decay and strip qualifiers for the controlling expression type, and handle
1587   // placeholder type replacement. See committee discussion from WG14 DR423.
1588   {
1589     EnterExpressionEvaluationContext Unevaluated(
1590         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1591     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1592     if (R.isInvalid())
1593       return ExprError();
1594     ControllingExpr = R.get();
1595   }
1596 
1597   // The controlling expression is an unevaluated operand, so side effects are
1598   // likely unintended.
1599   if (!inTemplateInstantiation() &&
1600       ControllingExpr->HasSideEffects(Context, false))
1601     Diag(ControllingExpr->getExprLoc(),
1602          diag::warn_side_effects_unevaluated_context);
1603 
1604   bool TypeErrorFound = false,
1605        IsResultDependent = ControllingExpr->isTypeDependent(),
1606        ContainsUnexpandedParameterPack
1607          = ControllingExpr->containsUnexpandedParameterPack();
1608 
1609   for (unsigned i = 0; i < NumAssocs; ++i) {
1610     if (Exprs[i]->containsUnexpandedParameterPack())
1611       ContainsUnexpandedParameterPack = true;
1612 
1613     if (Types[i]) {
1614       if (Types[i]->getType()->containsUnexpandedParameterPack())
1615         ContainsUnexpandedParameterPack = true;
1616 
1617       if (Types[i]->getType()->isDependentType()) {
1618         IsResultDependent = true;
1619       } else {
1620         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1621         // complete object type other than a variably modified type."
1622         unsigned D = 0;
1623         if (Types[i]->getType()->isIncompleteType())
1624           D = diag::err_assoc_type_incomplete;
1625         else if (!Types[i]->getType()->isObjectType())
1626           D = diag::err_assoc_type_nonobject;
1627         else if (Types[i]->getType()->isVariablyModifiedType())
1628           D = diag::err_assoc_type_variably_modified;
1629 
1630         if (D != 0) {
1631           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1632             << Types[i]->getTypeLoc().getSourceRange()
1633             << Types[i]->getType();
1634           TypeErrorFound = true;
1635         }
1636 
1637         // C11 6.5.1.1p2 "No two generic associations in the same generic
1638         // selection shall specify compatible types."
1639         for (unsigned j = i+1; j < NumAssocs; ++j)
1640           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1641               Context.typesAreCompatible(Types[i]->getType(),
1642                                          Types[j]->getType())) {
1643             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1644                  diag::err_assoc_compatible_types)
1645               << Types[j]->getTypeLoc().getSourceRange()
1646               << Types[j]->getType()
1647               << Types[i]->getType();
1648             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1649                  diag::note_compat_assoc)
1650               << Types[i]->getTypeLoc().getSourceRange()
1651               << Types[i]->getType();
1652             TypeErrorFound = true;
1653           }
1654       }
1655     }
1656   }
1657   if (TypeErrorFound)
1658     return ExprError();
1659 
1660   // If we determined that the generic selection is result-dependent, don't
1661   // try to compute the result expression.
1662   if (IsResultDependent)
1663     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1664                                         Exprs, DefaultLoc, RParenLoc,
1665                                         ContainsUnexpandedParameterPack);
1666 
1667   SmallVector<unsigned, 1> CompatIndices;
1668   unsigned DefaultIndex = -1U;
1669   for (unsigned i = 0; i < NumAssocs; ++i) {
1670     if (!Types[i])
1671       DefaultIndex = i;
1672     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1673                                         Types[i]->getType()))
1674       CompatIndices.push_back(i);
1675   }
1676 
1677   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1678   // type compatible with at most one of the types named in its generic
1679   // association list."
1680   if (CompatIndices.size() > 1) {
1681     // We strip parens here because the controlling expression is typically
1682     // parenthesized in macro definitions.
1683     ControllingExpr = ControllingExpr->IgnoreParens();
1684     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1685         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1686         << (unsigned)CompatIndices.size();
1687     for (unsigned I : CompatIndices) {
1688       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1689            diag::note_compat_assoc)
1690         << Types[I]->getTypeLoc().getSourceRange()
1691         << Types[I]->getType();
1692     }
1693     return ExprError();
1694   }
1695 
1696   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1697   // its controlling expression shall have type compatible with exactly one of
1698   // the types named in its generic association list."
1699   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1700     // We strip parens here because the controlling expression is typically
1701     // parenthesized in macro definitions.
1702     ControllingExpr = ControllingExpr->IgnoreParens();
1703     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1704         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1705     return ExprError();
1706   }
1707 
1708   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1709   // type name that is compatible with the type of the controlling expression,
1710   // then the result expression of the generic selection is the expression
1711   // in that generic association. Otherwise, the result expression of the
1712   // generic selection is the expression in the default generic association."
1713   unsigned ResultIndex =
1714     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1715 
1716   return GenericSelectionExpr::Create(
1717       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1718       ContainsUnexpandedParameterPack, ResultIndex);
1719 }
1720 
1721 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1722 /// location of the token and the offset of the ud-suffix within it.
1723 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1724                                      unsigned Offset) {
1725   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1726                                         S.getLangOpts());
1727 }
1728 
1729 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1730 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1731 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1732                                                  IdentifierInfo *UDSuffix,
1733                                                  SourceLocation UDSuffixLoc,
1734                                                  ArrayRef<Expr*> Args,
1735                                                  SourceLocation LitEndLoc) {
1736   assert(Args.size() <= 2 && "too many arguments for literal operator");
1737 
1738   QualType ArgTy[2];
1739   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1740     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1741     if (ArgTy[ArgIdx]->isArrayType())
1742       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1743   }
1744 
1745   DeclarationName OpName =
1746     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1747   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1748   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1749 
1750   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1751   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1752                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1753                               /*AllowStringTemplate*/ false,
1754                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1755     return ExprError();
1756 
1757   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1758 }
1759 
1760 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1761 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1762 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1763 /// multiple tokens.  However, the common case is that StringToks points to one
1764 /// string.
1765 ///
1766 ExprResult
1767 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1768   assert(!StringToks.empty() && "Must have at least one string!");
1769 
1770   StringLiteralParser Literal(StringToks, PP);
1771   if (Literal.hadError)
1772     return ExprError();
1773 
1774   SmallVector<SourceLocation, 4> StringTokLocs;
1775   for (const Token &Tok : StringToks)
1776     StringTokLocs.push_back(Tok.getLocation());
1777 
1778   QualType CharTy = Context.CharTy;
1779   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1780   if (Literal.isWide()) {
1781     CharTy = Context.getWideCharType();
1782     Kind = StringLiteral::Wide;
1783   } else if (Literal.isUTF8()) {
1784     if (getLangOpts().Char8)
1785       CharTy = Context.Char8Ty;
1786     Kind = StringLiteral::UTF8;
1787   } else if (Literal.isUTF16()) {
1788     CharTy = Context.Char16Ty;
1789     Kind = StringLiteral::UTF16;
1790   } else if (Literal.isUTF32()) {
1791     CharTy = Context.Char32Ty;
1792     Kind = StringLiteral::UTF32;
1793   } else if (Literal.isPascal()) {
1794     CharTy = Context.UnsignedCharTy;
1795   }
1796 
1797   // Warn on initializing an array of char from a u8 string literal; this
1798   // becomes ill-formed in C++2a.
1799   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1800       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1801     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1802 
1803     // Create removals for all 'u8' prefixes in the string literal(s). This
1804     // ensures C++2a compatibility (but may change the program behavior when
1805     // built by non-Clang compilers for which the execution character set is
1806     // not always UTF-8).
1807     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1808     SourceLocation RemovalDiagLoc;
1809     for (const Token &Tok : StringToks) {
1810       if (Tok.getKind() == tok::utf8_string_literal) {
1811         if (RemovalDiagLoc.isInvalid())
1812           RemovalDiagLoc = Tok.getLocation();
1813         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1814             Tok.getLocation(),
1815             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1816                                            getSourceManager(), getLangOpts())));
1817       }
1818     }
1819     Diag(RemovalDiagLoc, RemovalDiag);
1820   }
1821 
1822   QualType StrTy =
1823       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1824 
1825   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1826   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1827                                              Kind, Literal.Pascal, StrTy,
1828                                              &StringTokLocs[0],
1829                                              StringTokLocs.size());
1830   if (Literal.getUDSuffix().empty())
1831     return Lit;
1832 
1833   // We're building a user-defined literal.
1834   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1835   SourceLocation UDSuffixLoc =
1836     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1837                    Literal.getUDSuffixOffset());
1838 
1839   // Make sure we're allowed user-defined literals here.
1840   if (!UDLScope)
1841     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1842 
1843   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1844   //   operator "" X (str, len)
1845   QualType SizeType = Context.getSizeType();
1846 
1847   DeclarationName OpName =
1848     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1849   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1850   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1851 
1852   QualType ArgTy[] = {
1853     Context.getArrayDecayedType(StrTy), SizeType
1854   };
1855 
1856   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1857   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1858                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1859                                 /*AllowStringTemplate*/ true,
1860                                 /*DiagnoseMissing*/ true)) {
1861 
1862   case LOLR_Cooked: {
1863     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1864     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1865                                                     StringTokLocs[0]);
1866     Expr *Args[] = { Lit, LenArg };
1867 
1868     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1869   }
1870 
1871   case LOLR_StringTemplate: {
1872     TemplateArgumentListInfo ExplicitArgs;
1873 
1874     unsigned CharBits = Context.getIntWidth(CharTy);
1875     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1876     llvm::APSInt Value(CharBits, CharIsUnsigned);
1877 
1878     TemplateArgument TypeArg(CharTy);
1879     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1880     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1881 
1882     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1883       Value = Lit->getCodeUnit(I);
1884       TemplateArgument Arg(Context, Value, CharTy);
1885       TemplateArgumentLocInfo ArgInfo;
1886       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1887     }
1888     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1889                                     &ExplicitArgs);
1890   }
1891   case LOLR_Raw:
1892   case LOLR_Template:
1893   case LOLR_ErrorNoDiagnostic:
1894     llvm_unreachable("unexpected literal operator lookup result");
1895   case LOLR_Error:
1896     return ExprError();
1897   }
1898   llvm_unreachable("unexpected literal operator lookup result");
1899 }
1900 
1901 DeclRefExpr *
1902 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1903                        SourceLocation Loc,
1904                        const CXXScopeSpec *SS) {
1905   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1906   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1907 }
1908 
1909 DeclRefExpr *
1910 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1911                        const DeclarationNameInfo &NameInfo,
1912                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1913                        SourceLocation TemplateKWLoc,
1914                        const TemplateArgumentListInfo *TemplateArgs) {
1915   NestedNameSpecifierLoc NNS =
1916       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1917   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1918                           TemplateArgs);
1919 }
1920 
1921 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1922   // A declaration named in an unevaluated operand never constitutes an odr-use.
1923   if (isUnevaluatedContext())
1924     return NOUR_Unevaluated;
1925 
1926   // C++2a [basic.def.odr]p4:
1927   //   A variable x whose name appears as a potentially-evaluated expression e
1928   //   is odr-used by e unless [...] x is a reference that is usable in
1929   //   constant expressions.
1930   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1931     if (VD->getType()->isReferenceType() &&
1932         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1933         VD->isUsableInConstantExpressions(Context))
1934       return NOUR_Constant;
1935   }
1936 
1937   // All remaining non-variable cases constitute an odr-use. For variables, we
1938   // need to wait and see how the expression is used.
1939   return NOUR_None;
1940 }
1941 
1942 /// BuildDeclRefExpr - Build an expression that references a
1943 /// declaration that does not require a closure capture.
1944 DeclRefExpr *
1945 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1946                        const DeclarationNameInfo &NameInfo,
1947                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1948                        SourceLocation TemplateKWLoc,
1949                        const TemplateArgumentListInfo *TemplateArgs) {
1950   bool RefersToCapturedVariable =
1951       isa<VarDecl>(D) &&
1952       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1953 
1954   DeclRefExpr *E = DeclRefExpr::Create(
1955       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1956       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1957   MarkDeclRefReferenced(E);
1958 
1959   // C++ [except.spec]p17:
1960   //   An exception-specification is considered to be needed when:
1961   //   - in an expression, the function is the unique lookup result or
1962   //     the selected member of a set of overloaded functions.
1963   //
1964   // We delay doing this until after we've built the function reference and
1965   // marked it as used so that:
1966   //  a) if the function is defaulted, we get errors from defining it before /
1967   //     instead of errors from computing its exception specification, and
1968   //  b) if the function is a defaulted comparison, we can use the body we
1969   //     build when defining it as input to the exception specification
1970   //     computation rather than computing a new body.
1971   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1972     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1973       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1974         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1975     }
1976   }
1977 
1978   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1979       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1980       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1981     getCurFunction()->recordUseOfWeak(E);
1982 
1983   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1984   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1985     FD = IFD->getAnonField();
1986   if (FD) {
1987     UnusedPrivateFields.remove(FD);
1988     // Just in case we're building an illegal pointer-to-member.
1989     if (FD->isBitField())
1990       E->setObjectKind(OK_BitField);
1991   }
1992 
1993   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1994   // designates a bit-field.
1995   if (auto *BD = dyn_cast<BindingDecl>(D))
1996     if (auto *BE = BD->getBinding())
1997       E->setObjectKind(BE->getObjectKind());
1998 
1999   return E;
2000 }
2001 
2002 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2003 /// possibly a list of template arguments.
2004 ///
2005 /// If this produces template arguments, it is permitted to call
2006 /// DecomposeTemplateName.
2007 ///
2008 /// This actually loses a lot of source location information for
2009 /// non-standard name kinds; we should consider preserving that in
2010 /// some way.
2011 void
2012 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2013                              TemplateArgumentListInfo &Buffer,
2014                              DeclarationNameInfo &NameInfo,
2015                              const TemplateArgumentListInfo *&TemplateArgs) {
2016   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2017     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2018     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2019 
2020     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2021                                        Id.TemplateId->NumArgs);
2022     translateTemplateArguments(TemplateArgsPtr, Buffer);
2023 
2024     TemplateName TName = Id.TemplateId->Template.get();
2025     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2026     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2027     TemplateArgs = &Buffer;
2028   } else {
2029     NameInfo = GetNameFromUnqualifiedId(Id);
2030     TemplateArgs = nullptr;
2031   }
2032 }
2033 
2034 static void emitEmptyLookupTypoDiagnostic(
2035     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2036     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2037     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2038   DeclContext *Ctx =
2039       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2040   if (!TC) {
2041     // Emit a special diagnostic for failed member lookups.
2042     // FIXME: computing the declaration context might fail here (?)
2043     if (Ctx)
2044       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2045                                                  << SS.getRange();
2046     else
2047       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2048     return;
2049   }
2050 
2051   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2052   bool DroppedSpecifier =
2053       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2054   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2055                         ? diag::note_implicit_param_decl
2056                         : diag::note_previous_decl;
2057   if (!Ctx)
2058     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2059                          SemaRef.PDiag(NoteID));
2060   else
2061     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2062                                  << Typo << Ctx << DroppedSpecifier
2063                                  << SS.getRange(),
2064                          SemaRef.PDiag(NoteID));
2065 }
2066 
2067 /// Diagnose an empty lookup.
2068 ///
2069 /// \return false if new lookup candidates were found
2070 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2071                                CorrectionCandidateCallback &CCC,
2072                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2073                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2074   DeclarationName Name = R.getLookupName();
2075 
2076   unsigned diagnostic = diag::err_undeclared_var_use;
2077   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2078   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2079       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2080       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2081     diagnostic = diag::err_undeclared_use;
2082     diagnostic_suggest = diag::err_undeclared_use_suggest;
2083   }
2084 
2085   // If the original lookup was an unqualified lookup, fake an
2086   // unqualified lookup.  This is useful when (for example) the
2087   // original lookup would not have found something because it was a
2088   // dependent name.
2089   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2090   while (DC) {
2091     if (isa<CXXRecordDecl>(DC)) {
2092       LookupQualifiedName(R, DC);
2093 
2094       if (!R.empty()) {
2095         // Don't give errors about ambiguities in this lookup.
2096         R.suppressDiagnostics();
2097 
2098         // During a default argument instantiation the CurContext points
2099         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2100         // function parameter list, hence add an explicit check.
2101         bool isDefaultArgument =
2102             !CodeSynthesisContexts.empty() &&
2103             CodeSynthesisContexts.back().Kind ==
2104                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2105         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2106         bool isInstance = CurMethod &&
2107                           CurMethod->isInstance() &&
2108                           DC == CurMethod->getParent() && !isDefaultArgument;
2109 
2110         // Give a code modification hint to insert 'this->'.
2111         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2112         // Actually quite difficult!
2113         if (getLangOpts().MSVCCompat)
2114           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2115         if (isInstance) {
2116           Diag(R.getNameLoc(), diagnostic) << Name
2117             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2118           CheckCXXThisCapture(R.getNameLoc());
2119         } else {
2120           Diag(R.getNameLoc(), diagnostic) << Name;
2121         }
2122 
2123         // Do we really want to note all of these?
2124         for (NamedDecl *D : R)
2125           Diag(D->getLocation(), diag::note_dependent_var_use);
2126 
2127         // Return true if we are inside a default argument instantiation
2128         // and the found name refers to an instance member function, otherwise
2129         // the function calling DiagnoseEmptyLookup will try to create an
2130         // implicit member call and this is wrong for default argument.
2131         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2132           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2133           return true;
2134         }
2135 
2136         // Tell the callee to try to recover.
2137         return false;
2138       }
2139 
2140       R.clear();
2141     }
2142 
2143     DC = DC->getLookupParent();
2144   }
2145 
2146   // We didn't find anything, so try to correct for a typo.
2147   TypoCorrection Corrected;
2148   if (S && Out) {
2149     SourceLocation TypoLoc = R.getNameLoc();
2150     assert(!ExplicitTemplateArgs &&
2151            "Diagnosing an empty lookup with explicit template args!");
2152     *Out = CorrectTypoDelayed(
2153         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2154         [=](const TypoCorrection &TC) {
2155           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2156                                         diagnostic, diagnostic_suggest);
2157         },
2158         nullptr, CTK_ErrorRecovery);
2159     if (*Out)
2160       return true;
2161   } else if (S &&
2162              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2163                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2164     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2165     bool DroppedSpecifier =
2166         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2167     R.setLookupName(Corrected.getCorrection());
2168 
2169     bool AcceptableWithRecovery = false;
2170     bool AcceptableWithoutRecovery = false;
2171     NamedDecl *ND = Corrected.getFoundDecl();
2172     if (ND) {
2173       if (Corrected.isOverloaded()) {
2174         OverloadCandidateSet OCS(R.getNameLoc(),
2175                                  OverloadCandidateSet::CSK_Normal);
2176         OverloadCandidateSet::iterator Best;
2177         for (NamedDecl *CD : Corrected) {
2178           if (FunctionTemplateDecl *FTD =
2179                    dyn_cast<FunctionTemplateDecl>(CD))
2180             AddTemplateOverloadCandidate(
2181                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2182                 Args, OCS);
2183           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2184             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2185               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2186                                    Args, OCS);
2187         }
2188         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2189         case OR_Success:
2190           ND = Best->FoundDecl;
2191           Corrected.setCorrectionDecl(ND);
2192           break;
2193         default:
2194           // FIXME: Arbitrarily pick the first declaration for the note.
2195           Corrected.setCorrectionDecl(ND);
2196           break;
2197         }
2198       }
2199       R.addDecl(ND);
2200       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2201         CXXRecordDecl *Record = nullptr;
2202         if (Corrected.getCorrectionSpecifier()) {
2203           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2204           Record = Ty->getAsCXXRecordDecl();
2205         }
2206         if (!Record)
2207           Record = cast<CXXRecordDecl>(
2208               ND->getDeclContext()->getRedeclContext());
2209         R.setNamingClass(Record);
2210       }
2211 
2212       auto *UnderlyingND = ND->getUnderlyingDecl();
2213       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2214                                isa<FunctionTemplateDecl>(UnderlyingND);
2215       // FIXME: If we ended up with a typo for a type name or
2216       // Objective-C class name, we're in trouble because the parser
2217       // is in the wrong place to recover. Suggest the typo
2218       // correction, but don't make it a fix-it since we're not going
2219       // to recover well anyway.
2220       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2221                                   getAsTypeTemplateDecl(UnderlyingND) ||
2222                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2223     } else {
2224       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2225       // because we aren't able to recover.
2226       AcceptableWithoutRecovery = true;
2227     }
2228 
2229     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2230       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2231                             ? diag::note_implicit_param_decl
2232                             : diag::note_previous_decl;
2233       if (SS.isEmpty())
2234         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2235                      PDiag(NoteID), AcceptableWithRecovery);
2236       else
2237         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2238                                   << Name << computeDeclContext(SS, false)
2239                                   << DroppedSpecifier << SS.getRange(),
2240                      PDiag(NoteID), AcceptableWithRecovery);
2241 
2242       // Tell the callee whether to try to recover.
2243       return !AcceptableWithRecovery;
2244     }
2245   }
2246   R.clear();
2247 
2248   // Emit a special diagnostic for failed member lookups.
2249   // FIXME: computing the declaration context might fail here (?)
2250   if (!SS.isEmpty()) {
2251     Diag(R.getNameLoc(), diag::err_no_member)
2252       << Name << computeDeclContext(SS, false)
2253       << SS.getRange();
2254     return true;
2255   }
2256 
2257   // Give up, we can't recover.
2258   Diag(R.getNameLoc(), diagnostic) << Name;
2259   return true;
2260 }
2261 
2262 /// In Microsoft mode, if we are inside a template class whose parent class has
2263 /// dependent base classes, and we can't resolve an unqualified identifier, then
2264 /// assume the identifier is a member of a dependent base class.  We can only
2265 /// recover successfully in static methods, instance methods, and other contexts
2266 /// where 'this' is available.  This doesn't precisely match MSVC's
2267 /// instantiation model, but it's close enough.
2268 static Expr *
2269 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2270                                DeclarationNameInfo &NameInfo,
2271                                SourceLocation TemplateKWLoc,
2272                                const TemplateArgumentListInfo *TemplateArgs) {
2273   // Only try to recover from lookup into dependent bases in static methods or
2274   // contexts where 'this' is available.
2275   QualType ThisType = S.getCurrentThisType();
2276   const CXXRecordDecl *RD = nullptr;
2277   if (!ThisType.isNull())
2278     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2279   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2280     RD = MD->getParent();
2281   if (!RD || !RD->hasAnyDependentBases())
2282     return nullptr;
2283 
2284   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2285   // is available, suggest inserting 'this->' as a fixit.
2286   SourceLocation Loc = NameInfo.getLoc();
2287   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2288   DB << NameInfo.getName() << RD;
2289 
2290   if (!ThisType.isNull()) {
2291     DB << FixItHint::CreateInsertion(Loc, "this->");
2292     return CXXDependentScopeMemberExpr::Create(
2293         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2294         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2295         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2296   }
2297 
2298   // Synthesize a fake NNS that points to the derived class.  This will
2299   // perform name lookup during template instantiation.
2300   CXXScopeSpec SS;
2301   auto *NNS =
2302       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2303   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2304   return DependentScopeDeclRefExpr::Create(
2305       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2306       TemplateArgs);
2307 }
2308 
2309 ExprResult
2310 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2311                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2312                         bool HasTrailingLParen, bool IsAddressOfOperand,
2313                         CorrectionCandidateCallback *CCC,
2314                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2315   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2316          "cannot be direct & operand and have a trailing lparen");
2317   if (SS.isInvalid())
2318     return ExprError();
2319 
2320   TemplateArgumentListInfo TemplateArgsBuffer;
2321 
2322   // Decompose the UnqualifiedId into the following data.
2323   DeclarationNameInfo NameInfo;
2324   const TemplateArgumentListInfo *TemplateArgs;
2325   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2326 
2327   DeclarationName Name = NameInfo.getName();
2328   IdentifierInfo *II = Name.getAsIdentifierInfo();
2329   SourceLocation NameLoc = NameInfo.getLoc();
2330 
2331   if (II && II->isEditorPlaceholder()) {
2332     // FIXME: When typed placeholders are supported we can create a typed
2333     // placeholder expression node.
2334     return ExprError();
2335   }
2336 
2337   // C++ [temp.dep.expr]p3:
2338   //   An id-expression is type-dependent if it contains:
2339   //     -- an identifier that was declared with a dependent type,
2340   //        (note: handled after lookup)
2341   //     -- a template-id that is dependent,
2342   //        (note: handled in BuildTemplateIdExpr)
2343   //     -- a conversion-function-id that specifies a dependent type,
2344   //     -- a nested-name-specifier that contains a class-name that
2345   //        names a dependent type.
2346   // Determine whether this is a member of an unknown specialization;
2347   // we need to handle these differently.
2348   bool DependentID = false;
2349   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2350       Name.getCXXNameType()->isDependentType()) {
2351     DependentID = true;
2352   } else if (SS.isSet()) {
2353     if (DeclContext *DC = computeDeclContext(SS, false)) {
2354       if (RequireCompleteDeclContext(SS, DC))
2355         return ExprError();
2356     } else {
2357       DependentID = true;
2358     }
2359   }
2360 
2361   if (DependentID)
2362     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2363                                       IsAddressOfOperand, TemplateArgs);
2364 
2365   // Perform the required lookup.
2366   LookupResult R(*this, NameInfo,
2367                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2368                      ? LookupObjCImplicitSelfParam
2369                      : LookupOrdinaryName);
2370   if (TemplateKWLoc.isValid() || TemplateArgs) {
2371     // Lookup the template name again to correctly establish the context in
2372     // which it was found. This is really unfortunate as we already did the
2373     // lookup to determine that it was a template name in the first place. If
2374     // this becomes a performance hit, we can work harder to preserve those
2375     // results until we get here but it's likely not worth it.
2376     bool MemberOfUnknownSpecialization;
2377     AssumedTemplateKind AssumedTemplate;
2378     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2379                            MemberOfUnknownSpecialization, TemplateKWLoc,
2380                            &AssumedTemplate))
2381       return ExprError();
2382 
2383     if (MemberOfUnknownSpecialization ||
2384         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2385       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2386                                         IsAddressOfOperand, TemplateArgs);
2387   } else {
2388     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2389     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2390 
2391     // If the result might be in a dependent base class, this is a dependent
2392     // id-expression.
2393     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2394       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2395                                         IsAddressOfOperand, TemplateArgs);
2396 
2397     // If this reference is in an Objective-C method, then we need to do
2398     // some special Objective-C lookup, too.
2399     if (IvarLookupFollowUp) {
2400       ExprResult E(LookupInObjCMethod(R, S, II, true));
2401       if (E.isInvalid())
2402         return ExprError();
2403 
2404       if (Expr *Ex = E.getAs<Expr>())
2405         return Ex;
2406     }
2407   }
2408 
2409   if (R.isAmbiguous())
2410     return ExprError();
2411 
2412   // This could be an implicitly declared function reference (legal in C90,
2413   // extension in C99, forbidden in C++).
2414   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2415     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2416     if (D) R.addDecl(D);
2417   }
2418 
2419   // Determine whether this name might be a candidate for
2420   // argument-dependent lookup.
2421   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2422 
2423   if (R.empty() && !ADL) {
2424     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2425       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2426                                                    TemplateKWLoc, TemplateArgs))
2427         return E;
2428     }
2429 
2430     // Don't diagnose an empty lookup for inline assembly.
2431     if (IsInlineAsmIdentifier)
2432       return ExprError();
2433 
2434     // If this name wasn't predeclared and if this is not a function
2435     // call, diagnose the problem.
2436     TypoExpr *TE = nullptr;
2437     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2438                                                        : nullptr);
2439     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2440     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2441            "Typo correction callback misconfigured");
2442     if (CCC) {
2443       // Make sure the callback knows what the typo being diagnosed is.
2444       CCC->setTypoName(II);
2445       if (SS.isValid())
2446         CCC->setTypoNNS(SS.getScopeRep());
2447     }
2448     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2449     // a template name, but we happen to have always already looked up the name
2450     // before we get here if it must be a template name.
2451     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2452                             None, &TE)) {
2453       if (TE && KeywordReplacement) {
2454         auto &State = getTypoExprState(TE);
2455         auto BestTC = State.Consumer->getNextCorrection();
2456         if (BestTC.isKeyword()) {
2457           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2458           if (State.DiagHandler)
2459             State.DiagHandler(BestTC);
2460           KeywordReplacement->startToken();
2461           KeywordReplacement->setKind(II->getTokenID());
2462           KeywordReplacement->setIdentifierInfo(II);
2463           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2464           // Clean up the state associated with the TypoExpr, since it has
2465           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2466           clearDelayedTypo(TE);
2467           // Signal that a correction to a keyword was performed by returning a
2468           // valid-but-null ExprResult.
2469           return (Expr*)nullptr;
2470         }
2471         State.Consumer->resetCorrectionStream();
2472       }
2473       return TE ? TE : ExprError();
2474     }
2475 
2476     assert(!R.empty() &&
2477            "DiagnoseEmptyLookup returned false but added no results");
2478 
2479     // If we found an Objective-C instance variable, let
2480     // LookupInObjCMethod build the appropriate expression to
2481     // reference the ivar.
2482     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2483       R.clear();
2484       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2485       // In a hopelessly buggy code, Objective-C instance variable
2486       // lookup fails and no expression will be built to reference it.
2487       if (!E.isInvalid() && !E.get())
2488         return ExprError();
2489       return E;
2490     }
2491   }
2492 
2493   // This is guaranteed from this point on.
2494   assert(!R.empty() || ADL);
2495 
2496   // Check whether this might be a C++ implicit instance member access.
2497   // C++ [class.mfct.non-static]p3:
2498   //   When an id-expression that is not part of a class member access
2499   //   syntax and not used to form a pointer to member is used in the
2500   //   body of a non-static member function of class X, if name lookup
2501   //   resolves the name in the id-expression to a non-static non-type
2502   //   member of some class C, the id-expression is transformed into a
2503   //   class member access expression using (*this) as the
2504   //   postfix-expression to the left of the . operator.
2505   //
2506   // But we don't actually need to do this for '&' operands if R
2507   // resolved to a function or overloaded function set, because the
2508   // expression is ill-formed if it actually works out to be a
2509   // non-static member function:
2510   //
2511   // C++ [expr.ref]p4:
2512   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2513   //   [t]he expression can be used only as the left-hand operand of a
2514   //   member function call.
2515   //
2516   // There are other safeguards against such uses, but it's important
2517   // to get this right here so that we don't end up making a
2518   // spuriously dependent expression if we're inside a dependent
2519   // instance method.
2520   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2521     bool MightBeImplicitMember;
2522     if (!IsAddressOfOperand)
2523       MightBeImplicitMember = true;
2524     else if (!SS.isEmpty())
2525       MightBeImplicitMember = false;
2526     else if (R.isOverloadedResult())
2527       MightBeImplicitMember = false;
2528     else if (R.isUnresolvableResult())
2529       MightBeImplicitMember = true;
2530     else
2531       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2532                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2533                               isa<MSPropertyDecl>(R.getFoundDecl());
2534 
2535     if (MightBeImplicitMember)
2536       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2537                                              R, TemplateArgs, S);
2538   }
2539 
2540   if (TemplateArgs || TemplateKWLoc.isValid()) {
2541 
2542     // In C++1y, if this is a variable template id, then check it
2543     // in BuildTemplateIdExpr().
2544     // The single lookup result must be a variable template declaration.
2545     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2546         Id.TemplateId->Kind == TNK_Var_template) {
2547       assert(R.getAsSingle<VarTemplateDecl>() &&
2548              "There should only be one declaration found.");
2549     }
2550 
2551     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2552   }
2553 
2554   return BuildDeclarationNameExpr(SS, R, ADL);
2555 }
2556 
2557 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2558 /// declaration name, generally during template instantiation.
2559 /// There's a large number of things which don't need to be done along
2560 /// this path.
2561 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2562     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2563     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2564   DeclContext *DC = computeDeclContext(SS, false);
2565   if (!DC)
2566     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2567                                      NameInfo, /*TemplateArgs=*/nullptr);
2568 
2569   if (RequireCompleteDeclContext(SS, DC))
2570     return ExprError();
2571 
2572   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2573   LookupQualifiedName(R, DC);
2574 
2575   if (R.isAmbiguous())
2576     return ExprError();
2577 
2578   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2579     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2580                                      NameInfo, /*TemplateArgs=*/nullptr);
2581 
2582   if (R.empty()) {
2583     Diag(NameInfo.getLoc(), diag::err_no_member)
2584       << NameInfo.getName() << DC << SS.getRange();
2585     return ExprError();
2586   }
2587 
2588   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2589     // Diagnose a missing typename if this resolved unambiguously to a type in
2590     // a dependent context.  If we can recover with a type, downgrade this to
2591     // a warning in Microsoft compatibility mode.
2592     unsigned DiagID = diag::err_typename_missing;
2593     if (RecoveryTSI && getLangOpts().MSVCCompat)
2594       DiagID = diag::ext_typename_missing;
2595     SourceLocation Loc = SS.getBeginLoc();
2596     auto D = Diag(Loc, DiagID);
2597     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2598       << SourceRange(Loc, NameInfo.getEndLoc());
2599 
2600     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2601     // context.
2602     if (!RecoveryTSI)
2603       return ExprError();
2604 
2605     // Only issue the fixit if we're prepared to recover.
2606     D << FixItHint::CreateInsertion(Loc, "typename ");
2607 
2608     // Recover by pretending this was an elaborated type.
2609     QualType Ty = Context.getTypeDeclType(TD);
2610     TypeLocBuilder TLB;
2611     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2612 
2613     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2614     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2615     QTL.setElaboratedKeywordLoc(SourceLocation());
2616     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2617 
2618     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2619 
2620     return ExprEmpty();
2621   }
2622 
2623   // Defend against this resolving to an implicit member access. We usually
2624   // won't get here if this might be a legitimate a class member (we end up in
2625   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2626   // a pointer-to-member or in an unevaluated context in C++11.
2627   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2628     return BuildPossibleImplicitMemberExpr(SS,
2629                                            /*TemplateKWLoc=*/SourceLocation(),
2630                                            R, /*TemplateArgs=*/nullptr, S);
2631 
2632   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2633 }
2634 
2635 /// The parser has read a name in, and Sema has detected that we're currently
2636 /// inside an ObjC method. Perform some additional checks and determine if we
2637 /// should form a reference to an ivar.
2638 ///
2639 /// Ideally, most of this would be done by lookup, but there's
2640 /// actually quite a lot of extra work involved.
2641 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2642                                         IdentifierInfo *II) {
2643   SourceLocation Loc = Lookup.getNameLoc();
2644   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2645 
2646   // Check for error condition which is already reported.
2647   if (!CurMethod)
2648     return DeclResult(true);
2649 
2650   // There are two cases to handle here.  1) scoped lookup could have failed,
2651   // in which case we should look for an ivar.  2) scoped lookup could have
2652   // found a decl, but that decl is outside the current instance method (i.e.
2653   // a global variable).  In these two cases, we do a lookup for an ivar with
2654   // this name, if the lookup sucedes, we replace it our current decl.
2655 
2656   // If we're in a class method, we don't normally want to look for
2657   // ivars.  But if we don't find anything else, and there's an
2658   // ivar, that's an error.
2659   bool IsClassMethod = CurMethod->isClassMethod();
2660 
2661   bool LookForIvars;
2662   if (Lookup.empty())
2663     LookForIvars = true;
2664   else if (IsClassMethod)
2665     LookForIvars = false;
2666   else
2667     LookForIvars = (Lookup.isSingleResult() &&
2668                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2669   ObjCInterfaceDecl *IFace = nullptr;
2670   if (LookForIvars) {
2671     IFace = CurMethod->getClassInterface();
2672     ObjCInterfaceDecl *ClassDeclared;
2673     ObjCIvarDecl *IV = nullptr;
2674     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2675       // Diagnose using an ivar in a class method.
2676       if (IsClassMethod) {
2677         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2678         return DeclResult(true);
2679       }
2680 
2681       // Diagnose the use of an ivar outside of the declaring class.
2682       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2683           !declaresSameEntity(ClassDeclared, IFace) &&
2684           !getLangOpts().DebuggerSupport)
2685         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2686 
2687       // Success.
2688       return IV;
2689     }
2690   } else if (CurMethod->isInstanceMethod()) {
2691     // We should warn if a local variable hides an ivar.
2692     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2693       ObjCInterfaceDecl *ClassDeclared;
2694       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2695         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2696             declaresSameEntity(IFace, ClassDeclared))
2697           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2698       }
2699     }
2700   } else if (Lookup.isSingleResult() &&
2701              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2702     // If accessing a stand-alone ivar in a class method, this is an error.
2703     if (const ObjCIvarDecl *IV =
2704             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2705       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2706       return DeclResult(true);
2707     }
2708   }
2709 
2710   // Didn't encounter an error, didn't find an ivar.
2711   return DeclResult(false);
2712 }
2713 
2714 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2715                                   ObjCIvarDecl *IV) {
2716   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2717   assert(CurMethod && CurMethod->isInstanceMethod() &&
2718          "should not reference ivar from this context");
2719 
2720   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2721   assert(IFace && "should not reference ivar from this context");
2722 
2723   // If we're referencing an invalid decl, just return this as a silent
2724   // error node.  The error diagnostic was already emitted on the decl.
2725   if (IV->isInvalidDecl())
2726     return ExprError();
2727 
2728   // Check if referencing a field with __attribute__((deprecated)).
2729   if (DiagnoseUseOfDecl(IV, Loc))
2730     return ExprError();
2731 
2732   // FIXME: This should use a new expr for a direct reference, don't
2733   // turn this into Self->ivar, just return a BareIVarExpr or something.
2734   IdentifierInfo &II = Context.Idents.get("self");
2735   UnqualifiedId SelfName;
2736   SelfName.setIdentifier(&II, SourceLocation());
2737   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2738   CXXScopeSpec SelfScopeSpec;
2739   SourceLocation TemplateKWLoc;
2740   ExprResult SelfExpr =
2741       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2742                         /*HasTrailingLParen=*/false,
2743                         /*IsAddressOfOperand=*/false);
2744   if (SelfExpr.isInvalid())
2745     return ExprError();
2746 
2747   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2748   if (SelfExpr.isInvalid())
2749     return ExprError();
2750 
2751   MarkAnyDeclReferenced(Loc, IV, true);
2752 
2753   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2754   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2755       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2756     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2757 
2758   ObjCIvarRefExpr *Result = new (Context)
2759       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2760                       IV->getLocation(), SelfExpr.get(), true, true);
2761 
2762   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2763     if (!isUnevaluatedContext() &&
2764         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2765       getCurFunction()->recordUseOfWeak(Result);
2766   }
2767   if (getLangOpts().ObjCAutoRefCount)
2768     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2769       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2770 
2771   return Result;
2772 }
2773 
2774 /// The parser has read a name in, and Sema has detected that we're currently
2775 /// inside an ObjC method. Perform some additional checks and determine if we
2776 /// should form a reference to an ivar. If so, build an expression referencing
2777 /// that ivar.
2778 ExprResult
2779 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2780                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2781   // FIXME: Integrate this lookup step into LookupParsedName.
2782   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2783   if (Ivar.isInvalid())
2784     return ExprError();
2785   if (Ivar.isUsable())
2786     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2787                             cast<ObjCIvarDecl>(Ivar.get()));
2788 
2789   if (Lookup.empty() && II && AllowBuiltinCreation)
2790     LookupBuiltin(Lookup);
2791 
2792   // Sentinel value saying that we didn't do anything special.
2793   return ExprResult(false);
2794 }
2795 
2796 /// Cast a base object to a member's actual type.
2797 ///
2798 /// Logically this happens in three phases:
2799 ///
2800 /// * First we cast from the base type to the naming class.
2801 ///   The naming class is the class into which we were looking
2802 ///   when we found the member;  it's the qualifier type if a
2803 ///   qualifier was provided, and otherwise it's the base type.
2804 ///
2805 /// * Next we cast from the naming class to the declaring class.
2806 ///   If the member we found was brought into a class's scope by
2807 ///   a using declaration, this is that class;  otherwise it's
2808 ///   the class declaring the member.
2809 ///
2810 /// * Finally we cast from the declaring class to the "true"
2811 ///   declaring class of the member.  This conversion does not
2812 ///   obey access control.
2813 ExprResult
2814 Sema::PerformObjectMemberConversion(Expr *From,
2815                                     NestedNameSpecifier *Qualifier,
2816                                     NamedDecl *FoundDecl,
2817                                     NamedDecl *Member) {
2818   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2819   if (!RD)
2820     return From;
2821 
2822   QualType DestRecordType;
2823   QualType DestType;
2824   QualType FromRecordType;
2825   QualType FromType = From->getType();
2826   bool PointerConversions = false;
2827   if (isa<FieldDecl>(Member)) {
2828     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2829     auto FromPtrType = FromType->getAs<PointerType>();
2830     DestRecordType = Context.getAddrSpaceQualType(
2831         DestRecordType, FromPtrType
2832                             ? FromType->getPointeeType().getAddressSpace()
2833                             : FromType.getAddressSpace());
2834 
2835     if (FromPtrType) {
2836       DestType = Context.getPointerType(DestRecordType);
2837       FromRecordType = FromPtrType->getPointeeType();
2838       PointerConversions = true;
2839     } else {
2840       DestType = DestRecordType;
2841       FromRecordType = FromType;
2842     }
2843   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2844     if (Method->isStatic())
2845       return From;
2846 
2847     DestType = Method->getThisType();
2848     DestRecordType = DestType->getPointeeType();
2849 
2850     if (FromType->getAs<PointerType>()) {
2851       FromRecordType = FromType->getPointeeType();
2852       PointerConversions = true;
2853     } else {
2854       FromRecordType = FromType;
2855       DestType = DestRecordType;
2856     }
2857 
2858     LangAS FromAS = FromRecordType.getAddressSpace();
2859     LangAS DestAS = DestRecordType.getAddressSpace();
2860     if (FromAS != DestAS) {
2861       QualType FromRecordTypeWithoutAS =
2862           Context.removeAddrSpaceQualType(FromRecordType);
2863       QualType FromTypeWithDestAS =
2864           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2865       if (PointerConversions)
2866         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2867       From = ImpCastExprToType(From, FromTypeWithDestAS,
2868                                CK_AddressSpaceConversion, From->getValueKind())
2869                  .get();
2870     }
2871   } else {
2872     // No conversion necessary.
2873     return From;
2874   }
2875 
2876   if (DestType->isDependentType() || FromType->isDependentType())
2877     return From;
2878 
2879   // If the unqualified types are the same, no conversion is necessary.
2880   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2881     return From;
2882 
2883   SourceRange FromRange = From->getSourceRange();
2884   SourceLocation FromLoc = FromRange.getBegin();
2885 
2886   ExprValueKind VK = From->getValueKind();
2887 
2888   // C++ [class.member.lookup]p8:
2889   //   [...] Ambiguities can often be resolved by qualifying a name with its
2890   //   class name.
2891   //
2892   // If the member was a qualified name and the qualified referred to a
2893   // specific base subobject type, we'll cast to that intermediate type
2894   // first and then to the object in which the member is declared. That allows
2895   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2896   //
2897   //   class Base { public: int x; };
2898   //   class Derived1 : public Base { };
2899   //   class Derived2 : public Base { };
2900   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2901   //
2902   //   void VeryDerived::f() {
2903   //     x = 17; // error: ambiguous base subobjects
2904   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2905   //   }
2906   if (Qualifier && Qualifier->getAsType()) {
2907     QualType QType = QualType(Qualifier->getAsType(), 0);
2908     assert(QType->isRecordType() && "lookup done with non-record type");
2909 
2910     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2911 
2912     // In C++98, the qualifier type doesn't actually have to be a base
2913     // type of the object type, in which case we just ignore it.
2914     // Otherwise build the appropriate casts.
2915     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2916       CXXCastPath BasePath;
2917       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2918                                        FromLoc, FromRange, &BasePath))
2919         return ExprError();
2920 
2921       if (PointerConversions)
2922         QType = Context.getPointerType(QType);
2923       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2924                                VK, &BasePath).get();
2925 
2926       FromType = QType;
2927       FromRecordType = QRecordType;
2928 
2929       // If the qualifier type was the same as the destination type,
2930       // we're done.
2931       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2932         return From;
2933     }
2934   }
2935 
2936   bool IgnoreAccess = false;
2937 
2938   // If we actually found the member through a using declaration, cast
2939   // down to the using declaration's type.
2940   //
2941   // Pointer equality is fine here because only one declaration of a
2942   // class ever has member declarations.
2943   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2944     assert(isa<UsingShadowDecl>(FoundDecl));
2945     QualType URecordType = Context.getTypeDeclType(
2946                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2947 
2948     // We only need to do this if the naming-class to declaring-class
2949     // conversion is non-trivial.
2950     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2951       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2952       CXXCastPath BasePath;
2953       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2954                                        FromLoc, FromRange, &BasePath))
2955         return ExprError();
2956 
2957       QualType UType = URecordType;
2958       if (PointerConversions)
2959         UType = Context.getPointerType(UType);
2960       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2961                                VK, &BasePath).get();
2962       FromType = UType;
2963       FromRecordType = URecordType;
2964     }
2965 
2966     // We don't do access control for the conversion from the
2967     // declaring class to the true declaring class.
2968     IgnoreAccess = true;
2969   }
2970 
2971   CXXCastPath BasePath;
2972   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2973                                    FromLoc, FromRange, &BasePath,
2974                                    IgnoreAccess))
2975     return ExprError();
2976 
2977   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2978                            VK, &BasePath);
2979 }
2980 
2981 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2982                                       const LookupResult &R,
2983                                       bool HasTrailingLParen) {
2984   // Only when used directly as the postfix-expression of a call.
2985   if (!HasTrailingLParen)
2986     return false;
2987 
2988   // Never if a scope specifier was provided.
2989   if (SS.isSet())
2990     return false;
2991 
2992   // Only in C++ or ObjC++.
2993   if (!getLangOpts().CPlusPlus)
2994     return false;
2995 
2996   // Turn off ADL when we find certain kinds of declarations during
2997   // normal lookup:
2998   for (NamedDecl *D : R) {
2999     // C++0x [basic.lookup.argdep]p3:
3000     //     -- a declaration of a class member
3001     // Since using decls preserve this property, we check this on the
3002     // original decl.
3003     if (D->isCXXClassMember())
3004       return false;
3005 
3006     // C++0x [basic.lookup.argdep]p3:
3007     //     -- a block-scope function declaration that is not a
3008     //        using-declaration
3009     // NOTE: we also trigger this for function templates (in fact, we
3010     // don't check the decl type at all, since all other decl types
3011     // turn off ADL anyway).
3012     if (isa<UsingShadowDecl>(D))
3013       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3014     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3015       return false;
3016 
3017     // C++0x [basic.lookup.argdep]p3:
3018     //     -- a declaration that is neither a function or a function
3019     //        template
3020     // And also for builtin functions.
3021     if (isa<FunctionDecl>(D)) {
3022       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3023 
3024       // But also builtin functions.
3025       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3026         return false;
3027     } else if (!isa<FunctionTemplateDecl>(D))
3028       return false;
3029   }
3030 
3031   return true;
3032 }
3033 
3034 
3035 /// Diagnoses obvious problems with the use of the given declaration
3036 /// as an expression.  This is only actually called for lookups that
3037 /// were not overloaded, and it doesn't promise that the declaration
3038 /// will in fact be used.
3039 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3040   if (D->isInvalidDecl())
3041     return true;
3042 
3043   if (isa<TypedefNameDecl>(D)) {
3044     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3045     return true;
3046   }
3047 
3048   if (isa<ObjCInterfaceDecl>(D)) {
3049     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3050     return true;
3051   }
3052 
3053   if (isa<NamespaceDecl>(D)) {
3054     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3055     return true;
3056   }
3057 
3058   return false;
3059 }
3060 
3061 // Certain multiversion types should be treated as overloaded even when there is
3062 // only one result.
3063 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3064   assert(R.isSingleResult() && "Expected only a single result");
3065   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3066   return FD &&
3067          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3068 }
3069 
3070 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3071                                           LookupResult &R, bool NeedsADL,
3072                                           bool AcceptInvalidDecl) {
3073   // If this is a single, fully-resolved result and we don't need ADL,
3074   // just build an ordinary singleton decl ref.
3075   if (!NeedsADL && R.isSingleResult() &&
3076       !R.getAsSingle<FunctionTemplateDecl>() &&
3077       !ShouldLookupResultBeMultiVersionOverload(R))
3078     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3079                                     R.getRepresentativeDecl(), nullptr,
3080                                     AcceptInvalidDecl);
3081 
3082   // We only need to check the declaration if there's exactly one
3083   // result, because in the overloaded case the results can only be
3084   // functions and function templates.
3085   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3086       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3087     return ExprError();
3088 
3089   // Otherwise, just build an unresolved lookup expression.  Suppress
3090   // any lookup-related diagnostics; we'll hash these out later, when
3091   // we've picked a target.
3092   R.suppressDiagnostics();
3093 
3094   UnresolvedLookupExpr *ULE
3095     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3096                                    SS.getWithLocInContext(Context),
3097                                    R.getLookupNameInfo(),
3098                                    NeedsADL, R.isOverloadedResult(),
3099                                    R.begin(), R.end());
3100 
3101   return ULE;
3102 }
3103 
3104 static void
3105 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3106                                    ValueDecl *var, DeclContext *DC);
3107 
3108 /// Complete semantic analysis for a reference to the given declaration.
3109 ExprResult Sema::BuildDeclarationNameExpr(
3110     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3111     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3112     bool AcceptInvalidDecl) {
3113   assert(D && "Cannot refer to a NULL declaration");
3114   assert(!isa<FunctionTemplateDecl>(D) &&
3115          "Cannot refer unambiguously to a function template");
3116 
3117   SourceLocation Loc = NameInfo.getLoc();
3118   if (CheckDeclInExpr(*this, Loc, D))
3119     return ExprError();
3120 
3121   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3122     // Specifically diagnose references to class templates that are missing
3123     // a template argument list.
3124     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3125     return ExprError();
3126   }
3127 
3128   // Make sure that we're referring to a value.
3129   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3130   if (!VD) {
3131     Diag(Loc, diag::err_ref_non_value)
3132       << D << SS.getRange();
3133     Diag(D->getLocation(), diag::note_declared_at);
3134     return ExprError();
3135   }
3136 
3137   // Check whether this declaration can be used. Note that we suppress
3138   // this check when we're going to perform argument-dependent lookup
3139   // on this function name, because this might not be the function
3140   // that overload resolution actually selects.
3141   if (DiagnoseUseOfDecl(VD, Loc))
3142     return ExprError();
3143 
3144   // Only create DeclRefExpr's for valid Decl's.
3145   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3146     return ExprError();
3147 
3148   // Handle members of anonymous structs and unions.  If we got here,
3149   // and the reference is to a class member indirect field, then this
3150   // must be the subject of a pointer-to-member expression.
3151   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3152     if (!indirectField->isCXXClassMember())
3153       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3154                                                       indirectField);
3155 
3156   {
3157     QualType type = VD->getType();
3158     if (type.isNull())
3159       return ExprError();
3160     ExprValueKind valueKind = VK_RValue;
3161 
3162     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3163     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3164     // is expanded by some outer '...' in the context of the use.
3165     type = type.getNonPackExpansionType();
3166 
3167     switch (D->getKind()) {
3168     // Ignore all the non-ValueDecl kinds.
3169 #define ABSTRACT_DECL(kind)
3170 #define VALUE(type, base)
3171 #define DECL(type, base) \
3172     case Decl::type:
3173 #include "clang/AST/DeclNodes.inc"
3174       llvm_unreachable("invalid value decl kind");
3175 
3176     // These shouldn't make it here.
3177     case Decl::ObjCAtDefsField:
3178       llvm_unreachable("forming non-member reference to ivar?");
3179 
3180     // Enum constants are always r-values and never references.
3181     // Unresolved using declarations are dependent.
3182     case Decl::EnumConstant:
3183     case Decl::UnresolvedUsingValue:
3184     case Decl::OMPDeclareReduction:
3185     case Decl::OMPDeclareMapper:
3186       valueKind = VK_RValue;
3187       break;
3188 
3189     // Fields and indirect fields that got here must be for
3190     // pointer-to-member expressions; we just call them l-values for
3191     // internal consistency, because this subexpression doesn't really
3192     // exist in the high-level semantics.
3193     case Decl::Field:
3194     case Decl::IndirectField:
3195     case Decl::ObjCIvar:
3196       assert(getLangOpts().CPlusPlus &&
3197              "building reference to field in C?");
3198 
3199       // These can't have reference type in well-formed programs, but
3200       // for internal consistency we do this anyway.
3201       type = type.getNonReferenceType();
3202       valueKind = VK_LValue;
3203       break;
3204 
3205     // Non-type template parameters are either l-values or r-values
3206     // depending on the type.
3207     case Decl::NonTypeTemplateParm: {
3208       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3209         type = reftype->getPointeeType();
3210         valueKind = VK_LValue; // even if the parameter is an r-value reference
3211         break;
3212       }
3213 
3214       // For non-references, we need to strip qualifiers just in case
3215       // the template parameter was declared as 'const int' or whatever.
3216       valueKind = VK_RValue;
3217       type = type.getUnqualifiedType();
3218       break;
3219     }
3220 
3221     case Decl::Var:
3222     case Decl::VarTemplateSpecialization:
3223     case Decl::VarTemplatePartialSpecialization:
3224     case Decl::Decomposition:
3225     case Decl::OMPCapturedExpr:
3226       // In C, "extern void blah;" is valid and is an r-value.
3227       if (!getLangOpts().CPlusPlus &&
3228           !type.hasQualifiers() &&
3229           type->isVoidType()) {
3230         valueKind = VK_RValue;
3231         break;
3232       }
3233       LLVM_FALLTHROUGH;
3234 
3235     case Decl::ImplicitParam:
3236     case Decl::ParmVar: {
3237       // These are always l-values.
3238       valueKind = VK_LValue;
3239       type = type.getNonReferenceType();
3240 
3241       // FIXME: Does the addition of const really only apply in
3242       // potentially-evaluated contexts? Since the variable isn't actually
3243       // captured in an unevaluated context, it seems that the answer is no.
3244       if (!isUnevaluatedContext()) {
3245         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3246         if (!CapturedType.isNull())
3247           type = CapturedType;
3248       }
3249 
3250       break;
3251     }
3252 
3253     case Decl::Binding: {
3254       // These are always lvalues.
3255       valueKind = VK_LValue;
3256       type = type.getNonReferenceType();
3257       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3258       // decides how that's supposed to work.
3259       auto *BD = cast<BindingDecl>(VD);
3260       if (BD->getDeclContext() != CurContext) {
3261         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3262         if (DD && DD->hasLocalStorage())
3263           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3264       }
3265       break;
3266     }
3267 
3268     case Decl::Function: {
3269       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3270         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3271           type = Context.BuiltinFnTy;
3272           valueKind = VK_RValue;
3273           break;
3274         }
3275       }
3276 
3277       const FunctionType *fty = type->castAs<FunctionType>();
3278 
3279       // If we're referring to a function with an __unknown_anytype
3280       // result type, make the entire expression __unknown_anytype.
3281       if (fty->getReturnType() == Context.UnknownAnyTy) {
3282         type = Context.UnknownAnyTy;
3283         valueKind = VK_RValue;
3284         break;
3285       }
3286 
3287       // Functions are l-values in C++.
3288       if (getLangOpts().CPlusPlus) {
3289         valueKind = VK_LValue;
3290         break;
3291       }
3292 
3293       // C99 DR 316 says that, if a function type comes from a
3294       // function definition (without a prototype), that type is only
3295       // used for checking compatibility. Therefore, when referencing
3296       // the function, we pretend that we don't have the full function
3297       // type.
3298       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3299           isa<FunctionProtoType>(fty))
3300         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3301                                               fty->getExtInfo());
3302 
3303       // Functions are r-values in C.
3304       valueKind = VK_RValue;
3305       break;
3306     }
3307 
3308     case Decl::CXXDeductionGuide:
3309       llvm_unreachable("building reference to deduction guide");
3310 
3311     case Decl::MSProperty:
3312     case Decl::MSGuid:
3313       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3314       // or duplicated between host and device?
3315       valueKind = VK_LValue;
3316       break;
3317 
3318     case Decl::CXXMethod:
3319       // If we're referring to a method with an __unknown_anytype
3320       // result type, make the entire expression __unknown_anytype.
3321       // This should only be possible with a type written directly.
3322       if (const FunctionProtoType *proto
3323             = dyn_cast<FunctionProtoType>(VD->getType()))
3324         if (proto->getReturnType() == Context.UnknownAnyTy) {
3325           type = Context.UnknownAnyTy;
3326           valueKind = VK_RValue;
3327           break;
3328         }
3329 
3330       // C++ methods are l-values if static, r-values if non-static.
3331       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3332         valueKind = VK_LValue;
3333         break;
3334       }
3335       LLVM_FALLTHROUGH;
3336 
3337     case Decl::CXXConversion:
3338     case Decl::CXXDestructor:
3339     case Decl::CXXConstructor:
3340       valueKind = VK_RValue;
3341       break;
3342     }
3343 
3344     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3345                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3346                             TemplateArgs);
3347   }
3348 }
3349 
3350 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3351                                     SmallString<32> &Target) {
3352   Target.resize(CharByteWidth * (Source.size() + 1));
3353   char *ResultPtr = &Target[0];
3354   const llvm::UTF8 *ErrorPtr;
3355   bool success =
3356       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3357   (void)success;
3358   assert(success);
3359   Target.resize(ResultPtr - &Target[0]);
3360 }
3361 
3362 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3363                                      PredefinedExpr::IdentKind IK) {
3364   // Pick the current block, lambda, captured statement or function.
3365   Decl *currentDecl = nullptr;
3366   if (const BlockScopeInfo *BSI = getCurBlock())
3367     currentDecl = BSI->TheDecl;
3368   else if (const LambdaScopeInfo *LSI = getCurLambda())
3369     currentDecl = LSI->CallOperator;
3370   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3371     currentDecl = CSI->TheCapturedDecl;
3372   else
3373     currentDecl = getCurFunctionOrMethodDecl();
3374 
3375   if (!currentDecl) {
3376     Diag(Loc, diag::ext_predef_outside_function);
3377     currentDecl = Context.getTranslationUnitDecl();
3378   }
3379 
3380   QualType ResTy;
3381   StringLiteral *SL = nullptr;
3382   if (cast<DeclContext>(currentDecl)->isDependentContext())
3383     ResTy = Context.DependentTy;
3384   else {
3385     // Pre-defined identifiers are of type char[x], where x is the length of
3386     // the string.
3387     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3388     unsigned Length = Str.length();
3389 
3390     llvm::APInt LengthI(32, Length + 1);
3391     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3392       ResTy =
3393           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3394       SmallString<32> RawChars;
3395       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3396                               Str, RawChars);
3397       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3398                                            ArrayType::Normal,
3399                                            /*IndexTypeQuals*/ 0);
3400       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3401                                  /*Pascal*/ false, ResTy, Loc);
3402     } else {
3403       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3404       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3405                                            ArrayType::Normal,
3406                                            /*IndexTypeQuals*/ 0);
3407       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3408                                  /*Pascal*/ false, ResTy, Loc);
3409     }
3410   }
3411 
3412   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3413 }
3414 
3415 static std::pair<QualType, StringLiteral *>
3416 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3417                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3418   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3419 
3420   if (OpType->isDependentType()) {
3421       Result.first = Context.DependentTy;
3422       return Result;
3423   }
3424 
3425   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3426   llvm::APInt Length(32, Str.length() + 1);
3427   Result.first =
3428       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3429   Result.first = Context.getConstantArrayType(
3430       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3431   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3432                                         /*Pascal*/ false, Result.first, OpLoc);
3433   return Result;
3434 }
3435 
3436 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3437                                        TypeSourceInfo *Operand) {
3438   QualType ResultTy;
3439   StringLiteral *SL;
3440   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3441       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3442 
3443   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3444                                 PredefinedExpr::UniqueStableNameType, SL,
3445                                 Operand);
3446 }
3447 
3448 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3449                                        Expr *E) {
3450   QualType ResultTy;
3451   StringLiteral *SL;
3452   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3453       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3454 
3455   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3456                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3457 }
3458 
3459 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3460                                            SourceLocation L, SourceLocation R,
3461                                            ParsedType Ty) {
3462   TypeSourceInfo *TInfo = nullptr;
3463   QualType T = GetTypeFromParser(Ty, &TInfo);
3464 
3465   if (T.isNull())
3466     return ExprError();
3467   if (!TInfo)
3468     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3469 
3470   return BuildUniqueStableName(OpLoc, TInfo);
3471 }
3472 
3473 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3474                                            SourceLocation L, SourceLocation R,
3475                                            Expr *E) {
3476   return BuildUniqueStableName(OpLoc, E);
3477 }
3478 
3479 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3480   PredefinedExpr::IdentKind IK;
3481 
3482   switch (Kind) {
3483   default: llvm_unreachable("Unknown simple primary expr!");
3484   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3485   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3486   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3487   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3488   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3489   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3490   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3491   }
3492 
3493   return BuildPredefinedExpr(Loc, IK);
3494 }
3495 
3496 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3497   SmallString<16> CharBuffer;
3498   bool Invalid = false;
3499   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3500   if (Invalid)
3501     return ExprError();
3502 
3503   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3504                             PP, Tok.getKind());
3505   if (Literal.hadError())
3506     return ExprError();
3507 
3508   QualType Ty;
3509   if (Literal.isWide())
3510     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3511   else if (Literal.isUTF8() && getLangOpts().Char8)
3512     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3513   else if (Literal.isUTF16())
3514     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3515   else if (Literal.isUTF32())
3516     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3517   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3518     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3519   else
3520     Ty = Context.CharTy;  // 'x' -> char in C++
3521 
3522   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3523   if (Literal.isWide())
3524     Kind = CharacterLiteral::Wide;
3525   else if (Literal.isUTF16())
3526     Kind = CharacterLiteral::UTF16;
3527   else if (Literal.isUTF32())
3528     Kind = CharacterLiteral::UTF32;
3529   else if (Literal.isUTF8())
3530     Kind = CharacterLiteral::UTF8;
3531 
3532   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3533                                              Tok.getLocation());
3534 
3535   if (Literal.getUDSuffix().empty())
3536     return Lit;
3537 
3538   // We're building a user-defined literal.
3539   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3540   SourceLocation UDSuffixLoc =
3541     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3542 
3543   // Make sure we're allowed user-defined literals here.
3544   if (!UDLScope)
3545     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3546 
3547   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3548   //   operator "" X (ch)
3549   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3550                                         Lit, Tok.getLocation());
3551 }
3552 
3553 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3554   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3555   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3556                                 Context.IntTy, Loc);
3557 }
3558 
3559 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3560                                   QualType Ty, SourceLocation Loc) {
3561   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3562 
3563   using llvm::APFloat;
3564   APFloat Val(Format);
3565 
3566   APFloat::opStatus result = Literal.GetFloatValue(Val);
3567 
3568   // Overflow is always an error, but underflow is only an error if
3569   // we underflowed to zero (APFloat reports denormals as underflow).
3570   if ((result & APFloat::opOverflow) ||
3571       ((result & APFloat::opUnderflow) && Val.isZero())) {
3572     unsigned diagnostic;
3573     SmallString<20> buffer;
3574     if (result & APFloat::opOverflow) {
3575       diagnostic = diag::warn_float_overflow;
3576       APFloat::getLargest(Format).toString(buffer);
3577     } else {
3578       diagnostic = diag::warn_float_underflow;
3579       APFloat::getSmallest(Format).toString(buffer);
3580     }
3581 
3582     S.Diag(Loc, diagnostic)
3583       << Ty
3584       << StringRef(buffer.data(), buffer.size());
3585   }
3586 
3587   bool isExact = (result == APFloat::opOK);
3588   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3589 }
3590 
3591 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3592   assert(E && "Invalid expression");
3593 
3594   if (E->isValueDependent())
3595     return false;
3596 
3597   QualType QT = E->getType();
3598   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3599     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3600     return true;
3601   }
3602 
3603   llvm::APSInt ValueAPS;
3604   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3605 
3606   if (R.isInvalid())
3607     return true;
3608 
3609   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3610   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3611     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3612         << ValueAPS.toString(10) << ValueIsPositive;
3613     return true;
3614   }
3615 
3616   return false;
3617 }
3618 
3619 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3620   // Fast path for a single digit (which is quite common).  A single digit
3621   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3622   if (Tok.getLength() == 1) {
3623     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3624     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3625   }
3626 
3627   SmallString<128> SpellingBuffer;
3628   // NumericLiteralParser wants to overread by one character.  Add padding to
3629   // the buffer in case the token is copied to the buffer.  If getSpelling()
3630   // returns a StringRef to the memory buffer, it should have a null char at
3631   // the EOF, so it is also safe.
3632   SpellingBuffer.resize(Tok.getLength() + 1);
3633 
3634   // Get the spelling of the token, which eliminates trigraphs, etc.
3635   bool Invalid = false;
3636   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3637   if (Invalid)
3638     return ExprError();
3639 
3640   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3641                                PP.getSourceManager(), PP.getLangOpts(),
3642                                PP.getTargetInfo(), PP.getDiagnostics());
3643   if (Literal.hadError)
3644     return ExprError();
3645 
3646   if (Literal.hasUDSuffix()) {
3647     // We're building a user-defined literal.
3648     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3649     SourceLocation UDSuffixLoc =
3650       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3651 
3652     // Make sure we're allowed user-defined literals here.
3653     if (!UDLScope)
3654       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3655 
3656     QualType CookedTy;
3657     if (Literal.isFloatingLiteral()) {
3658       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3659       // long double, the literal is treated as a call of the form
3660       //   operator "" X (f L)
3661       CookedTy = Context.LongDoubleTy;
3662     } else {
3663       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3664       // unsigned long long, the literal is treated as a call of the form
3665       //   operator "" X (n ULL)
3666       CookedTy = Context.UnsignedLongLongTy;
3667     }
3668 
3669     DeclarationName OpName =
3670       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3671     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3672     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3673 
3674     SourceLocation TokLoc = Tok.getLocation();
3675 
3676     // Perform literal operator lookup to determine if we're building a raw
3677     // literal or a cooked one.
3678     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3679     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3680                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3681                                   /*AllowStringTemplate*/ false,
3682                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3683     case LOLR_ErrorNoDiagnostic:
3684       // Lookup failure for imaginary constants isn't fatal, there's still the
3685       // GNU extension producing _Complex types.
3686       break;
3687     case LOLR_Error:
3688       return ExprError();
3689     case LOLR_Cooked: {
3690       Expr *Lit;
3691       if (Literal.isFloatingLiteral()) {
3692         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3693       } else {
3694         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3695         if (Literal.GetIntegerValue(ResultVal))
3696           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3697               << /* Unsigned */ 1;
3698         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3699                                      Tok.getLocation());
3700       }
3701       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3702     }
3703 
3704     case LOLR_Raw: {
3705       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3706       // literal is treated as a call of the form
3707       //   operator "" X ("n")
3708       unsigned Length = Literal.getUDSuffixOffset();
3709       QualType StrTy = Context.getConstantArrayType(
3710           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3711           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3712       Expr *Lit = StringLiteral::Create(
3713           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3714           /*Pascal*/false, StrTy, &TokLoc, 1);
3715       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3716     }
3717 
3718     case LOLR_Template: {
3719       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3720       // template), L is treated as a call fo the form
3721       //   operator "" X <'c1', 'c2', ... 'ck'>()
3722       // where n is the source character sequence c1 c2 ... ck.
3723       TemplateArgumentListInfo ExplicitArgs;
3724       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3725       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3726       llvm::APSInt Value(CharBits, CharIsUnsigned);
3727       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3728         Value = TokSpelling[I];
3729         TemplateArgument Arg(Context, Value, Context.CharTy);
3730         TemplateArgumentLocInfo ArgInfo;
3731         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3732       }
3733       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3734                                       &ExplicitArgs);
3735     }
3736     case LOLR_StringTemplate:
3737       llvm_unreachable("unexpected literal operator lookup result");
3738     }
3739   }
3740 
3741   Expr *Res;
3742 
3743   if (Literal.isFixedPointLiteral()) {
3744     QualType Ty;
3745 
3746     if (Literal.isAccum) {
3747       if (Literal.isHalf) {
3748         Ty = Context.ShortAccumTy;
3749       } else if (Literal.isLong) {
3750         Ty = Context.LongAccumTy;
3751       } else {
3752         Ty = Context.AccumTy;
3753       }
3754     } else if (Literal.isFract) {
3755       if (Literal.isHalf) {
3756         Ty = Context.ShortFractTy;
3757       } else if (Literal.isLong) {
3758         Ty = Context.LongFractTy;
3759       } else {
3760         Ty = Context.FractTy;
3761       }
3762     }
3763 
3764     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3765 
3766     bool isSigned = !Literal.isUnsigned;
3767     unsigned scale = Context.getFixedPointScale(Ty);
3768     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3769 
3770     llvm::APInt Val(bit_width, 0, isSigned);
3771     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3772     bool ValIsZero = Val.isNullValue() && !Overflowed;
3773 
3774     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3775     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3776       // Clause 6.4.4 - The value of a constant shall be in the range of
3777       // representable values for its type, with exception for constants of a
3778       // fract type with a value of exactly 1; such a constant shall denote
3779       // the maximal value for the type.
3780       --Val;
3781     else if (Val.ugt(MaxVal) || Overflowed)
3782       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3783 
3784     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3785                                               Tok.getLocation(), scale);
3786   } else if (Literal.isFloatingLiteral()) {
3787     QualType Ty;
3788     if (Literal.isHalf){
3789       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3790         Ty = Context.HalfTy;
3791       else {
3792         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3793         return ExprError();
3794       }
3795     } else if (Literal.isFloat)
3796       Ty = Context.FloatTy;
3797     else if (Literal.isLong)
3798       Ty = Context.LongDoubleTy;
3799     else if (Literal.isFloat16)
3800       Ty = Context.Float16Ty;
3801     else if (Literal.isFloat128)
3802       Ty = Context.Float128Ty;
3803     else
3804       Ty = Context.DoubleTy;
3805 
3806     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3807 
3808     if (Ty == Context.DoubleTy) {
3809       if (getLangOpts().SinglePrecisionConstants) {
3810         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3811         if (BTy->getKind() != BuiltinType::Float) {
3812           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3813         }
3814       } else if (getLangOpts().OpenCL &&
3815                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3816         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3817         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3818         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3819       }
3820     }
3821   } else if (!Literal.isIntegerLiteral()) {
3822     return ExprError();
3823   } else {
3824     QualType Ty;
3825 
3826     // 'long long' is a C99 or C++11 feature.
3827     if (!getLangOpts().C99 && Literal.isLongLong) {
3828       if (getLangOpts().CPlusPlus)
3829         Diag(Tok.getLocation(),
3830              getLangOpts().CPlusPlus11 ?
3831              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3832       else
3833         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3834     }
3835 
3836     // Get the value in the widest-possible width.
3837     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3838     llvm::APInt ResultVal(MaxWidth, 0);
3839 
3840     if (Literal.GetIntegerValue(ResultVal)) {
3841       // If this value didn't fit into uintmax_t, error and force to ull.
3842       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3843           << /* Unsigned */ 1;
3844       Ty = Context.UnsignedLongLongTy;
3845       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3846              "long long is not intmax_t?");
3847     } else {
3848       // If this value fits into a ULL, try to figure out what else it fits into
3849       // according to the rules of C99 6.4.4.1p5.
3850 
3851       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3852       // be an unsigned int.
3853       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3854 
3855       // Check from smallest to largest, picking the smallest type we can.
3856       unsigned Width = 0;
3857 
3858       // Microsoft specific integer suffixes are explicitly sized.
3859       if (Literal.MicrosoftInteger) {
3860         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3861           Width = 8;
3862           Ty = Context.CharTy;
3863         } else {
3864           Width = Literal.MicrosoftInteger;
3865           Ty = Context.getIntTypeForBitwidth(Width,
3866                                              /*Signed=*/!Literal.isUnsigned);
3867         }
3868       }
3869 
3870       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3871         // Are int/unsigned possibilities?
3872         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3873 
3874         // Does it fit in a unsigned int?
3875         if (ResultVal.isIntN(IntSize)) {
3876           // Does it fit in a signed int?
3877           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3878             Ty = Context.IntTy;
3879           else if (AllowUnsigned)
3880             Ty = Context.UnsignedIntTy;
3881           Width = IntSize;
3882         }
3883       }
3884 
3885       // Are long/unsigned long possibilities?
3886       if (Ty.isNull() && !Literal.isLongLong) {
3887         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3888 
3889         // Does it fit in a unsigned long?
3890         if (ResultVal.isIntN(LongSize)) {
3891           // Does it fit in a signed long?
3892           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3893             Ty = Context.LongTy;
3894           else if (AllowUnsigned)
3895             Ty = Context.UnsignedLongTy;
3896           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3897           // is compatible.
3898           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3899             const unsigned LongLongSize =
3900                 Context.getTargetInfo().getLongLongWidth();
3901             Diag(Tok.getLocation(),
3902                  getLangOpts().CPlusPlus
3903                      ? Literal.isLong
3904                            ? diag::warn_old_implicitly_unsigned_long_cxx
3905                            : /*C++98 UB*/ diag::
3906                                  ext_old_implicitly_unsigned_long_cxx
3907                      : diag::warn_old_implicitly_unsigned_long)
3908                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3909                                             : /*will be ill-formed*/ 1);
3910             Ty = Context.UnsignedLongTy;
3911           }
3912           Width = LongSize;
3913         }
3914       }
3915 
3916       // Check long long if needed.
3917       if (Ty.isNull()) {
3918         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3919 
3920         // Does it fit in a unsigned long long?
3921         if (ResultVal.isIntN(LongLongSize)) {
3922           // Does it fit in a signed long long?
3923           // To be compatible with MSVC, hex integer literals ending with the
3924           // LL or i64 suffix are always signed in Microsoft mode.
3925           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3926               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3927             Ty = Context.LongLongTy;
3928           else if (AllowUnsigned)
3929             Ty = Context.UnsignedLongLongTy;
3930           Width = LongLongSize;
3931         }
3932       }
3933 
3934       // If we still couldn't decide a type, we probably have something that
3935       // does not fit in a signed long long, but has no U suffix.
3936       if (Ty.isNull()) {
3937         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3938         Ty = Context.UnsignedLongLongTy;
3939         Width = Context.getTargetInfo().getLongLongWidth();
3940       }
3941 
3942       if (ResultVal.getBitWidth() != Width)
3943         ResultVal = ResultVal.trunc(Width);
3944     }
3945     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3946   }
3947 
3948   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3949   if (Literal.isImaginary) {
3950     Res = new (Context) ImaginaryLiteral(Res,
3951                                         Context.getComplexType(Res->getType()));
3952 
3953     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3954   }
3955   return Res;
3956 }
3957 
3958 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3959   assert(E && "ActOnParenExpr() missing expr");
3960   return new (Context) ParenExpr(L, R, E);
3961 }
3962 
3963 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3964                                          SourceLocation Loc,
3965                                          SourceRange ArgRange) {
3966   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3967   // scalar or vector data type argument..."
3968   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3969   // type (C99 6.2.5p18) or void.
3970   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3971     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3972       << T << ArgRange;
3973     return true;
3974   }
3975 
3976   assert((T->isVoidType() || !T->isIncompleteType()) &&
3977          "Scalar types should always be complete");
3978   return false;
3979 }
3980 
3981 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3982                                            SourceLocation Loc,
3983                                            SourceRange ArgRange,
3984                                            UnaryExprOrTypeTrait TraitKind) {
3985   // Invalid types must be hard errors for SFINAE in C++.
3986   if (S.LangOpts.CPlusPlus)
3987     return true;
3988 
3989   // C99 6.5.3.4p1:
3990   if (T->isFunctionType() &&
3991       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3992        TraitKind == UETT_PreferredAlignOf)) {
3993     // sizeof(function)/alignof(function) is allowed as an extension.
3994     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3995         << getTraitSpelling(TraitKind) << ArgRange;
3996     return false;
3997   }
3998 
3999   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4000   // this is an error (OpenCL v1.1 s6.3.k)
4001   if (T->isVoidType()) {
4002     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4003                                         : diag::ext_sizeof_alignof_void_type;
4004     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4005     return false;
4006   }
4007 
4008   return true;
4009 }
4010 
4011 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4012                                              SourceLocation Loc,
4013                                              SourceRange ArgRange,
4014                                              UnaryExprOrTypeTrait TraitKind) {
4015   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4016   // runtime doesn't allow it.
4017   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4018     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4019       << T << (TraitKind == UETT_SizeOf)
4020       << ArgRange;
4021     return true;
4022   }
4023 
4024   return false;
4025 }
4026 
4027 /// Check whether E is a pointer from a decayed array type (the decayed
4028 /// pointer type is equal to T) and emit a warning if it is.
4029 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4030                                      Expr *E) {
4031   // Don't warn if the operation changed the type.
4032   if (T != E->getType())
4033     return;
4034 
4035   // Now look for array decays.
4036   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4037   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4038     return;
4039 
4040   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4041                                              << ICE->getType()
4042                                              << ICE->getSubExpr()->getType();
4043 }
4044 
4045 /// Check the constraints on expression operands to unary type expression
4046 /// and type traits.
4047 ///
4048 /// Completes any types necessary and validates the constraints on the operand
4049 /// expression. The logic mostly mirrors the type-based overload, but may modify
4050 /// the expression as it completes the type for that expression through template
4051 /// instantiation, etc.
4052 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4053                                             UnaryExprOrTypeTrait ExprKind) {
4054   QualType ExprTy = E->getType();
4055   assert(!ExprTy->isReferenceType());
4056 
4057   bool IsUnevaluatedOperand =
4058       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4059        ExprKind == UETT_PreferredAlignOf);
4060   if (IsUnevaluatedOperand) {
4061     ExprResult Result = CheckUnevaluatedOperand(E);
4062     if (Result.isInvalid())
4063       return true;
4064     E = Result.get();
4065   }
4066 
4067   if (ExprKind == UETT_VecStep)
4068     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4069                                         E->getSourceRange());
4070 
4071   // Explicitly list some types as extensions.
4072   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4073                                       E->getSourceRange(), ExprKind))
4074     return false;
4075 
4076   // 'alignof' applied to an expression only requires the base element type of
4077   // the expression to be complete. 'sizeof' requires the expression's type to
4078   // be complete (and will attempt to complete it if it's an array of unknown
4079   // bound).
4080   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4081     if (RequireCompleteSizedType(
4082             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4083             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4084             getTraitSpelling(ExprKind), E->getSourceRange()))
4085       return true;
4086   } else {
4087     if (RequireCompleteSizedExprType(
4088             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4089             getTraitSpelling(ExprKind), E->getSourceRange()))
4090       return true;
4091   }
4092 
4093   // Completing the expression's type may have changed it.
4094   ExprTy = E->getType();
4095   assert(!ExprTy->isReferenceType());
4096 
4097   if (ExprTy->isFunctionType()) {
4098     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4099         << getTraitSpelling(ExprKind) << E->getSourceRange();
4100     return true;
4101   }
4102 
4103   // The operand for sizeof and alignof is in an unevaluated expression context,
4104   // so side effects could result in unintended consequences.
4105   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4106       E->HasSideEffects(Context, false))
4107     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4108 
4109   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4110                                        E->getSourceRange(), ExprKind))
4111     return true;
4112 
4113   if (ExprKind == UETT_SizeOf) {
4114     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4115       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4116         QualType OType = PVD->getOriginalType();
4117         QualType Type = PVD->getType();
4118         if (Type->isPointerType() && OType->isArrayType()) {
4119           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4120             << Type << OType;
4121           Diag(PVD->getLocation(), diag::note_declared_at);
4122         }
4123       }
4124     }
4125 
4126     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4127     // decays into a pointer and returns an unintended result. This is most
4128     // likely a typo for "sizeof(array) op x".
4129     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4130       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4131                                BO->getLHS());
4132       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4133                                BO->getRHS());
4134     }
4135   }
4136 
4137   return false;
4138 }
4139 
4140 /// Check the constraints on operands to unary expression and type
4141 /// traits.
4142 ///
4143 /// This will complete any types necessary, and validate the various constraints
4144 /// on those operands.
4145 ///
4146 /// The UsualUnaryConversions() function is *not* called by this routine.
4147 /// C99 6.3.2.1p[2-4] all state:
4148 ///   Except when it is the operand of the sizeof operator ...
4149 ///
4150 /// C++ [expr.sizeof]p4
4151 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4152 ///   standard conversions are not applied to the operand of sizeof.
4153 ///
4154 /// This policy is followed for all of the unary trait expressions.
4155 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4156                                             SourceLocation OpLoc,
4157                                             SourceRange ExprRange,
4158                                             UnaryExprOrTypeTrait ExprKind) {
4159   if (ExprType->isDependentType())
4160     return false;
4161 
4162   // C++ [expr.sizeof]p2:
4163   //     When applied to a reference or a reference type, the result
4164   //     is the size of the referenced type.
4165   // C++11 [expr.alignof]p3:
4166   //     When alignof is applied to a reference type, the result
4167   //     shall be the alignment of the referenced type.
4168   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4169     ExprType = Ref->getPointeeType();
4170 
4171   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4172   //   When alignof or _Alignof is applied to an array type, the result
4173   //   is the alignment of the element type.
4174   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4175       ExprKind == UETT_OpenMPRequiredSimdAlign)
4176     ExprType = Context.getBaseElementType(ExprType);
4177 
4178   if (ExprKind == UETT_VecStep)
4179     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4180 
4181   // Explicitly list some types as extensions.
4182   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4183                                       ExprKind))
4184     return false;
4185 
4186   if (RequireCompleteSizedType(
4187           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4188           getTraitSpelling(ExprKind), ExprRange))
4189     return true;
4190 
4191   if (ExprType->isFunctionType()) {
4192     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4193         << getTraitSpelling(ExprKind) << ExprRange;
4194     return true;
4195   }
4196 
4197   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4198                                        ExprKind))
4199     return true;
4200 
4201   return false;
4202 }
4203 
4204 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4205   // Cannot know anything else if the expression is dependent.
4206   if (E->isTypeDependent())
4207     return false;
4208 
4209   if (E->getObjectKind() == OK_BitField) {
4210     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4211        << 1 << E->getSourceRange();
4212     return true;
4213   }
4214 
4215   ValueDecl *D = nullptr;
4216   Expr *Inner = E->IgnoreParens();
4217   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4218     D = DRE->getDecl();
4219   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4220     D = ME->getMemberDecl();
4221   }
4222 
4223   // If it's a field, require the containing struct to have a
4224   // complete definition so that we can compute the layout.
4225   //
4226   // This can happen in C++11 onwards, either by naming the member
4227   // in a way that is not transformed into a member access expression
4228   // (in an unevaluated operand, for instance), or by naming the member
4229   // in a trailing-return-type.
4230   //
4231   // For the record, since __alignof__ on expressions is a GCC
4232   // extension, GCC seems to permit this but always gives the
4233   // nonsensical answer 0.
4234   //
4235   // We don't really need the layout here --- we could instead just
4236   // directly check for all the appropriate alignment-lowing
4237   // attributes --- but that would require duplicating a lot of
4238   // logic that just isn't worth duplicating for such a marginal
4239   // use-case.
4240   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4241     // Fast path this check, since we at least know the record has a
4242     // definition if we can find a member of it.
4243     if (!FD->getParent()->isCompleteDefinition()) {
4244       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4245         << E->getSourceRange();
4246       return true;
4247     }
4248 
4249     // Otherwise, if it's a field, and the field doesn't have
4250     // reference type, then it must have a complete type (or be a
4251     // flexible array member, which we explicitly want to
4252     // white-list anyway), which makes the following checks trivial.
4253     if (!FD->getType()->isReferenceType())
4254       return false;
4255   }
4256 
4257   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4258 }
4259 
4260 bool Sema::CheckVecStepExpr(Expr *E) {
4261   E = E->IgnoreParens();
4262 
4263   // Cannot know anything else if the expression is dependent.
4264   if (E->isTypeDependent())
4265     return false;
4266 
4267   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4268 }
4269 
4270 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4271                                         CapturingScopeInfo *CSI) {
4272   assert(T->isVariablyModifiedType());
4273   assert(CSI != nullptr);
4274 
4275   // We're going to walk down into the type and look for VLA expressions.
4276   do {
4277     const Type *Ty = T.getTypePtr();
4278     switch (Ty->getTypeClass()) {
4279 #define TYPE(Class, Base)
4280 #define ABSTRACT_TYPE(Class, Base)
4281 #define NON_CANONICAL_TYPE(Class, Base)
4282 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4283 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4284 #include "clang/AST/TypeNodes.inc"
4285       T = QualType();
4286       break;
4287     // These types are never variably-modified.
4288     case Type::Builtin:
4289     case Type::Complex:
4290     case Type::Vector:
4291     case Type::ExtVector:
4292     case Type::ConstantMatrix:
4293     case Type::Record:
4294     case Type::Enum:
4295     case Type::Elaborated:
4296     case Type::TemplateSpecialization:
4297     case Type::ObjCObject:
4298     case Type::ObjCInterface:
4299     case Type::ObjCObjectPointer:
4300     case Type::ObjCTypeParam:
4301     case Type::Pipe:
4302     case Type::ExtInt:
4303       llvm_unreachable("type class is never variably-modified!");
4304     case Type::Adjusted:
4305       T = cast<AdjustedType>(Ty)->getOriginalType();
4306       break;
4307     case Type::Decayed:
4308       T = cast<DecayedType>(Ty)->getPointeeType();
4309       break;
4310     case Type::Pointer:
4311       T = cast<PointerType>(Ty)->getPointeeType();
4312       break;
4313     case Type::BlockPointer:
4314       T = cast<BlockPointerType>(Ty)->getPointeeType();
4315       break;
4316     case Type::LValueReference:
4317     case Type::RValueReference:
4318       T = cast<ReferenceType>(Ty)->getPointeeType();
4319       break;
4320     case Type::MemberPointer:
4321       T = cast<MemberPointerType>(Ty)->getPointeeType();
4322       break;
4323     case Type::ConstantArray:
4324     case Type::IncompleteArray:
4325       // Losing element qualification here is fine.
4326       T = cast<ArrayType>(Ty)->getElementType();
4327       break;
4328     case Type::VariableArray: {
4329       // Losing element qualification here is fine.
4330       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4331 
4332       // Unknown size indication requires no size computation.
4333       // Otherwise, evaluate and record it.
4334       auto Size = VAT->getSizeExpr();
4335       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4336           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4337         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4338 
4339       T = VAT->getElementType();
4340       break;
4341     }
4342     case Type::FunctionProto:
4343     case Type::FunctionNoProto:
4344       T = cast<FunctionType>(Ty)->getReturnType();
4345       break;
4346     case Type::Paren:
4347     case Type::TypeOf:
4348     case Type::UnaryTransform:
4349     case Type::Attributed:
4350     case Type::SubstTemplateTypeParm:
4351     case Type::MacroQualified:
4352       // Keep walking after single level desugaring.
4353       T = T.getSingleStepDesugaredType(Context);
4354       break;
4355     case Type::Typedef:
4356       T = cast<TypedefType>(Ty)->desugar();
4357       break;
4358     case Type::Decltype:
4359       T = cast<DecltypeType>(Ty)->desugar();
4360       break;
4361     case Type::Auto:
4362     case Type::DeducedTemplateSpecialization:
4363       T = cast<DeducedType>(Ty)->getDeducedType();
4364       break;
4365     case Type::TypeOfExpr:
4366       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4367       break;
4368     case Type::Atomic:
4369       T = cast<AtomicType>(Ty)->getValueType();
4370       break;
4371     }
4372   } while (!T.isNull() && T->isVariablyModifiedType());
4373 }
4374 
4375 /// Build a sizeof or alignof expression given a type operand.
4376 ExprResult
4377 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4378                                      SourceLocation OpLoc,
4379                                      UnaryExprOrTypeTrait ExprKind,
4380                                      SourceRange R) {
4381   if (!TInfo)
4382     return ExprError();
4383 
4384   QualType T = TInfo->getType();
4385 
4386   if (!T->isDependentType() &&
4387       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4388     return ExprError();
4389 
4390   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4391     if (auto *TT = T->getAs<TypedefType>()) {
4392       for (auto I = FunctionScopes.rbegin(),
4393                 E = std::prev(FunctionScopes.rend());
4394            I != E; ++I) {
4395         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4396         if (CSI == nullptr)
4397           break;
4398         DeclContext *DC = nullptr;
4399         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4400           DC = LSI->CallOperator;
4401         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4402           DC = CRSI->TheCapturedDecl;
4403         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4404           DC = BSI->TheDecl;
4405         if (DC) {
4406           if (DC->containsDecl(TT->getDecl()))
4407             break;
4408           captureVariablyModifiedType(Context, T, CSI);
4409         }
4410       }
4411     }
4412   }
4413 
4414   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4415   return new (Context) UnaryExprOrTypeTraitExpr(
4416       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4417 }
4418 
4419 /// Build a sizeof or alignof expression given an expression
4420 /// operand.
4421 ExprResult
4422 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4423                                      UnaryExprOrTypeTrait ExprKind) {
4424   ExprResult PE = CheckPlaceholderExpr(E);
4425   if (PE.isInvalid())
4426     return ExprError();
4427 
4428   E = PE.get();
4429 
4430   // Verify that the operand is valid.
4431   bool isInvalid = false;
4432   if (E->isTypeDependent()) {
4433     // Delay type-checking for type-dependent expressions.
4434   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4435     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4436   } else if (ExprKind == UETT_VecStep) {
4437     isInvalid = CheckVecStepExpr(E);
4438   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4439       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4440       isInvalid = true;
4441   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4442     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4443     isInvalid = true;
4444   } else {
4445     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4446   }
4447 
4448   if (isInvalid)
4449     return ExprError();
4450 
4451   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4452     PE = TransformToPotentiallyEvaluated(E);
4453     if (PE.isInvalid()) return ExprError();
4454     E = PE.get();
4455   }
4456 
4457   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4458   return new (Context) UnaryExprOrTypeTraitExpr(
4459       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4460 }
4461 
4462 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4463 /// expr and the same for @c alignof and @c __alignof
4464 /// Note that the ArgRange is invalid if isType is false.
4465 ExprResult
4466 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4467                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4468                                     void *TyOrEx, SourceRange ArgRange) {
4469   // If error parsing type, ignore.
4470   if (!TyOrEx) return ExprError();
4471 
4472   if (IsType) {
4473     TypeSourceInfo *TInfo;
4474     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4475     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4476   }
4477 
4478   Expr *ArgEx = (Expr *)TyOrEx;
4479   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4480   return Result;
4481 }
4482 
4483 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4484                                      bool IsReal) {
4485   if (V.get()->isTypeDependent())
4486     return S.Context.DependentTy;
4487 
4488   // _Real and _Imag are only l-values for normal l-values.
4489   if (V.get()->getObjectKind() != OK_Ordinary) {
4490     V = S.DefaultLvalueConversion(V.get());
4491     if (V.isInvalid())
4492       return QualType();
4493   }
4494 
4495   // These operators return the element type of a complex type.
4496   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4497     return CT->getElementType();
4498 
4499   // Otherwise they pass through real integer and floating point types here.
4500   if (V.get()->getType()->isArithmeticType())
4501     return V.get()->getType();
4502 
4503   // Test for placeholders.
4504   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4505   if (PR.isInvalid()) return QualType();
4506   if (PR.get() != V.get()) {
4507     V = PR;
4508     return CheckRealImagOperand(S, V, Loc, IsReal);
4509   }
4510 
4511   // Reject anything else.
4512   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4513     << (IsReal ? "__real" : "__imag");
4514   return QualType();
4515 }
4516 
4517 
4518 
4519 ExprResult
4520 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4521                           tok::TokenKind Kind, Expr *Input) {
4522   UnaryOperatorKind Opc;
4523   switch (Kind) {
4524   default: llvm_unreachable("Unknown unary op!");
4525   case tok::plusplus:   Opc = UO_PostInc; break;
4526   case tok::minusminus: Opc = UO_PostDec; break;
4527   }
4528 
4529   // Since this might is a postfix expression, get rid of ParenListExprs.
4530   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4531   if (Result.isInvalid()) return ExprError();
4532   Input = Result.get();
4533 
4534   return BuildUnaryOp(S, OpLoc, Opc, Input);
4535 }
4536 
4537 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4538 ///
4539 /// \return true on error
4540 static bool checkArithmeticOnObjCPointer(Sema &S,
4541                                          SourceLocation opLoc,
4542                                          Expr *op) {
4543   assert(op->getType()->isObjCObjectPointerType());
4544   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4545       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4546     return false;
4547 
4548   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4549     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4550     << op->getSourceRange();
4551   return true;
4552 }
4553 
4554 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4555   auto *BaseNoParens = Base->IgnoreParens();
4556   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4557     return MSProp->getPropertyDecl()->getType()->isArrayType();
4558   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4559 }
4560 
4561 ExprResult
4562 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4563                               Expr *idx, SourceLocation rbLoc) {
4564   if (base && !base->getType().isNull() &&
4565       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4566     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4567                                     SourceLocation(), /*Length*/ nullptr,
4568                                     /*Stride=*/nullptr, rbLoc);
4569 
4570   // Since this might be a postfix expression, get rid of ParenListExprs.
4571   if (isa<ParenListExpr>(base)) {
4572     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4573     if (result.isInvalid()) return ExprError();
4574     base = result.get();
4575   }
4576 
4577   // Check if base and idx form a MatrixSubscriptExpr.
4578   //
4579   // Helper to check for comma expressions, which are not allowed as indices for
4580   // matrix subscript expressions.
4581   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4582     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4583       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4584           << SourceRange(base->getBeginLoc(), rbLoc);
4585       return true;
4586     }
4587     return false;
4588   };
4589   // The matrix subscript operator ([][])is considered a single operator.
4590   // Separating the index expressions by parenthesis is not allowed.
4591   if (base->getType()->isSpecificPlaceholderType(
4592           BuiltinType::IncompleteMatrixIdx) &&
4593       !isa<MatrixSubscriptExpr>(base)) {
4594     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4595         << SourceRange(base->getBeginLoc(), rbLoc);
4596     return ExprError();
4597   }
4598   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4599   // a new MatrixSubscriptExpr.
4600   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4601   if (matSubscriptE) {
4602     if (CheckAndReportCommaError(idx))
4603       return ExprError();
4604 
4605     assert(matSubscriptE->isIncomplete() &&
4606            "base has to be an incomplete matrix subscript");
4607     return CreateBuiltinMatrixSubscriptExpr(
4608         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4609   }
4610   Expr *matrixBase = base;
4611   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4612   if (!IsMSPropertySubscript) {
4613     ExprResult result = CheckPlaceholderExpr(base);
4614     if (!result.isInvalid())
4615       matrixBase = result.get();
4616   }
4617   if (matrixBase->getType()->isMatrixType()) {
4618     if (CheckAndReportCommaError(idx))
4619       return ExprError();
4620 
4621     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4622   }
4623 
4624   // A comma-expression as the index is deprecated in C++2a onwards.
4625   if (getLangOpts().CPlusPlus20 &&
4626       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4627        (isa<CXXOperatorCallExpr>(idx) &&
4628         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4629     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4630       << SourceRange(base->getBeginLoc(), rbLoc);
4631   }
4632 
4633   // Handle any non-overload placeholder types in the base and index
4634   // expressions.  We can't handle overloads here because the other
4635   // operand might be an overloadable type, in which case the overload
4636   // resolution for the operator overload should get the first crack
4637   // at the overload.
4638   if (base->getType()->isNonOverloadPlaceholderType()) {
4639     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4640     if (!IsMSPropertySubscript) {
4641       ExprResult result = CheckPlaceholderExpr(base);
4642       if (result.isInvalid())
4643         return ExprError();
4644       base = result.get();
4645     }
4646   }
4647   if (idx->getType()->isNonOverloadPlaceholderType()) {
4648     ExprResult result = CheckPlaceholderExpr(idx);
4649     if (result.isInvalid()) return ExprError();
4650     idx = result.get();
4651   }
4652 
4653   // Build an unanalyzed expression if either operand is type-dependent.
4654   if (getLangOpts().CPlusPlus &&
4655       (base->isTypeDependent() || idx->isTypeDependent())) {
4656     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4657                                             VK_LValue, OK_Ordinary, rbLoc);
4658   }
4659 
4660   // MSDN, property (C++)
4661   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4662   // This attribute can also be used in the declaration of an empty array in a
4663   // class or structure definition. For example:
4664   // __declspec(property(get=GetX, put=PutX)) int x[];
4665   // The above statement indicates that x[] can be used with one or more array
4666   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4667   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4668   if (IsMSPropertySubscript) {
4669     // Build MS property subscript expression if base is MS property reference
4670     // or MS property subscript.
4671     return new (Context) MSPropertySubscriptExpr(
4672         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4673   }
4674 
4675   // Use C++ overloaded-operator rules if either operand has record
4676   // type.  The spec says to do this if either type is *overloadable*,
4677   // but enum types can't declare subscript operators or conversion
4678   // operators, so there's nothing interesting for overload resolution
4679   // to do if there aren't any record types involved.
4680   //
4681   // ObjC pointers have their own subscripting logic that is not tied
4682   // to overload resolution and so should not take this path.
4683   if (getLangOpts().CPlusPlus &&
4684       (base->getType()->isRecordType() ||
4685        (!base->getType()->isObjCObjectPointerType() &&
4686         idx->getType()->isRecordType()))) {
4687     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4688   }
4689 
4690   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4691 
4692   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4693     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4694 
4695   return Res;
4696 }
4697 
4698 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4699   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4700   InitializationKind Kind =
4701       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4702   InitializationSequence InitSeq(*this, Entity, Kind, E);
4703   return InitSeq.Perform(*this, Entity, Kind, E);
4704 }
4705 
4706 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4707                                                   Expr *ColumnIdx,
4708                                                   SourceLocation RBLoc) {
4709   ExprResult BaseR = CheckPlaceholderExpr(Base);
4710   if (BaseR.isInvalid())
4711     return BaseR;
4712   Base = BaseR.get();
4713 
4714   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4715   if (RowR.isInvalid())
4716     return RowR;
4717   RowIdx = RowR.get();
4718 
4719   if (!ColumnIdx)
4720     return new (Context) MatrixSubscriptExpr(
4721         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4722 
4723   // Build an unanalyzed expression if any of the operands is type-dependent.
4724   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4725       ColumnIdx->isTypeDependent())
4726     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4727                                              Context.DependentTy, RBLoc);
4728 
4729   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4730   if (ColumnR.isInvalid())
4731     return ColumnR;
4732   ColumnIdx = ColumnR.get();
4733 
4734   // Check that IndexExpr is an integer expression. If it is a constant
4735   // expression, check that it is less than Dim (= the number of elements in the
4736   // corresponding dimension).
4737   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4738                           bool IsColumnIdx) -> Expr * {
4739     if (!IndexExpr->getType()->isIntegerType() &&
4740         !IndexExpr->isTypeDependent()) {
4741       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4742           << IsColumnIdx;
4743       return nullptr;
4744     }
4745 
4746     if (Optional<llvm::APSInt> Idx =
4747             IndexExpr->getIntegerConstantExpr(Context)) {
4748       if ((*Idx < 0 || *Idx >= Dim)) {
4749         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4750             << IsColumnIdx << Dim;
4751         return nullptr;
4752       }
4753     }
4754 
4755     ExprResult ConvExpr =
4756         tryConvertExprToType(IndexExpr, Context.getSizeType());
4757     assert(!ConvExpr.isInvalid() &&
4758            "should be able to convert any integer type to size type");
4759     return ConvExpr.get();
4760   };
4761 
4762   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4763   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4764   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4765   if (!RowIdx || !ColumnIdx)
4766     return ExprError();
4767 
4768   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4769                                            MTy->getElementType(), RBLoc);
4770 }
4771 
4772 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4773   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4774   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4775 
4776   // For expressions like `&(*s).b`, the base is recorded and what should be
4777   // checked.
4778   const MemberExpr *Member = nullptr;
4779   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4780     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4781 
4782   LastRecord.PossibleDerefs.erase(StrippedExpr);
4783 }
4784 
4785 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4786   QualType ResultTy = E->getType();
4787   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4788 
4789   // Bail if the element is an array since it is not memory access.
4790   if (isa<ArrayType>(ResultTy))
4791     return;
4792 
4793   if (ResultTy->hasAttr(attr::NoDeref)) {
4794     LastRecord.PossibleDerefs.insert(E);
4795     return;
4796   }
4797 
4798   // Check if the base type is a pointer to a member access of a struct
4799   // marked with noderef.
4800   const Expr *Base = E->getBase();
4801   QualType BaseTy = Base->getType();
4802   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4803     // Not a pointer access
4804     return;
4805 
4806   const MemberExpr *Member = nullptr;
4807   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4808          Member->isArrow())
4809     Base = Member->getBase();
4810 
4811   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4812     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4813       LastRecord.PossibleDerefs.insert(E);
4814   }
4815 }
4816 
4817 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4818                                           Expr *LowerBound,
4819                                           SourceLocation ColonLocFirst,
4820                                           SourceLocation ColonLocSecond,
4821                                           Expr *Length, Expr *Stride,
4822                                           SourceLocation RBLoc) {
4823   if (Base->getType()->isPlaceholderType() &&
4824       !Base->getType()->isSpecificPlaceholderType(
4825           BuiltinType::OMPArraySection)) {
4826     ExprResult Result = CheckPlaceholderExpr(Base);
4827     if (Result.isInvalid())
4828       return ExprError();
4829     Base = Result.get();
4830   }
4831   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4832     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4833     if (Result.isInvalid())
4834       return ExprError();
4835     Result = DefaultLvalueConversion(Result.get());
4836     if (Result.isInvalid())
4837       return ExprError();
4838     LowerBound = Result.get();
4839   }
4840   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4841     ExprResult Result = CheckPlaceholderExpr(Length);
4842     if (Result.isInvalid())
4843       return ExprError();
4844     Result = DefaultLvalueConversion(Result.get());
4845     if (Result.isInvalid())
4846       return ExprError();
4847     Length = Result.get();
4848   }
4849   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4850     ExprResult Result = CheckPlaceholderExpr(Stride);
4851     if (Result.isInvalid())
4852       return ExprError();
4853     Result = DefaultLvalueConversion(Result.get());
4854     if (Result.isInvalid())
4855       return ExprError();
4856     Stride = Result.get();
4857   }
4858 
4859   // Build an unanalyzed expression if either operand is type-dependent.
4860   if (Base->isTypeDependent() ||
4861       (LowerBound &&
4862        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4863       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4864       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4865     return new (Context) OMPArraySectionExpr(
4866         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4867         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4868   }
4869 
4870   // Perform default conversions.
4871   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4872   QualType ResultTy;
4873   if (OriginalTy->isAnyPointerType()) {
4874     ResultTy = OriginalTy->getPointeeType();
4875   } else if (OriginalTy->isArrayType()) {
4876     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4877   } else {
4878     return ExprError(
4879         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4880         << Base->getSourceRange());
4881   }
4882   // C99 6.5.2.1p1
4883   if (LowerBound) {
4884     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4885                                                       LowerBound);
4886     if (Res.isInvalid())
4887       return ExprError(Diag(LowerBound->getExprLoc(),
4888                             diag::err_omp_typecheck_section_not_integer)
4889                        << 0 << LowerBound->getSourceRange());
4890     LowerBound = Res.get();
4891 
4892     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4893         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4894       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4895           << 0 << LowerBound->getSourceRange();
4896   }
4897   if (Length) {
4898     auto Res =
4899         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4900     if (Res.isInvalid())
4901       return ExprError(Diag(Length->getExprLoc(),
4902                             diag::err_omp_typecheck_section_not_integer)
4903                        << 1 << Length->getSourceRange());
4904     Length = Res.get();
4905 
4906     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4907         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4908       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4909           << 1 << Length->getSourceRange();
4910   }
4911   if (Stride) {
4912     ExprResult Res =
4913         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4914     if (Res.isInvalid())
4915       return ExprError(Diag(Stride->getExprLoc(),
4916                             diag::err_omp_typecheck_section_not_integer)
4917                        << 1 << Stride->getSourceRange());
4918     Stride = Res.get();
4919 
4920     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4921         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4922       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4923           << 1 << Stride->getSourceRange();
4924   }
4925 
4926   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4927   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4928   // type. Note that functions are not objects, and that (in C99 parlance)
4929   // incomplete types are not object types.
4930   if (ResultTy->isFunctionType()) {
4931     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4932         << ResultTy << Base->getSourceRange();
4933     return ExprError();
4934   }
4935 
4936   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4937                           diag::err_omp_section_incomplete_type, Base))
4938     return ExprError();
4939 
4940   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4941     Expr::EvalResult Result;
4942     if (LowerBound->EvaluateAsInt(Result, Context)) {
4943       // OpenMP 5.0, [2.1.5 Array Sections]
4944       // The array section must be a subset of the original array.
4945       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4946       if (LowerBoundValue.isNegative()) {
4947         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4948             << LowerBound->getSourceRange();
4949         return ExprError();
4950       }
4951     }
4952   }
4953 
4954   if (Length) {
4955     Expr::EvalResult Result;
4956     if (Length->EvaluateAsInt(Result, Context)) {
4957       // OpenMP 5.0, [2.1.5 Array Sections]
4958       // The length must evaluate to non-negative integers.
4959       llvm::APSInt LengthValue = Result.Val.getInt();
4960       if (LengthValue.isNegative()) {
4961         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4962             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4963             << Length->getSourceRange();
4964         return ExprError();
4965       }
4966     }
4967   } else if (ColonLocFirst.isValid() &&
4968              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4969                                       !OriginalTy->isVariableArrayType()))) {
4970     // OpenMP 5.0, [2.1.5 Array Sections]
4971     // When the size of the array dimension is not known, the length must be
4972     // specified explicitly.
4973     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4974         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4975     return ExprError();
4976   }
4977 
4978   if (Stride) {
4979     Expr::EvalResult Result;
4980     if (Stride->EvaluateAsInt(Result, Context)) {
4981       // OpenMP 5.0, [2.1.5 Array Sections]
4982       // The stride must evaluate to a positive integer.
4983       llvm::APSInt StrideValue = Result.Val.getInt();
4984       if (!StrideValue.isStrictlyPositive()) {
4985         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4986             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4987             << Stride->getSourceRange();
4988         return ExprError();
4989       }
4990     }
4991   }
4992 
4993   if (!Base->getType()->isSpecificPlaceholderType(
4994           BuiltinType::OMPArraySection)) {
4995     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4996     if (Result.isInvalid())
4997       return ExprError();
4998     Base = Result.get();
4999   }
5000   return new (Context) OMPArraySectionExpr(
5001       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5002       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5003 }
5004 
5005 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5006                                           SourceLocation RParenLoc,
5007                                           ArrayRef<Expr *> Dims,
5008                                           ArrayRef<SourceRange> Brackets) {
5009   if (Base->getType()->isPlaceholderType()) {
5010     ExprResult Result = CheckPlaceholderExpr(Base);
5011     if (Result.isInvalid())
5012       return ExprError();
5013     Result = DefaultLvalueConversion(Result.get());
5014     if (Result.isInvalid())
5015       return ExprError();
5016     Base = Result.get();
5017   }
5018   QualType BaseTy = Base->getType();
5019   // Delay analysis of the types/expressions if instantiation/specialization is
5020   // required.
5021   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5022     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5023                                        LParenLoc, RParenLoc, Dims, Brackets);
5024   if (!BaseTy->isPointerType() ||
5025       (!Base->isTypeDependent() &&
5026        BaseTy->getPointeeType()->isIncompleteType()))
5027     return ExprError(Diag(Base->getExprLoc(),
5028                           diag::err_omp_non_pointer_type_array_shaping_base)
5029                      << Base->getSourceRange());
5030 
5031   SmallVector<Expr *, 4> NewDims;
5032   bool ErrorFound = false;
5033   for (Expr *Dim : Dims) {
5034     if (Dim->getType()->isPlaceholderType()) {
5035       ExprResult Result = CheckPlaceholderExpr(Dim);
5036       if (Result.isInvalid()) {
5037         ErrorFound = true;
5038         continue;
5039       }
5040       Result = DefaultLvalueConversion(Result.get());
5041       if (Result.isInvalid()) {
5042         ErrorFound = true;
5043         continue;
5044       }
5045       Dim = Result.get();
5046     }
5047     if (!Dim->isTypeDependent()) {
5048       ExprResult Result =
5049           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5050       if (Result.isInvalid()) {
5051         ErrorFound = true;
5052         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5053             << Dim->getSourceRange();
5054         continue;
5055       }
5056       Dim = Result.get();
5057       Expr::EvalResult EvResult;
5058       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5059         // OpenMP 5.0, [2.1.4 Array Shaping]
5060         // Each si is an integral type expression that must evaluate to a
5061         // positive integer.
5062         llvm::APSInt Value = EvResult.Val.getInt();
5063         if (!Value.isStrictlyPositive()) {
5064           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5065               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5066               << Dim->getSourceRange();
5067           ErrorFound = true;
5068           continue;
5069         }
5070       }
5071     }
5072     NewDims.push_back(Dim);
5073   }
5074   if (ErrorFound)
5075     return ExprError();
5076   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5077                                      LParenLoc, RParenLoc, NewDims, Brackets);
5078 }
5079 
5080 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5081                                       SourceLocation LLoc, SourceLocation RLoc,
5082                                       ArrayRef<OMPIteratorData> Data) {
5083   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5084   bool IsCorrect = true;
5085   for (const OMPIteratorData &D : Data) {
5086     TypeSourceInfo *TInfo = nullptr;
5087     SourceLocation StartLoc;
5088     QualType DeclTy;
5089     if (!D.Type.getAsOpaquePtr()) {
5090       // OpenMP 5.0, 2.1.6 Iterators
5091       // In an iterator-specifier, if the iterator-type is not specified then
5092       // the type of that iterator is of int type.
5093       DeclTy = Context.IntTy;
5094       StartLoc = D.DeclIdentLoc;
5095     } else {
5096       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5097       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5098     }
5099 
5100     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5101                              DeclTy->containsUnexpandedParameterPack() ||
5102                              DeclTy->isInstantiationDependentType();
5103     if (!IsDeclTyDependent) {
5104       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5105         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5106         // The iterator-type must be an integral or pointer type.
5107         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5108             << DeclTy;
5109         IsCorrect = false;
5110         continue;
5111       }
5112       if (DeclTy.isConstant(Context)) {
5113         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5114         // The iterator-type must not be const qualified.
5115         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5116             << DeclTy;
5117         IsCorrect = false;
5118         continue;
5119       }
5120     }
5121 
5122     // Iterator declaration.
5123     assert(D.DeclIdent && "Identifier expected.");
5124     // Always try to create iterator declarator to avoid extra error messages
5125     // about unknown declarations use.
5126     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5127                                D.DeclIdent, DeclTy, TInfo, SC_None);
5128     VD->setImplicit();
5129     if (S) {
5130       // Check for conflicting previous declaration.
5131       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5132       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5133                             ForVisibleRedeclaration);
5134       Previous.suppressDiagnostics();
5135       LookupName(Previous, S);
5136 
5137       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5138                            /*AllowInlineNamespace=*/false);
5139       if (!Previous.empty()) {
5140         NamedDecl *Old = Previous.getRepresentativeDecl();
5141         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5142         Diag(Old->getLocation(), diag::note_previous_definition);
5143       } else {
5144         PushOnScopeChains(VD, S);
5145       }
5146     } else {
5147       CurContext->addDecl(VD);
5148     }
5149     Expr *Begin = D.Range.Begin;
5150     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5151       ExprResult BeginRes =
5152           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5153       Begin = BeginRes.get();
5154     }
5155     Expr *End = D.Range.End;
5156     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5157       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5158       End = EndRes.get();
5159     }
5160     Expr *Step = D.Range.Step;
5161     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5162       if (!Step->getType()->isIntegralType(Context)) {
5163         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5164             << Step << Step->getSourceRange();
5165         IsCorrect = false;
5166         continue;
5167       }
5168       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5169       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5170       // If the step expression of a range-specification equals zero, the
5171       // behavior is unspecified.
5172       if (Result && Result->isNullValue()) {
5173         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5174             << Step << Step->getSourceRange();
5175         IsCorrect = false;
5176         continue;
5177       }
5178     }
5179     if (!Begin || !End || !IsCorrect) {
5180       IsCorrect = false;
5181       continue;
5182     }
5183     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5184     IDElem.IteratorDecl = VD;
5185     IDElem.AssignmentLoc = D.AssignLoc;
5186     IDElem.Range.Begin = Begin;
5187     IDElem.Range.End = End;
5188     IDElem.Range.Step = Step;
5189     IDElem.ColonLoc = D.ColonLoc;
5190     IDElem.SecondColonLoc = D.SecColonLoc;
5191   }
5192   if (!IsCorrect) {
5193     // Invalidate all created iterator declarations if error is found.
5194     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5195       if (Decl *ID = D.IteratorDecl)
5196         ID->setInvalidDecl();
5197     }
5198     return ExprError();
5199   }
5200   SmallVector<OMPIteratorHelperData, 4> Helpers;
5201   if (!CurContext->isDependentContext()) {
5202     // Build number of ityeration for each iteration range.
5203     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5204     // ((Begini-Stepi-1-Endi) / -Stepi);
5205     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5206       // (Endi - Begini)
5207       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5208                                           D.Range.Begin);
5209       if(!Res.isUsable()) {
5210         IsCorrect = false;
5211         continue;
5212       }
5213       ExprResult St, St1;
5214       if (D.Range.Step) {
5215         St = D.Range.Step;
5216         // (Endi - Begini) + Stepi
5217         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5218         if (!Res.isUsable()) {
5219           IsCorrect = false;
5220           continue;
5221         }
5222         // (Endi - Begini) + Stepi - 1
5223         Res =
5224             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5225                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5226         if (!Res.isUsable()) {
5227           IsCorrect = false;
5228           continue;
5229         }
5230         // ((Endi - Begini) + Stepi - 1) / Stepi
5231         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5232         if (!Res.isUsable()) {
5233           IsCorrect = false;
5234           continue;
5235         }
5236         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5237         // (Begini - Endi)
5238         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5239                                              D.Range.Begin, D.Range.End);
5240         if (!Res1.isUsable()) {
5241           IsCorrect = false;
5242           continue;
5243         }
5244         // (Begini - Endi) - Stepi
5245         Res1 =
5246             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5247         if (!Res1.isUsable()) {
5248           IsCorrect = false;
5249           continue;
5250         }
5251         // (Begini - Endi) - Stepi - 1
5252         Res1 =
5253             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5254                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5255         if (!Res1.isUsable()) {
5256           IsCorrect = false;
5257           continue;
5258         }
5259         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5260         Res1 =
5261             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5262         if (!Res1.isUsable()) {
5263           IsCorrect = false;
5264           continue;
5265         }
5266         // Stepi > 0.
5267         ExprResult CmpRes =
5268             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5269                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5270         if (!CmpRes.isUsable()) {
5271           IsCorrect = false;
5272           continue;
5273         }
5274         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5275                                  Res.get(), Res1.get());
5276         if (!Res.isUsable()) {
5277           IsCorrect = false;
5278           continue;
5279         }
5280       }
5281       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5282       if (!Res.isUsable()) {
5283         IsCorrect = false;
5284         continue;
5285       }
5286 
5287       // Build counter update.
5288       // Build counter.
5289       auto *CounterVD =
5290           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5291                           D.IteratorDecl->getBeginLoc(), nullptr,
5292                           Res.get()->getType(), nullptr, SC_None);
5293       CounterVD->setImplicit();
5294       ExprResult RefRes =
5295           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5296                            D.IteratorDecl->getBeginLoc());
5297       // Build counter update.
5298       // I = Begini + counter * Stepi;
5299       ExprResult UpdateRes;
5300       if (D.Range.Step) {
5301         UpdateRes = CreateBuiltinBinOp(
5302             D.AssignmentLoc, BO_Mul,
5303             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5304       } else {
5305         UpdateRes = DefaultLvalueConversion(RefRes.get());
5306       }
5307       if (!UpdateRes.isUsable()) {
5308         IsCorrect = false;
5309         continue;
5310       }
5311       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5312                                      UpdateRes.get());
5313       if (!UpdateRes.isUsable()) {
5314         IsCorrect = false;
5315         continue;
5316       }
5317       ExprResult VDRes =
5318           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5319                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5320                            D.IteratorDecl->getBeginLoc());
5321       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5322                                      UpdateRes.get());
5323       if (!UpdateRes.isUsable()) {
5324         IsCorrect = false;
5325         continue;
5326       }
5327       UpdateRes =
5328           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5329       if (!UpdateRes.isUsable()) {
5330         IsCorrect = false;
5331         continue;
5332       }
5333       ExprResult CounterUpdateRes =
5334           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5335       if (!CounterUpdateRes.isUsable()) {
5336         IsCorrect = false;
5337         continue;
5338       }
5339       CounterUpdateRes =
5340           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5341       if (!CounterUpdateRes.isUsable()) {
5342         IsCorrect = false;
5343         continue;
5344       }
5345       OMPIteratorHelperData &HD = Helpers.emplace_back();
5346       HD.CounterVD = CounterVD;
5347       HD.Upper = Res.get();
5348       HD.Update = UpdateRes.get();
5349       HD.CounterUpdate = CounterUpdateRes.get();
5350     }
5351   } else {
5352     Helpers.assign(ID.size(), {});
5353   }
5354   if (!IsCorrect) {
5355     // Invalidate all created iterator declarations if error is found.
5356     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5357       if (Decl *ID = D.IteratorDecl)
5358         ID->setInvalidDecl();
5359     }
5360     return ExprError();
5361   }
5362   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5363                                  LLoc, RLoc, ID, Helpers);
5364 }
5365 
5366 ExprResult
5367 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5368                                       Expr *Idx, SourceLocation RLoc) {
5369   Expr *LHSExp = Base;
5370   Expr *RHSExp = Idx;
5371 
5372   ExprValueKind VK = VK_LValue;
5373   ExprObjectKind OK = OK_Ordinary;
5374 
5375   // Per C++ core issue 1213, the result is an xvalue if either operand is
5376   // a non-lvalue array, and an lvalue otherwise.
5377   if (getLangOpts().CPlusPlus11) {
5378     for (auto *Op : {LHSExp, RHSExp}) {
5379       Op = Op->IgnoreImplicit();
5380       if (Op->getType()->isArrayType() && !Op->isLValue())
5381         VK = VK_XValue;
5382     }
5383   }
5384 
5385   // Perform default conversions.
5386   if (!LHSExp->getType()->getAs<VectorType>()) {
5387     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5388     if (Result.isInvalid())
5389       return ExprError();
5390     LHSExp = Result.get();
5391   }
5392   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5393   if (Result.isInvalid())
5394     return ExprError();
5395   RHSExp = Result.get();
5396 
5397   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5398 
5399   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5400   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5401   // in the subscript position. As a result, we need to derive the array base
5402   // and index from the expression types.
5403   Expr *BaseExpr, *IndexExpr;
5404   QualType ResultType;
5405   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5406     BaseExpr = LHSExp;
5407     IndexExpr = RHSExp;
5408     ResultType = Context.DependentTy;
5409   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5410     BaseExpr = LHSExp;
5411     IndexExpr = RHSExp;
5412     ResultType = PTy->getPointeeType();
5413   } else if (const ObjCObjectPointerType *PTy =
5414                LHSTy->getAs<ObjCObjectPointerType>()) {
5415     BaseExpr = LHSExp;
5416     IndexExpr = RHSExp;
5417 
5418     // Use custom logic if this should be the pseudo-object subscript
5419     // expression.
5420     if (!LangOpts.isSubscriptPointerArithmetic())
5421       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5422                                           nullptr);
5423 
5424     ResultType = PTy->getPointeeType();
5425   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5426      // Handle the uncommon case of "123[Ptr]".
5427     BaseExpr = RHSExp;
5428     IndexExpr = LHSExp;
5429     ResultType = PTy->getPointeeType();
5430   } else if (const ObjCObjectPointerType *PTy =
5431                RHSTy->getAs<ObjCObjectPointerType>()) {
5432      // Handle the uncommon case of "123[Ptr]".
5433     BaseExpr = RHSExp;
5434     IndexExpr = LHSExp;
5435     ResultType = PTy->getPointeeType();
5436     if (!LangOpts.isSubscriptPointerArithmetic()) {
5437       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5438         << ResultType << BaseExpr->getSourceRange();
5439       return ExprError();
5440     }
5441   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5442     BaseExpr = LHSExp;    // vectors: V[123]
5443     IndexExpr = RHSExp;
5444     // We apply C++ DR1213 to vector subscripting too.
5445     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5446       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5447       if (Materialized.isInvalid())
5448         return ExprError();
5449       LHSExp = Materialized.get();
5450     }
5451     VK = LHSExp->getValueKind();
5452     if (VK != VK_RValue)
5453       OK = OK_VectorComponent;
5454 
5455     ResultType = VTy->getElementType();
5456     QualType BaseType = BaseExpr->getType();
5457     Qualifiers BaseQuals = BaseType.getQualifiers();
5458     Qualifiers MemberQuals = ResultType.getQualifiers();
5459     Qualifiers Combined = BaseQuals + MemberQuals;
5460     if (Combined != MemberQuals)
5461       ResultType = Context.getQualifiedType(ResultType, Combined);
5462   } else if (LHSTy->isArrayType()) {
5463     // If we see an array that wasn't promoted by
5464     // DefaultFunctionArrayLvalueConversion, it must be an array that
5465     // wasn't promoted because of the C90 rule that doesn't
5466     // allow promoting non-lvalue arrays.  Warn, then
5467     // force the promotion here.
5468     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5469         << LHSExp->getSourceRange();
5470     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5471                                CK_ArrayToPointerDecay).get();
5472     LHSTy = LHSExp->getType();
5473 
5474     BaseExpr = LHSExp;
5475     IndexExpr = RHSExp;
5476     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5477   } else if (RHSTy->isArrayType()) {
5478     // Same as previous, except for 123[f().a] case
5479     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5480         << RHSExp->getSourceRange();
5481     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5482                                CK_ArrayToPointerDecay).get();
5483     RHSTy = RHSExp->getType();
5484 
5485     BaseExpr = RHSExp;
5486     IndexExpr = LHSExp;
5487     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5488   } else {
5489     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5490        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5491   }
5492   // C99 6.5.2.1p1
5493   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5494     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5495                      << IndexExpr->getSourceRange());
5496 
5497   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5498        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5499          && !IndexExpr->isTypeDependent())
5500     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5501 
5502   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5503   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5504   // type. Note that Functions are not objects, and that (in C99 parlance)
5505   // incomplete types are not object types.
5506   if (ResultType->isFunctionType()) {
5507     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5508         << ResultType << BaseExpr->getSourceRange();
5509     return ExprError();
5510   }
5511 
5512   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5513     // GNU extension: subscripting on pointer to void
5514     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5515       << BaseExpr->getSourceRange();
5516 
5517     // C forbids expressions of unqualified void type from being l-values.
5518     // See IsCForbiddenLValueType.
5519     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5520   } else if (!ResultType->isDependentType() &&
5521              RequireCompleteSizedType(
5522                  LLoc, ResultType,
5523                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5524     return ExprError();
5525 
5526   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5527          !ResultType.isCForbiddenLValueType());
5528 
5529   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5530       FunctionScopes.size() > 1) {
5531     if (auto *TT =
5532             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5533       for (auto I = FunctionScopes.rbegin(),
5534                 E = std::prev(FunctionScopes.rend());
5535            I != E; ++I) {
5536         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5537         if (CSI == nullptr)
5538           break;
5539         DeclContext *DC = nullptr;
5540         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5541           DC = LSI->CallOperator;
5542         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5543           DC = CRSI->TheCapturedDecl;
5544         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5545           DC = BSI->TheDecl;
5546         if (DC) {
5547           if (DC->containsDecl(TT->getDecl()))
5548             break;
5549           captureVariablyModifiedType(
5550               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5551         }
5552       }
5553     }
5554   }
5555 
5556   return new (Context)
5557       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5558 }
5559 
5560 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5561                                   ParmVarDecl *Param) {
5562   if (Param->hasUnparsedDefaultArg()) {
5563     // If we've already cleared out the location for the default argument,
5564     // that means we're parsing it right now.
5565     if (!UnparsedDefaultArgLocs.count(Param)) {
5566       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5567       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5568       Param->setInvalidDecl();
5569       return true;
5570     }
5571 
5572     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5573         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5574     Diag(UnparsedDefaultArgLocs[Param],
5575          diag::note_default_argument_declared_here);
5576     return true;
5577   }
5578 
5579   if (Param->hasUninstantiatedDefaultArg() &&
5580       InstantiateDefaultArgument(CallLoc, FD, Param))
5581     return true;
5582 
5583   assert(Param->hasInit() && "default argument but no initializer?");
5584 
5585   // If the default expression creates temporaries, we need to
5586   // push them to the current stack of expression temporaries so they'll
5587   // be properly destroyed.
5588   // FIXME: We should really be rebuilding the default argument with new
5589   // bound temporaries; see the comment in PR5810.
5590   // We don't need to do that with block decls, though, because
5591   // blocks in default argument expression can never capture anything.
5592   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5593     // Set the "needs cleanups" bit regardless of whether there are
5594     // any explicit objects.
5595     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5596 
5597     // Append all the objects to the cleanup list.  Right now, this
5598     // should always be a no-op, because blocks in default argument
5599     // expressions should never be able to capture anything.
5600     assert(!Init->getNumObjects() &&
5601            "default argument expression has capturing blocks?");
5602   }
5603 
5604   // We already type-checked the argument, so we know it works.
5605   // Just mark all of the declarations in this potentially-evaluated expression
5606   // as being "referenced".
5607   EnterExpressionEvaluationContext EvalContext(
5608       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5609   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5610                                    /*SkipLocalVariables=*/true);
5611   return false;
5612 }
5613 
5614 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5615                                         FunctionDecl *FD, ParmVarDecl *Param) {
5616   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5617   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5618     return ExprError();
5619   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5620 }
5621 
5622 Sema::VariadicCallType
5623 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5624                           Expr *Fn) {
5625   if (Proto && Proto->isVariadic()) {
5626     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5627       return VariadicConstructor;
5628     else if (Fn && Fn->getType()->isBlockPointerType())
5629       return VariadicBlock;
5630     else if (FDecl) {
5631       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5632         if (Method->isInstance())
5633           return VariadicMethod;
5634     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5635       return VariadicMethod;
5636     return VariadicFunction;
5637   }
5638   return VariadicDoesNotApply;
5639 }
5640 
5641 namespace {
5642 class FunctionCallCCC final : public FunctionCallFilterCCC {
5643 public:
5644   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5645                   unsigned NumArgs, MemberExpr *ME)
5646       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5647         FunctionName(FuncName) {}
5648 
5649   bool ValidateCandidate(const TypoCorrection &candidate) override {
5650     if (!candidate.getCorrectionSpecifier() ||
5651         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5652       return false;
5653     }
5654 
5655     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5656   }
5657 
5658   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5659     return std::make_unique<FunctionCallCCC>(*this);
5660   }
5661 
5662 private:
5663   const IdentifierInfo *const FunctionName;
5664 };
5665 }
5666 
5667 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5668                                                FunctionDecl *FDecl,
5669                                                ArrayRef<Expr *> Args) {
5670   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5671   DeclarationName FuncName = FDecl->getDeclName();
5672   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5673 
5674   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5675   if (TypoCorrection Corrected = S.CorrectTypo(
5676           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5677           S.getScopeForContext(S.CurContext), nullptr, CCC,
5678           Sema::CTK_ErrorRecovery)) {
5679     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5680       if (Corrected.isOverloaded()) {
5681         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5682         OverloadCandidateSet::iterator Best;
5683         for (NamedDecl *CD : Corrected) {
5684           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5685             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5686                                    OCS);
5687         }
5688         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5689         case OR_Success:
5690           ND = Best->FoundDecl;
5691           Corrected.setCorrectionDecl(ND);
5692           break;
5693         default:
5694           break;
5695         }
5696       }
5697       ND = ND->getUnderlyingDecl();
5698       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5699         return Corrected;
5700     }
5701   }
5702   return TypoCorrection();
5703 }
5704 
5705 /// ConvertArgumentsForCall - Converts the arguments specified in
5706 /// Args/NumArgs to the parameter types of the function FDecl with
5707 /// function prototype Proto. Call is the call expression itself, and
5708 /// Fn is the function expression. For a C++ member function, this
5709 /// routine does not attempt to convert the object argument. Returns
5710 /// true if the call is ill-formed.
5711 bool
5712 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5713                               FunctionDecl *FDecl,
5714                               const FunctionProtoType *Proto,
5715                               ArrayRef<Expr *> Args,
5716                               SourceLocation RParenLoc,
5717                               bool IsExecConfig) {
5718   // Bail out early if calling a builtin with custom typechecking.
5719   if (FDecl)
5720     if (unsigned ID = FDecl->getBuiltinID())
5721       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5722         return false;
5723 
5724   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5725   // assignment, to the types of the corresponding parameter, ...
5726   unsigned NumParams = Proto->getNumParams();
5727   bool Invalid = false;
5728   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5729   unsigned FnKind = Fn->getType()->isBlockPointerType()
5730                        ? 1 /* block */
5731                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5732                                        : 0 /* function */);
5733 
5734   // If too few arguments are available (and we don't have default
5735   // arguments for the remaining parameters), don't make the call.
5736   if (Args.size() < NumParams) {
5737     if (Args.size() < MinArgs) {
5738       TypoCorrection TC;
5739       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5740         unsigned diag_id =
5741             MinArgs == NumParams && !Proto->isVariadic()
5742                 ? diag::err_typecheck_call_too_few_args_suggest
5743                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5744         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5745                                         << static_cast<unsigned>(Args.size())
5746                                         << TC.getCorrectionRange());
5747       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5748         Diag(RParenLoc,
5749              MinArgs == NumParams && !Proto->isVariadic()
5750                  ? diag::err_typecheck_call_too_few_args_one
5751                  : diag::err_typecheck_call_too_few_args_at_least_one)
5752             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5753       else
5754         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5755                             ? diag::err_typecheck_call_too_few_args
5756                             : diag::err_typecheck_call_too_few_args_at_least)
5757             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5758             << Fn->getSourceRange();
5759 
5760       // Emit the location of the prototype.
5761       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5762         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5763 
5764       return true;
5765     }
5766     // We reserve space for the default arguments when we create
5767     // the call expression, before calling ConvertArgumentsForCall.
5768     assert((Call->getNumArgs() == NumParams) &&
5769            "We should have reserved space for the default arguments before!");
5770   }
5771 
5772   // If too many are passed and not variadic, error on the extras and drop
5773   // them.
5774   if (Args.size() > NumParams) {
5775     if (!Proto->isVariadic()) {
5776       TypoCorrection TC;
5777       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5778         unsigned diag_id =
5779             MinArgs == NumParams && !Proto->isVariadic()
5780                 ? diag::err_typecheck_call_too_many_args_suggest
5781                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5782         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5783                                         << static_cast<unsigned>(Args.size())
5784                                         << TC.getCorrectionRange());
5785       } else if (NumParams == 1 && FDecl &&
5786                  FDecl->getParamDecl(0)->getDeclName())
5787         Diag(Args[NumParams]->getBeginLoc(),
5788              MinArgs == NumParams
5789                  ? diag::err_typecheck_call_too_many_args_one
5790                  : diag::err_typecheck_call_too_many_args_at_most_one)
5791             << FnKind << FDecl->getParamDecl(0)
5792             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5793             << SourceRange(Args[NumParams]->getBeginLoc(),
5794                            Args.back()->getEndLoc());
5795       else
5796         Diag(Args[NumParams]->getBeginLoc(),
5797              MinArgs == NumParams
5798                  ? diag::err_typecheck_call_too_many_args
5799                  : diag::err_typecheck_call_too_many_args_at_most)
5800             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5801             << Fn->getSourceRange()
5802             << SourceRange(Args[NumParams]->getBeginLoc(),
5803                            Args.back()->getEndLoc());
5804 
5805       // Emit the location of the prototype.
5806       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5807         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5808 
5809       // This deletes the extra arguments.
5810       Call->shrinkNumArgs(NumParams);
5811       return true;
5812     }
5813   }
5814   SmallVector<Expr *, 8> AllArgs;
5815   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5816 
5817   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5818                                    AllArgs, CallType);
5819   if (Invalid)
5820     return true;
5821   unsigned TotalNumArgs = AllArgs.size();
5822   for (unsigned i = 0; i < TotalNumArgs; ++i)
5823     Call->setArg(i, AllArgs[i]);
5824 
5825   return false;
5826 }
5827 
5828 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5829                                   const FunctionProtoType *Proto,
5830                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5831                                   SmallVectorImpl<Expr *> &AllArgs,
5832                                   VariadicCallType CallType, bool AllowExplicit,
5833                                   bool IsListInitialization) {
5834   unsigned NumParams = Proto->getNumParams();
5835   bool Invalid = false;
5836   size_t ArgIx = 0;
5837   // Continue to check argument types (even if we have too few/many args).
5838   for (unsigned i = FirstParam; i < NumParams; i++) {
5839     QualType ProtoArgType = Proto->getParamType(i);
5840 
5841     Expr *Arg;
5842     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5843     if (ArgIx < Args.size()) {
5844       Arg = Args[ArgIx++];
5845 
5846       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5847                               diag::err_call_incomplete_argument, Arg))
5848         return true;
5849 
5850       // Strip the unbridged-cast placeholder expression off, if applicable.
5851       bool CFAudited = false;
5852       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5853           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5854           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5855         Arg = stripARCUnbridgedCast(Arg);
5856       else if (getLangOpts().ObjCAutoRefCount &&
5857                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5858                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5859         CFAudited = true;
5860 
5861       if (Proto->getExtParameterInfo(i).isNoEscape())
5862         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5863           BE->getBlockDecl()->setDoesNotEscape();
5864 
5865       InitializedEntity Entity =
5866           Param ? InitializedEntity::InitializeParameter(Context, Param,
5867                                                          ProtoArgType)
5868                 : InitializedEntity::InitializeParameter(
5869                       Context, ProtoArgType, Proto->isParamConsumed(i));
5870 
5871       // Remember that parameter belongs to a CF audited API.
5872       if (CFAudited)
5873         Entity.setParameterCFAudited();
5874 
5875       ExprResult ArgE = PerformCopyInitialization(
5876           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5877       if (ArgE.isInvalid())
5878         return true;
5879 
5880       Arg = ArgE.getAs<Expr>();
5881     } else {
5882       assert(Param && "can't use default arguments without a known callee");
5883 
5884       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5885       if (ArgExpr.isInvalid())
5886         return true;
5887 
5888       Arg = ArgExpr.getAs<Expr>();
5889     }
5890 
5891     // Check for array bounds violations for each argument to the call. This
5892     // check only triggers warnings when the argument isn't a more complex Expr
5893     // with its own checking, such as a BinaryOperator.
5894     CheckArrayAccess(Arg);
5895 
5896     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5897     CheckStaticArrayArgument(CallLoc, Param, Arg);
5898 
5899     AllArgs.push_back(Arg);
5900   }
5901 
5902   // If this is a variadic call, handle args passed through "...".
5903   if (CallType != VariadicDoesNotApply) {
5904     // Assume that extern "C" functions with variadic arguments that
5905     // return __unknown_anytype aren't *really* variadic.
5906     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5907         FDecl->isExternC()) {
5908       for (Expr *A : Args.slice(ArgIx)) {
5909         QualType paramType; // ignored
5910         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5911         Invalid |= arg.isInvalid();
5912         AllArgs.push_back(arg.get());
5913       }
5914 
5915     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5916     } else {
5917       for (Expr *A : Args.slice(ArgIx)) {
5918         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5919         Invalid |= Arg.isInvalid();
5920         AllArgs.push_back(Arg.get());
5921       }
5922     }
5923 
5924     // Check for array bounds violations.
5925     for (Expr *A : Args.slice(ArgIx))
5926       CheckArrayAccess(A);
5927   }
5928   return Invalid;
5929 }
5930 
5931 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5932   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5933   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5934     TL = DTL.getOriginalLoc();
5935   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5936     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5937       << ATL.getLocalSourceRange();
5938 }
5939 
5940 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5941 /// array parameter, check that it is non-null, and that if it is formed by
5942 /// array-to-pointer decay, the underlying array is sufficiently large.
5943 ///
5944 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5945 /// array type derivation, then for each call to the function, the value of the
5946 /// corresponding actual argument shall provide access to the first element of
5947 /// an array with at least as many elements as specified by the size expression.
5948 void
5949 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5950                                ParmVarDecl *Param,
5951                                const Expr *ArgExpr) {
5952   // Static array parameters are not supported in C++.
5953   if (!Param || getLangOpts().CPlusPlus)
5954     return;
5955 
5956   QualType OrigTy = Param->getOriginalType();
5957 
5958   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5959   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5960     return;
5961 
5962   if (ArgExpr->isNullPointerConstant(Context,
5963                                      Expr::NPC_NeverValueDependent)) {
5964     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5965     DiagnoseCalleeStaticArrayParam(*this, Param);
5966     return;
5967   }
5968 
5969   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5970   if (!CAT)
5971     return;
5972 
5973   const ConstantArrayType *ArgCAT =
5974     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5975   if (!ArgCAT)
5976     return;
5977 
5978   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5979                                              ArgCAT->getElementType())) {
5980     if (ArgCAT->getSize().ult(CAT->getSize())) {
5981       Diag(CallLoc, diag::warn_static_array_too_small)
5982           << ArgExpr->getSourceRange()
5983           << (unsigned)ArgCAT->getSize().getZExtValue()
5984           << (unsigned)CAT->getSize().getZExtValue() << 0;
5985       DiagnoseCalleeStaticArrayParam(*this, Param);
5986     }
5987     return;
5988   }
5989 
5990   Optional<CharUnits> ArgSize =
5991       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5992   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5993   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5994     Diag(CallLoc, diag::warn_static_array_too_small)
5995         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5996         << (unsigned)ParmSize->getQuantity() << 1;
5997     DiagnoseCalleeStaticArrayParam(*this, Param);
5998   }
5999 }
6000 
6001 /// Given a function expression of unknown-any type, try to rebuild it
6002 /// to have a function type.
6003 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6004 
6005 /// Is the given type a placeholder that we need to lower out
6006 /// immediately during argument processing?
6007 static bool isPlaceholderToRemoveAsArg(QualType type) {
6008   // Placeholders are never sugared.
6009   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6010   if (!placeholder) return false;
6011 
6012   switch (placeholder->getKind()) {
6013   // Ignore all the non-placeholder types.
6014 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6015   case BuiltinType::Id:
6016 #include "clang/Basic/OpenCLImageTypes.def"
6017 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6018   case BuiltinType::Id:
6019 #include "clang/Basic/OpenCLExtensionTypes.def"
6020   // In practice we'll never use this, since all SVE types are sugared
6021   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6022 #define SVE_TYPE(Name, Id, SingletonId) \
6023   case BuiltinType::Id:
6024 #include "clang/Basic/AArch64SVEACLETypes.def"
6025 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6026 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6027 #include "clang/AST/BuiltinTypes.def"
6028     return false;
6029 
6030   // We cannot lower out overload sets; they might validly be resolved
6031   // by the call machinery.
6032   case BuiltinType::Overload:
6033     return false;
6034 
6035   // Unbridged casts in ARC can be handled in some call positions and
6036   // should be left in place.
6037   case BuiltinType::ARCUnbridgedCast:
6038     return false;
6039 
6040   // Pseudo-objects should be converted as soon as possible.
6041   case BuiltinType::PseudoObject:
6042     return true;
6043 
6044   // The debugger mode could theoretically but currently does not try
6045   // to resolve unknown-typed arguments based on known parameter types.
6046   case BuiltinType::UnknownAny:
6047     return true;
6048 
6049   // These are always invalid as call arguments and should be reported.
6050   case BuiltinType::BoundMember:
6051   case BuiltinType::BuiltinFn:
6052   case BuiltinType::IncompleteMatrixIdx:
6053   case BuiltinType::OMPArraySection:
6054   case BuiltinType::OMPArrayShaping:
6055   case BuiltinType::OMPIterator:
6056     return true;
6057 
6058   }
6059   llvm_unreachable("bad builtin type kind");
6060 }
6061 
6062 /// Check an argument list for placeholders that we won't try to
6063 /// handle later.
6064 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6065   // Apply this processing to all the arguments at once instead of
6066   // dying at the first failure.
6067   bool hasInvalid = false;
6068   for (size_t i = 0, e = args.size(); i != e; i++) {
6069     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6070       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6071       if (result.isInvalid()) hasInvalid = true;
6072       else args[i] = result.get();
6073     } else if (hasInvalid) {
6074       (void)S.CorrectDelayedTyposInExpr(args[i]);
6075     }
6076   }
6077   return hasInvalid;
6078 }
6079 
6080 /// If a builtin function has a pointer argument with no explicit address
6081 /// space, then it should be able to accept a pointer to any address
6082 /// space as input.  In order to do this, we need to replace the
6083 /// standard builtin declaration with one that uses the same address space
6084 /// as the call.
6085 ///
6086 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6087 ///                  it does not contain any pointer arguments without
6088 ///                  an address space qualifer.  Otherwise the rewritten
6089 ///                  FunctionDecl is returned.
6090 /// TODO: Handle pointer return types.
6091 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6092                                                 FunctionDecl *FDecl,
6093                                                 MultiExprArg ArgExprs) {
6094 
6095   QualType DeclType = FDecl->getType();
6096   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6097 
6098   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6099       ArgExprs.size() < FT->getNumParams())
6100     return nullptr;
6101 
6102   bool NeedsNewDecl = false;
6103   unsigned i = 0;
6104   SmallVector<QualType, 8> OverloadParams;
6105 
6106   for (QualType ParamType : FT->param_types()) {
6107 
6108     // Convert array arguments to pointer to simplify type lookup.
6109     ExprResult ArgRes =
6110         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6111     if (ArgRes.isInvalid())
6112       return nullptr;
6113     Expr *Arg = ArgRes.get();
6114     QualType ArgType = Arg->getType();
6115     if (!ParamType->isPointerType() ||
6116         ParamType.hasAddressSpace() ||
6117         !ArgType->isPointerType() ||
6118         !ArgType->getPointeeType().hasAddressSpace()) {
6119       OverloadParams.push_back(ParamType);
6120       continue;
6121     }
6122 
6123     QualType PointeeType = ParamType->getPointeeType();
6124     if (PointeeType.hasAddressSpace())
6125       continue;
6126 
6127     NeedsNewDecl = true;
6128     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6129 
6130     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6131     OverloadParams.push_back(Context.getPointerType(PointeeType));
6132   }
6133 
6134   if (!NeedsNewDecl)
6135     return nullptr;
6136 
6137   FunctionProtoType::ExtProtoInfo EPI;
6138   EPI.Variadic = FT->isVariadic();
6139   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6140                                                 OverloadParams, EPI);
6141   DeclContext *Parent = FDecl->getParent();
6142   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6143                                                     FDecl->getLocation(),
6144                                                     FDecl->getLocation(),
6145                                                     FDecl->getIdentifier(),
6146                                                     OverloadTy,
6147                                                     /*TInfo=*/nullptr,
6148                                                     SC_Extern, false,
6149                                                     /*hasPrototype=*/true);
6150   SmallVector<ParmVarDecl*, 16> Params;
6151   FT = cast<FunctionProtoType>(OverloadTy);
6152   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6153     QualType ParamType = FT->getParamType(i);
6154     ParmVarDecl *Parm =
6155         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6156                                 SourceLocation(), nullptr, ParamType,
6157                                 /*TInfo=*/nullptr, SC_None, nullptr);
6158     Parm->setScopeInfo(0, i);
6159     Params.push_back(Parm);
6160   }
6161   OverloadDecl->setParams(Params);
6162   return OverloadDecl;
6163 }
6164 
6165 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6166                                     FunctionDecl *Callee,
6167                                     MultiExprArg ArgExprs) {
6168   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6169   // similar attributes) really don't like it when functions are called with an
6170   // invalid number of args.
6171   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6172                          /*PartialOverloading=*/false) &&
6173       !Callee->isVariadic())
6174     return;
6175   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6176     return;
6177 
6178   if (const EnableIfAttr *Attr =
6179           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6180     S.Diag(Fn->getBeginLoc(),
6181            isa<CXXMethodDecl>(Callee)
6182                ? diag::err_ovl_no_viable_member_function_in_call
6183                : diag::err_ovl_no_viable_function_in_call)
6184         << Callee << Callee->getSourceRange();
6185     S.Diag(Callee->getLocation(),
6186            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6187         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6188     return;
6189   }
6190 }
6191 
6192 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6193     const UnresolvedMemberExpr *const UME, Sema &S) {
6194 
6195   const auto GetFunctionLevelDCIfCXXClass =
6196       [](Sema &S) -> const CXXRecordDecl * {
6197     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6198     if (!DC || !DC->getParent())
6199       return nullptr;
6200 
6201     // If the call to some member function was made from within a member
6202     // function body 'M' return return 'M's parent.
6203     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6204       return MD->getParent()->getCanonicalDecl();
6205     // else the call was made from within a default member initializer of a
6206     // class, so return the class.
6207     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6208       return RD->getCanonicalDecl();
6209     return nullptr;
6210   };
6211   // If our DeclContext is neither a member function nor a class (in the
6212   // case of a lambda in a default member initializer), we can't have an
6213   // enclosing 'this'.
6214 
6215   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6216   if (!CurParentClass)
6217     return false;
6218 
6219   // The naming class for implicit member functions call is the class in which
6220   // name lookup starts.
6221   const CXXRecordDecl *const NamingClass =
6222       UME->getNamingClass()->getCanonicalDecl();
6223   assert(NamingClass && "Must have naming class even for implicit access");
6224 
6225   // If the unresolved member functions were found in a 'naming class' that is
6226   // related (either the same or derived from) to the class that contains the
6227   // member function that itself contained the implicit member access.
6228 
6229   return CurParentClass == NamingClass ||
6230          CurParentClass->isDerivedFrom(NamingClass);
6231 }
6232 
6233 static void
6234 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6235     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6236 
6237   if (!UME)
6238     return;
6239 
6240   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6241   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6242   // already been captured, or if this is an implicit member function call (if
6243   // it isn't, an attempt to capture 'this' should already have been made).
6244   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6245       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6246     return;
6247 
6248   // Check if the naming class in which the unresolved members were found is
6249   // related (same as or is a base of) to the enclosing class.
6250 
6251   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6252     return;
6253 
6254 
6255   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6256   // If the enclosing function is not dependent, then this lambda is
6257   // capture ready, so if we can capture this, do so.
6258   if (!EnclosingFunctionCtx->isDependentContext()) {
6259     // If the current lambda and all enclosing lambdas can capture 'this' -
6260     // then go ahead and capture 'this' (since our unresolved overload set
6261     // contains at least one non-static member function).
6262     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6263       S.CheckCXXThisCapture(CallLoc);
6264   } else if (S.CurContext->isDependentContext()) {
6265     // ... since this is an implicit member reference, that might potentially
6266     // involve a 'this' capture, mark 'this' for potential capture in
6267     // enclosing lambdas.
6268     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6269       CurLSI->addPotentialThisCapture(CallLoc);
6270   }
6271 }
6272 
6273 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6274                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6275                                Expr *ExecConfig) {
6276   ExprResult Call =
6277       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6278   if (Call.isInvalid())
6279     return Call;
6280 
6281   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6282   // language modes.
6283   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6284     if (ULE->hasExplicitTemplateArgs() &&
6285         ULE->decls_begin() == ULE->decls_end()) {
6286       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6287                                  ? diag::warn_cxx17_compat_adl_only_template_id
6288                                  : diag::ext_adl_only_template_id)
6289           << ULE->getName();
6290     }
6291   }
6292 
6293   if (LangOpts.OpenMP)
6294     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6295                            ExecConfig);
6296 
6297   return Call;
6298 }
6299 
6300 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6301 /// This provides the location of the left/right parens and a list of comma
6302 /// locations.
6303 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6304                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6305                                Expr *ExecConfig, bool IsExecConfig) {
6306   // Since this might be a postfix expression, get rid of ParenListExprs.
6307   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6308   if (Result.isInvalid()) return ExprError();
6309   Fn = Result.get();
6310 
6311   if (checkArgsForPlaceholders(*this, ArgExprs))
6312     return ExprError();
6313 
6314   if (getLangOpts().CPlusPlus) {
6315     // If this is a pseudo-destructor expression, build the call immediately.
6316     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6317       if (!ArgExprs.empty()) {
6318         // Pseudo-destructor calls should not have any arguments.
6319         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6320             << FixItHint::CreateRemoval(
6321                    SourceRange(ArgExprs.front()->getBeginLoc(),
6322                                ArgExprs.back()->getEndLoc()));
6323       }
6324 
6325       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6326                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6327     }
6328     if (Fn->getType() == Context.PseudoObjectTy) {
6329       ExprResult result = CheckPlaceholderExpr(Fn);
6330       if (result.isInvalid()) return ExprError();
6331       Fn = result.get();
6332     }
6333 
6334     // Determine whether this is a dependent call inside a C++ template,
6335     // in which case we won't do any semantic analysis now.
6336     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6337       if (ExecConfig) {
6338         return CUDAKernelCallExpr::Create(
6339             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6340             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6341       } else {
6342 
6343         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6344             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6345             Fn->getBeginLoc());
6346 
6347         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6348                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6349       }
6350     }
6351 
6352     // Determine whether this is a call to an object (C++ [over.call.object]).
6353     if (Fn->getType()->isRecordType())
6354       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6355                                           RParenLoc);
6356 
6357     if (Fn->getType() == Context.UnknownAnyTy) {
6358       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6359       if (result.isInvalid()) return ExprError();
6360       Fn = result.get();
6361     }
6362 
6363     if (Fn->getType() == Context.BoundMemberTy) {
6364       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6365                                        RParenLoc);
6366     }
6367   }
6368 
6369   // Check for overloaded calls.  This can happen even in C due to extensions.
6370   if (Fn->getType() == Context.OverloadTy) {
6371     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6372 
6373     // We aren't supposed to apply this logic if there's an '&' involved.
6374     if (!find.HasFormOfMemberPointer) {
6375       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6376         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6377                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6378       OverloadExpr *ovl = find.Expression;
6379       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6380         return BuildOverloadedCallExpr(
6381             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6382             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6383       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6384                                        RParenLoc);
6385     }
6386   }
6387 
6388   // If we're directly calling a function, get the appropriate declaration.
6389   if (Fn->getType() == Context.UnknownAnyTy) {
6390     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6391     if (result.isInvalid()) return ExprError();
6392     Fn = result.get();
6393   }
6394 
6395   Expr *NakedFn = Fn->IgnoreParens();
6396 
6397   bool CallingNDeclIndirectly = false;
6398   NamedDecl *NDecl = nullptr;
6399   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6400     if (UnOp->getOpcode() == UO_AddrOf) {
6401       CallingNDeclIndirectly = true;
6402       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6403     }
6404   }
6405 
6406   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6407     NDecl = DRE->getDecl();
6408 
6409     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6410     if (FDecl && FDecl->getBuiltinID()) {
6411       // Rewrite the function decl for this builtin by replacing parameters
6412       // with no explicit address space with the address space of the arguments
6413       // in ArgExprs.
6414       if ((FDecl =
6415                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6416         NDecl = FDecl;
6417         Fn = DeclRefExpr::Create(
6418             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6419             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6420             nullptr, DRE->isNonOdrUse());
6421       }
6422     }
6423   } else if (isa<MemberExpr>(NakedFn))
6424     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6425 
6426   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6427     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6428                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6429       return ExprError();
6430 
6431     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6432       return ExprError();
6433 
6434     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6435   }
6436 
6437   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6438                                ExecConfig, IsExecConfig);
6439 }
6440 
6441 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6442 ///
6443 /// __builtin_astype( value, dst type )
6444 ///
6445 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6446                                  SourceLocation BuiltinLoc,
6447                                  SourceLocation RParenLoc) {
6448   ExprValueKind VK = VK_RValue;
6449   ExprObjectKind OK = OK_Ordinary;
6450   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6451   QualType SrcTy = E->getType();
6452   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6453     return ExprError(Diag(BuiltinLoc,
6454                           diag::err_invalid_astype_of_different_size)
6455                      << DstTy
6456                      << SrcTy
6457                      << E->getSourceRange());
6458   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6459 }
6460 
6461 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6462 /// provided arguments.
6463 ///
6464 /// __builtin_convertvector( value, dst type )
6465 ///
6466 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6467                                         SourceLocation BuiltinLoc,
6468                                         SourceLocation RParenLoc) {
6469   TypeSourceInfo *TInfo;
6470   GetTypeFromParser(ParsedDestTy, &TInfo);
6471   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6472 }
6473 
6474 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6475 /// i.e. an expression not of \p OverloadTy.  The expression should
6476 /// unary-convert to an expression of function-pointer or
6477 /// block-pointer type.
6478 ///
6479 /// \param NDecl the declaration being called, if available
6480 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6481                                        SourceLocation LParenLoc,
6482                                        ArrayRef<Expr *> Args,
6483                                        SourceLocation RParenLoc, Expr *Config,
6484                                        bool IsExecConfig, ADLCallKind UsesADL) {
6485   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6486   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6487 
6488   // Functions with 'interrupt' attribute cannot be called directly.
6489   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6490     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6491     return ExprError();
6492   }
6493 
6494   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6495   // so there's some risk when calling out to non-interrupt handler functions
6496   // that the callee might not preserve them. This is easy to diagnose here,
6497   // but can be very challenging to debug.
6498   if (auto *Caller = getCurFunctionDecl())
6499     if (Caller->hasAttr<ARMInterruptAttr>()) {
6500       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6501       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6502         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6503     }
6504 
6505   // Promote the function operand.
6506   // We special-case function promotion here because we only allow promoting
6507   // builtin functions to function pointers in the callee of a call.
6508   ExprResult Result;
6509   QualType ResultTy;
6510   if (BuiltinID &&
6511       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6512     // Extract the return type from the (builtin) function pointer type.
6513     // FIXME Several builtins still have setType in
6514     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6515     // Builtins.def to ensure they are correct before removing setType calls.
6516     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6517     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6518     ResultTy = FDecl->getCallResultType();
6519   } else {
6520     Result = CallExprUnaryConversions(Fn);
6521     ResultTy = Context.BoolTy;
6522   }
6523   if (Result.isInvalid())
6524     return ExprError();
6525   Fn = Result.get();
6526 
6527   // Check for a valid function type, but only if it is not a builtin which
6528   // requires custom type checking. These will be handled by
6529   // CheckBuiltinFunctionCall below just after creation of the call expression.
6530   const FunctionType *FuncT = nullptr;
6531   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6532   retry:
6533     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6534       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6535       // have type pointer to function".
6536       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6537       if (!FuncT)
6538         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6539                          << Fn->getType() << Fn->getSourceRange());
6540     } else if (const BlockPointerType *BPT =
6541                    Fn->getType()->getAs<BlockPointerType>()) {
6542       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6543     } else {
6544       // Handle calls to expressions of unknown-any type.
6545       if (Fn->getType() == Context.UnknownAnyTy) {
6546         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6547         if (rewrite.isInvalid())
6548           return ExprError();
6549         Fn = rewrite.get();
6550         goto retry;
6551       }
6552 
6553       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6554                        << Fn->getType() << Fn->getSourceRange());
6555     }
6556   }
6557 
6558   // Get the number of parameters in the function prototype, if any.
6559   // We will allocate space for max(Args.size(), NumParams) arguments
6560   // in the call expression.
6561   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6562   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6563 
6564   CallExpr *TheCall;
6565   if (Config) {
6566     assert(UsesADL == ADLCallKind::NotADL &&
6567            "CUDAKernelCallExpr should not use ADL");
6568     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6569                                          Args, ResultTy, VK_RValue, RParenLoc,
6570                                          CurFPFeatureOverrides(), NumParams);
6571   } else {
6572     TheCall =
6573         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6574                          CurFPFeatureOverrides(), NumParams, UsesADL);
6575   }
6576 
6577   if (!getLangOpts().CPlusPlus) {
6578     // Forget about the nulled arguments since typo correction
6579     // do not handle them well.
6580     TheCall->shrinkNumArgs(Args.size());
6581     // C cannot always handle TypoExpr nodes in builtin calls and direct
6582     // function calls as their argument checking don't necessarily handle
6583     // dependent types properly, so make sure any TypoExprs have been
6584     // dealt with.
6585     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6586     if (!Result.isUsable()) return ExprError();
6587     CallExpr *TheOldCall = TheCall;
6588     TheCall = dyn_cast<CallExpr>(Result.get());
6589     bool CorrectedTypos = TheCall != TheOldCall;
6590     if (!TheCall) return Result;
6591     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6592 
6593     // A new call expression node was created if some typos were corrected.
6594     // However it may not have been constructed with enough storage. In this
6595     // case, rebuild the node with enough storage. The waste of space is
6596     // immaterial since this only happens when some typos were corrected.
6597     if (CorrectedTypos && Args.size() < NumParams) {
6598       if (Config)
6599         TheCall = CUDAKernelCallExpr::Create(
6600             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6601             RParenLoc, CurFPFeatureOverrides(), NumParams);
6602       else
6603         TheCall =
6604             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6605                              CurFPFeatureOverrides(), NumParams, UsesADL);
6606     }
6607     // We can now handle the nulled arguments for the default arguments.
6608     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6609   }
6610 
6611   // Bail out early if calling a builtin with custom type checking.
6612   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6613     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6614 
6615   if (getLangOpts().CUDA) {
6616     if (Config) {
6617       // CUDA: Kernel calls must be to global functions
6618       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6619         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6620             << FDecl << Fn->getSourceRange());
6621 
6622       // CUDA: Kernel function must have 'void' return type
6623       if (!FuncT->getReturnType()->isVoidType() &&
6624           !FuncT->getReturnType()->getAs<AutoType>() &&
6625           !FuncT->getReturnType()->isInstantiationDependentType())
6626         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6627             << Fn->getType() << Fn->getSourceRange());
6628     } else {
6629       // CUDA: Calls to global functions must be configured
6630       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6631         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6632             << FDecl << Fn->getSourceRange());
6633     }
6634   }
6635 
6636   // Check for a valid return type
6637   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6638                           FDecl))
6639     return ExprError();
6640 
6641   // We know the result type of the call, set it.
6642   TheCall->setType(FuncT->getCallResultType(Context));
6643   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6644 
6645   if (Proto) {
6646     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6647                                 IsExecConfig))
6648       return ExprError();
6649   } else {
6650     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6651 
6652     if (FDecl) {
6653       // Check if we have too few/too many template arguments, based
6654       // on our knowledge of the function definition.
6655       const FunctionDecl *Def = nullptr;
6656       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6657         Proto = Def->getType()->getAs<FunctionProtoType>();
6658        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6659           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6660           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6661       }
6662 
6663       // If the function we're calling isn't a function prototype, but we have
6664       // a function prototype from a prior declaratiom, use that prototype.
6665       if (!FDecl->hasPrototype())
6666         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6667     }
6668 
6669     // Promote the arguments (C99 6.5.2.2p6).
6670     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6671       Expr *Arg = Args[i];
6672 
6673       if (Proto && i < Proto->getNumParams()) {
6674         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6675             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6676         ExprResult ArgE =
6677             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6678         if (ArgE.isInvalid())
6679           return true;
6680 
6681         Arg = ArgE.getAs<Expr>();
6682 
6683       } else {
6684         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6685 
6686         if (ArgE.isInvalid())
6687           return true;
6688 
6689         Arg = ArgE.getAs<Expr>();
6690       }
6691 
6692       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6693                               diag::err_call_incomplete_argument, Arg))
6694         return ExprError();
6695 
6696       TheCall->setArg(i, Arg);
6697     }
6698   }
6699 
6700   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6701     if (!Method->isStatic())
6702       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6703         << Fn->getSourceRange());
6704 
6705   // Check for sentinels
6706   if (NDecl)
6707     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6708 
6709   // Warn for unions passing across security boundary (CMSE).
6710   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6711     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6712       if (const auto *RT =
6713               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6714         if (RT->getDecl()->isOrContainsUnion())
6715           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6716               << 0 << i;
6717       }
6718     }
6719   }
6720 
6721   // Do special checking on direct calls to functions.
6722   if (FDecl) {
6723     if (CheckFunctionCall(FDecl, TheCall, Proto))
6724       return ExprError();
6725 
6726     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6727 
6728     if (BuiltinID)
6729       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6730   } else if (NDecl) {
6731     if (CheckPointerCall(NDecl, TheCall, Proto))
6732       return ExprError();
6733   } else {
6734     if (CheckOtherCall(TheCall, Proto))
6735       return ExprError();
6736   }
6737 
6738   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6739 }
6740 
6741 ExprResult
6742 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6743                            SourceLocation RParenLoc, Expr *InitExpr) {
6744   assert(Ty && "ActOnCompoundLiteral(): missing type");
6745   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6746 
6747   TypeSourceInfo *TInfo;
6748   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6749   if (!TInfo)
6750     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6751 
6752   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6753 }
6754 
6755 ExprResult
6756 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6757                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6758   QualType literalType = TInfo->getType();
6759 
6760   if (literalType->isArrayType()) {
6761     if (RequireCompleteSizedType(
6762             LParenLoc, Context.getBaseElementType(literalType),
6763             diag::err_array_incomplete_or_sizeless_type,
6764             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6765       return ExprError();
6766     if (literalType->isVariableArrayType())
6767       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6768         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6769   } else if (!literalType->isDependentType() &&
6770              RequireCompleteType(LParenLoc, literalType,
6771                diag::err_typecheck_decl_incomplete_type,
6772                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6773     return ExprError();
6774 
6775   InitializedEntity Entity
6776     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6777   InitializationKind Kind
6778     = InitializationKind::CreateCStyleCast(LParenLoc,
6779                                            SourceRange(LParenLoc, RParenLoc),
6780                                            /*InitList=*/true);
6781   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6782   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6783                                       &literalType);
6784   if (Result.isInvalid())
6785     return ExprError();
6786   LiteralExpr = Result.get();
6787 
6788   bool isFileScope = !CurContext->isFunctionOrMethod();
6789 
6790   // In C, compound literals are l-values for some reason.
6791   // For GCC compatibility, in C++, file-scope array compound literals with
6792   // constant initializers are also l-values, and compound literals are
6793   // otherwise prvalues.
6794   //
6795   // (GCC also treats C++ list-initialized file-scope array prvalues with
6796   // constant initializers as l-values, but that's non-conforming, so we don't
6797   // follow it there.)
6798   //
6799   // FIXME: It would be better to handle the lvalue cases as materializing and
6800   // lifetime-extending a temporary object, but our materialized temporaries
6801   // representation only supports lifetime extension from a variable, not "out
6802   // of thin air".
6803   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6804   // is bound to the result of applying array-to-pointer decay to the compound
6805   // literal.
6806   // FIXME: GCC supports compound literals of reference type, which should
6807   // obviously have a value kind derived from the kind of reference involved.
6808   ExprValueKind VK =
6809       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6810           ? VK_RValue
6811           : VK_LValue;
6812 
6813   if (isFileScope)
6814     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6815       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6816         Expr *Init = ILE->getInit(i);
6817         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6818       }
6819 
6820   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6821                                               VK, LiteralExpr, isFileScope);
6822   if (isFileScope) {
6823     if (!LiteralExpr->isTypeDependent() &&
6824         !LiteralExpr->isValueDependent() &&
6825         !literalType->isDependentType()) // C99 6.5.2.5p3
6826       if (CheckForConstantInitializer(LiteralExpr, literalType))
6827         return ExprError();
6828   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6829              literalType.getAddressSpace() != LangAS::Default) {
6830     // Embedded-C extensions to C99 6.5.2.5:
6831     //   "If the compound literal occurs inside the body of a function, the
6832     //   type name shall not be qualified by an address-space qualifier."
6833     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6834       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6835     return ExprError();
6836   }
6837 
6838   if (!isFileScope && !getLangOpts().CPlusPlus) {
6839     // Compound literals that have automatic storage duration are destroyed at
6840     // the end of the scope in C; in C++, they're just temporaries.
6841 
6842     // Emit diagnostics if it is or contains a C union type that is non-trivial
6843     // to destruct.
6844     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6845       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6846                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6847 
6848     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6849     if (literalType.isDestructedType()) {
6850       Cleanup.setExprNeedsCleanups(true);
6851       ExprCleanupObjects.push_back(E);
6852       getCurFunction()->setHasBranchProtectedScope();
6853     }
6854   }
6855 
6856   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6857       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6858     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6859                                        E->getInitializer()->getExprLoc());
6860 
6861   return MaybeBindToTemporary(E);
6862 }
6863 
6864 ExprResult
6865 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6866                     SourceLocation RBraceLoc) {
6867   // Only produce each kind of designated initialization diagnostic once.
6868   SourceLocation FirstDesignator;
6869   bool DiagnosedArrayDesignator = false;
6870   bool DiagnosedNestedDesignator = false;
6871   bool DiagnosedMixedDesignator = false;
6872 
6873   // Check that any designated initializers are syntactically valid in the
6874   // current language mode.
6875   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6876     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6877       if (FirstDesignator.isInvalid())
6878         FirstDesignator = DIE->getBeginLoc();
6879 
6880       if (!getLangOpts().CPlusPlus)
6881         break;
6882 
6883       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6884         DiagnosedNestedDesignator = true;
6885         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6886           << DIE->getDesignatorsSourceRange();
6887       }
6888 
6889       for (auto &Desig : DIE->designators()) {
6890         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6891           DiagnosedArrayDesignator = true;
6892           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6893             << Desig.getSourceRange();
6894         }
6895       }
6896 
6897       if (!DiagnosedMixedDesignator &&
6898           !isa<DesignatedInitExpr>(InitArgList[0])) {
6899         DiagnosedMixedDesignator = true;
6900         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6901           << DIE->getSourceRange();
6902         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6903           << InitArgList[0]->getSourceRange();
6904       }
6905     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6906                isa<DesignatedInitExpr>(InitArgList[0])) {
6907       DiagnosedMixedDesignator = true;
6908       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6909       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6910         << DIE->getSourceRange();
6911       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6912         << InitArgList[I]->getSourceRange();
6913     }
6914   }
6915 
6916   if (FirstDesignator.isValid()) {
6917     // Only diagnose designated initiaization as a C++20 extension if we didn't
6918     // already diagnose use of (non-C++20) C99 designator syntax.
6919     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6920         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6921       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6922                                 ? diag::warn_cxx17_compat_designated_init
6923                                 : diag::ext_cxx_designated_init);
6924     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6925       Diag(FirstDesignator, diag::ext_designated_init);
6926     }
6927   }
6928 
6929   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6930 }
6931 
6932 ExprResult
6933 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6934                     SourceLocation RBraceLoc) {
6935   // Semantic analysis for initializers is done by ActOnDeclarator() and
6936   // CheckInitializer() - it requires knowledge of the object being initialized.
6937 
6938   // Immediately handle non-overload placeholders.  Overloads can be
6939   // resolved contextually, but everything else here can't.
6940   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6941     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6942       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6943 
6944       // Ignore failures; dropping the entire initializer list because
6945       // of one failure would be terrible for indexing/etc.
6946       if (result.isInvalid()) continue;
6947 
6948       InitArgList[I] = result.get();
6949     }
6950   }
6951 
6952   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6953                                                RBraceLoc);
6954   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6955   return E;
6956 }
6957 
6958 /// Do an explicit extend of the given block pointer if we're in ARC.
6959 void Sema::maybeExtendBlockObject(ExprResult &E) {
6960   assert(E.get()->getType()->isBlockPointerType());
6961   assert(E.get()->isRValue());
6962 
6963   // Only do this in an r-value context.
6964   if (!getLangOpts().ObjCAutoRefCount) return;
6965 
6966   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6967                                CK_ARCExtendBlockObject, E.get(),
6968                                /*base path*/ nullptr, VK_RValue);
6969   Cleanup.setExprNeedsCleanups(true);
6970 }
6971 
6972 /// Prepare a conversion of the given expression to an ObjC object
6973 /// pointer type.
6974 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6975   QualType type = E.get()->getType();
6976   if (type->isObjCObjectPointerType()) {
6977     return CK_BitCast;
6978   } else if (type->isBlockPointerType()) {
6979     maybeExtendBlockObject(E);
6980     return CK_BlockPointerToObjCPointerCast;
6981   } else {
6982     assert(type->isPointerType());
6983     return CK_CPointerToObjCPointerCast;
6984   }
6985 }
6986 
6987 /// Prepares for a scalar cast, performing all the necessary stages
6988 /// except the final cast and returning the kind required.
6989 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6990   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6991   // Also, callers should have filtered out the invalid cases with
6992   // pointers.  Everything else should be possible.
6993 
6994   QualType SrcTy = Src.get()->getType();
6995   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6996     return CK_NoOp;
6997 
6998   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6999   case Type::STK_MemberPointer:
7000     llvm_unreachable("member pointer type in C");
7001 
7002   case Type::STK_CPointer:
7003   case Type::STK_BlockPointer:
7004   case Type::STK_ObjCObjectPointer:
7005     switch (DestTy->getScalarTypeKind()) {
7006     case Type::STK_CPointer: {
7007       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7008       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7009       if (SrcAS != DestAS)
7010         return CK_AddressSpaceConversion;
7011       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7012         return CK_NoOp;
7013       return CK_BitCast;
7014     }
7015     case Type::STK_BlockPointer:
7016       return (SrcKind == Type::STK_BlockPointer
7017                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7018     case Type::STK_ObjCObjectPointer:
7019       if (SrcKind == Type::STK_ObjCObjectPointer)
7020         return CK_BitCast;
7021       if (SrcKind == Type::STK_CPointer)
7022         return CK_CPointerToObjCPointerCast;
7023       maybeExtendBlockObject(Src);
7024       return CK_BlockPointerToObjCPointerCast;
7025     case Type::STK_Bool:
7026       return CK_PointerToBoolean;
7027     case Type::STK_Integral:
7028       return CK_PointerToIntegral;
7029     case Type::STK_Floating:
7030     case Type::STK_FloatingComplex:
7031     case Type::STK_IntegralComplex:
7032     case Type::STK_MemberPointer:
7033     case Type::STK_FixedPoint:
7034       llvm_unreachable("illegal cast from pointer");
7035     }
7036     llvm_unreachable("Should have returned before this");
7037 
7038   case Type::STK_FixedPoint:
7039     switch (DestTy->getScalarTypeKind()) {
7040     case Type::STK_FixedPoint:
7041       return CK_FixedPointCast;
7042     case Type::STK_Bool:
7043       return CK_FixedPointToBoolean;
7044     case Type::STK_Integral:
7045       return CK_FixedPointToIntegral;
7046     case Type::STK_Floating:
7047     case Type::STK_IntegralComplex:
7048     case Type::STK_FloatingComplex:
7049       Diag(Src.get()->getExprLoc(),
7050            diag::err_unimplemented_conversion_with_fixed_point_type)
7051           << DestTy;
7052       return CK_IntegralCast;
7053     case Type::STK_CPointer:
7054     case Type::STK_ObjCObjectPointer:
7055     case Type::STK_BlockPointer:
7056     case Type::STK_MemberPointer:
7057       llvm_unreachable("illegal cast to pointer type");
7058     }
7059     llvm_unreachable("Should have returned before this");
7060 
7061   case Type::STK_Bool: // casting from bool is like casting from an integer
7062   case Type::STK_Integral:
7063     switch (DestTy->getScalarTypeKind()) {
7064     case Type::STK_CPointer:
7065     case Type::STK_ObjCObjectPointer:
7066     case Type::STK_BlockPointer:
7067       if (Src.get()->isNullPointerConstant(Context,
7068                                            Expr::NPC_ValueDependentIsNull))
7069         return CK_NullToPointer;
7070       return CK_IntegralToPointer;
7071     case Type::STK_Bool:
7072       return CK_IntegralToBoolean;
7073     case Type::STK_Integral:
7074       return CK_IntegralCast;
7075     case Type::STK_Floating:
7076       return CK_IntegralToFloating;
7077     case Type::STK_IntegralComplex:
7078       Src = ImpCastExprToType(Src.get(),
7079                       DestTy->castAs<ComplexType>()->getElementType(),
7080                       CK_IntegralCast);
7081       return CK_IntegralRealToComplex;
7082     case Type::STK_FloatingComplex:
7083       Src = ImpCastExprToType(Src.get(),
7084                       DestTy->castAs<ComplexType>()->getElementType(),
7085                       CK_IntegralToFloating);
7086       return CK_FloatingRealToComplex;
7087     case Type::STK_MemberPointer:
7088       llvm_unreachable("member pointer type in C");
7089     case Type::STK_FixedPoint:
7090       return CK_IntegralToFixedPoint;
7091     }
7092     llvm_unreachable("Should have returned before this");
7093 
7094   case Type::STK_Floating:
7095     switch (DestTy->getScalarTypeKind()) {
7096     case Type::STK_Floating:
7097       return CK_FloatingCast;
7098     case Type::STK_Bool:
7099       return CK_FloatingToBoolean;
7100     case Type::STK_Integral:
7101       return CK_FloatingToIntegral;
7102     case Type::STK_FloatingComplex:
7103       Src = ImpCastExprToType(Src.get(),
7104                               DestTy->castAs<ComplexType>()->getElementType(),
7105                               CK_FloatingCast);
7106       return CK_FloatingRealToComplex;
7107     case Type::STK_IntegralComplex:
7108       Src = ImpCastExprToType(Src.get(),
7109                               DestTy->castAs<ComplexType>()->getElementType(),
7110                               CK_FloatingToIntegral);
7111       return CK_IntegralRealToComplex;
7112     case Type::STK_CPointer:
7113     case Type::STK_ObjCObjectPointer:
7114     case Type::STK_BlockPointer:
7115       llvm_unreachable("valid float->pointer cast?");
7116     case Type::STK_MemberPointer:
7117       llvm_unreachable("member pointer type in C");
7118     case Type::STK_FixedPoint:
7119       Diag(Src.get()->getExprLoc(),
7120            diag::err_unimplemented_conversion_with_fixed_point_type)
7121           << SrcTy;
7122       return CK_IntegralCast;
7123     }
7124     llvm_unreachable("Should have returned before this");
7125 
7126   case Type::STK_FloatingComplex:
7127     switch (DestTy->getScalarTypeKind()) {
7128     case Type::STK_FloatingComplex:
7129       return CK_FloatingComplexCast;
7130     case Type::STK_IntegralComplex:
7131       return CK_FloatingComplexToIntegralComplex;
7132     case Type::STK_Floating: {
7133       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7134       if (Context.hasSameType(ET, DestTy))
7135         return CK_FloatingComplexToReal;
7136       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7137       return CK_FloatingCast;
7138     }
7139     case Type::STK_Bool:
7140       return CK_FloatingComplexToBoolean;
7141     case Type::STK_Integral:
7142       Src = ImpCastExprToType(Src.get(),
7143                               SrcTy->castAs<ComplexType>()->getElementType(),
7144                               CK_FloatingComplexToReal);
7145       return CK_FloatingToIntegral;
7146     case Type::STK_CPointer:
7147     case Type::STK_ObjCObjectPointer:
7148     case Type::STK_BlockPointer:
7149       llvm_unreachable("valid complex float->pointer cast?");
7150     case Type::STK_MemberPointer:
7151       llvm_unreachable("member pointer type in C");
7152     case Type::STK_FixedPoint:
7153       Diag(Src.get()->getExprLoc(),
7154            diag::err_unimplemented_conversion_with_fixed_point_type)
7155           << SrcTy;
7156       return CK_IntegralCast;
7157     }
7158     llvm_unreachable("Should have returned before this");
7159 
7160   case Type::STK_IntegralComplex:
7161     switch (DestTy->getScalarTypeKind()) {
7162     case Type::STK_FloatingComplex:
7163       return CK_IntegralComplexToFloatingComplex;
7164     case Type::STK_IntegralComplex:
7165       return CK_IntegralComplexCast;
7166     case Type::STK_Integral: {
7167       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7168       if (Context.hasSameType(ET, DestTy))
7169         return CK_IntegralComplexToReal;
7170       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7171       return CK_IntegralCast;
7172     }
7173     case Type::STK_Bool:
7174       return CK_IntegralComplexToBoolean;
7175     case Type::STK_Floating:
7176       Src = ImpCastExprToType(Src.get(),
7177                               SrcTy->castAs<ComplexType>()->getElementType(),
7178                               CK_IntegralComplexToReal);
7179       return CK_IntegralToFloating;
7180     case Type::STK_CPointer:
7181     case Type::STK_ObjCObjectPointer:
7182     case Type::STK_BlockPointer:
7183       llvm_unreachable("valid complex int->pointer cast?");
7184     case Type::STK_MemberPointer:
7185       llvm_unreachable("member pointer type in C");
7186     case Type::STK_FixedPoint:
7187       Diag(Src.get()->getExprLoc(),
7188            diag::err_unimplemented_conversion_with_fixed_point_type)
7189           << SrcTy;
7190       return CK_IntegralCast;
7191     }
7192     llvm_unreachable("Should have returned before this");
7193   }
7194 
7195   llvm_unreachable("Unhandled scalar cast");
7196 }
7197 
7198 static bool breakDownVectorType(QualType type, uint64_t &len,
7199                                 QualType &eltType) {
7200   // Vectors are simple.
7201   if (const VectorType *vecType = type->getAs<VectorType>()) {
7202     len = vecType->getNumElements();
7203     eltType = vecType->getElementType();
7204     assert(eltType->isScalarType());
7205     return true;
7206   }
7207 
7208   // We allow lax conversion to and from non-vector types, but only if
7209   // they're real types (i.e. non-complex, non-pointer scalar types).
7210   if (!type->isRealType()) return false;
7211 
7212   len = 1;
7213   eltType = type;
7214   return true;
7215 }
7216 
7217 /// Are the two types lax-compatible vector types?  That is, given
7218 /// that one of them is a vector, do they have equal storage sizes,
7219 /// where the storage size is the number of elements times the element
7220 /// size?
7221 ///
7222 /// This will also return false if either of the types is neither a
7223 /// vector nor a real type.
7224 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7225   assert(destTy->isVectorType() || srcTy->isVectorType());
7226 
7227   // Disallow lax conversions between scalars and ExtVectors (these
7228   // conversions are allowed for other vector types because common headers
7229   // depend on them).  Most scalar OP ExtVector cases are handled by the
7230   // splat path anyway, which does what we want (convert, not bitcast).
7231   // What this rules out for ExtVectors is crazy things like char4*float.
7232   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7233   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7234 
7235   uint64_t srcLen, destLen;
7236   QualType srcEltTy, destEltTy;
7237   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7238   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7239 
7240   // ASTContext::getTypeSize will return the size rounded up to a
7241   // power of 2, so instead of using that, we need to use the raw
7242   // element size multiplied by the element count.
7243   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7244   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7245 
7246   return (srcLen * srcEltSize == destLen * destEltSize);
7247 }
7248 
7249 /// Is this a legal conversion between two types, one of which is
7250 /// known to be a vector type?
7251 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7252   assert(destTy->isVectorType() || srcTy->isVectorType());
7253 
7254   switch (Context.getLangOpts().getLaxVectorConversions()) {
7255   case LangOptions::LaxVectorConversionKind::None:
7256     return false;
7257 
7258   case LangOptions::LaxVectorConversionKind::Integer:
7259     if (!srcTy->isIntegralOrEnumerationType()) {
7260       auto *Vec = srcTy->getAs<VectorType>();
7261       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7262         return false;
7263     }
7264     if (!destTy->isIntegralOrEnumerationType()) {
7265       auto *Vec = destTy->getAs<VectorType>();
7266       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7267         return false;
7268     }
7269     // OK, integer (vector) -> integer (vector) bitcast.
7270     break;
7271 
7272     case LangOptions::LaxVectorConversionKind::All:
7273     break;
7274   }
7275 
7276   return areLaxCompatibleVectorTypes(srcTy, destTy);
7277 }
7278 
7279 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7280                            CastKind &Kind) {
7281   assert(VectorTy->isVectorType() && "Not a vector type!");
7282 
7283   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7284     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7285       return Diag(R.getBegin(),
7286                   Ty->isVectorType() ?
7287                   diag::err_invalid_conversion_between_vectors :
7288                   diag::err_invalid_conversion_between_vector_and_integer)
7289         << VectorTy << Ty << R;
7290   } else
7291     return Diag(R.getBegin(),
7292                 diag::err_invalid_conversion_between_vector_and_scalar)
7293       << VectorTy << Ty << R;
7294 
7295   Kind = CK_BitCast;
7296   return false;
7297 }
7298 
7299 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7300   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7301 
7302   if (DestElemTy == SplattedExpr->getType())
7303     return SplattedExpr;
7304 
7305   assert(DestElemTy->isFloatingType() ||
7306          DestElemTy->isIntegralOrEnumerationType());
7307 
7308   CastKind CK;
7309   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7310     // OpenCL requires that we convert `true` boolean expressions to -1, but
7311     // only when splatting vectors.
7312     if (DestElemTy->isFloatingType()) {
7313       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7314       // in two steps: boolean to signed integral, then to floating.
7315       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7316                                                  CK_BooleanToSignedIntegral);
7317       SplattedExpr = CastExprRes.get();
7318       CK = CK_IntegralToFloating;
7319     } else {
7320       CK = CK_BooleanToSignedIntegral;
7321     }
7322   } else {
7323     ExprResult CastExprRes = SplattedExpr;
7324     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7325     if (CastExprRes.isInvalid())
7326       return ExprError();
7327     SplattedExpr = CastExprRes.get();
7328   }
7329   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7330 }
7331 
7332 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7333                                     Expr *CastExpr, CastKind &Kind) {
7334   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7335 
7336   QualType SrcTy = CastExpr->getType();
7337 
7338   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7339   // an ExtVectorType.
7340   // In OpenCL, casts between vectors of different types are not allowed.
7341   // (See OpenCL 6.2).
7342   if (SrcTy->isVectorType()) {
7343     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7344         (getLangOpts().OpenCL &&
7345          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7346       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7347         << DestTy << SrcTy << R;
7348       return ExprError();
7349     }
7350     Kind = CK_BitCast;
7351     return CastExpr;
7352   }
7353 
7354   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7355   // conversion will take place first from scalar to elt type, and then
7356   // splat from elt type to vector.
7357   if (SrcTy->isPointerType())
7358     return Diag(R.getBegin(),
7359                 diag::err_invalid_conversion_between_vector_and_scalar)
7360       << DestTy << SrcTy << R;
7361 
7362   Kind = CK_VectorSplat;
7363   return prepareVectorSplat(DestTy, CastExpr);
7364 }
7365 
7366 ExprResult
7367 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7368                     Declarator &D, ParsedType &Ty,
7369                     SourceLocation RParenLoc, Expr *CastExpr) {
7370   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7371          "ActOnCastExpr(): missing type or expr");
7372 
7373   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7374   if (D.isInvalidType())
7375     return ExprError();
7376 
7377   if (getLangOpts().CPlusPlus) {
7378     // Check that there are no default arguments (C++ only).
7379     CheckExtraCXXDefaultArguments(D);
7380   } else {
7381     // Make sure any TypoExprs have been dealt with.
7382     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7383     if (!Res.isUsable())
7384       return ExprError();
7385     CastExpr = Res.get();
7386   }
7387 
7388   checkUnusedDeclAttributes(D);
7389 
7390   QualType castType = castTInfo->getType();
7391   Ty = CreateParsedType(castType, castTInfo);
7392 
7393   bool isVectorLiteral = false;
7394 
7395   // Check for an altivec or OpenCL literal,
7396   // i.e. all the elements are integer constants.
7397   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7398   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7399   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7400        && castType->isVectorType() && (PE || PLE)) {
7401     if (PLE && PLE->getNumExprs() == 0) {
7402       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7403       return ExprError();
7404     }
7405     if (PE || PLE->getNumExprs() == 1) {
7406       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7407       if (!E->getType()->isVectorType())
7408         isVectorLiteral = true;
7409     }
7410     else
7411       isVectorLiteral = true;
7412   }
7413 
7414   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7415   // then handle it as such.
7416   if (isVectorLiteral)
7417     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7418 
7419   // If the Expr being casted is a ParenListExpr, handle it specially.
7420   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7421   // sequence of BinOp comma operators.
7422   if (isa<ParenListExpr>(CastExpr)) {
7423     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7424     if (Result.isInvalid()) return ExprError();
7425     CastExpr = Result.get();
7426   }
7427 
7428   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7429       !getSourceManager().isInSystemMacro(LParenLoc))
7430     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7431 
7432   CheckTollFreeBridgeCast(castType, CastExpr);
7433 
7434   CheckObjCBridgeRelatedCast(castType, CastExpr);
7435 
7436   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7437 
7438   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7439 }
7440 
7441 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7442                                     SourceLocation RParenLoc, Expr *E,
7443                                     TypeSourceInfo *TInfo) {
7444   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7445          "Expected paren or paren list expression");
7446 
7447   Expr **exprs;
7448   unsigned numExprs;
7449   Expr *subExpr;
7450   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7451   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7452     LiteralLParenLoc = PE->getLParenLoc();
7453     LiteralRParenLoc = PE->getRParenLoc();
7454     exprs = PE->getExprs();
7455     numExprs = PE->getNumExprs();
7456   } else { // isa<ParenExpr> by assertion at function entrance
7457     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7458     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7459     subExpr = cast<ParenExpr>(E)->getSubExpr();
7460     exprs = &subExpr;
7461     numExprs = 1;
7462   }
7463 
7464   QualType Ty = TInfo->getType();
7465   assert(Ty->isVectorType() && "Expected vector type");
7466 
7467   SmallVector<Expr *, 8> initExprs;
7468   const VectorType *VTy = Ty->castAs<VectorType>();
7469   unsigned numElems = VTy->getNumElements();
7470 
7471   // '(...)' form of vector initialization in AltiVec: the number of
7472   // initializers must be one or must match the size of the vector.
7473   // If a single value is specified in the initializer then it will be
7474   // replicated to all the components of the vector
7475   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7476     // The number of initializers must be one or must match the size of the
7477     // vector. If a single value is specified in the initializer then it will
7478     // be replicated to all the components of the vector
7479     if (numExprs == 1) {
7480       QualType ElemTy = VTy->getElementType();
7481       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7482       if (Literal.isInvalid())
7483         return ExprError();
7484       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7485                                   PrepareScalarCast(Literal, ElemTy));
7486       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7487     }
7488     else if (numExprs < numElems) {
7489       Diag(E->getExprLoc(),
7490            diag::err_incorrect_number_of_vector_initializers);
7491       return ExprError();
7492     }
7493     else
7494       initExprs.append(exprs, exprs + numExprs);
7495   }
7496   else {
7497     // For OpenCL, when the number of initializers is a single value,
7498     // it will be replicated to all components of the vector.
7499     if (getLangOpts().OpenCL &&
7500         VTy->getVectorKind() == VectorType::GenericVector &&
7501         numExprs == 1) {
7502         QualType ElemTy = VTy->getElementType();
7503         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7504         if (Literal.isInvalid())
7505           return ExprError();
7506         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7507                                     PrepareScalarCast(Literal, ElemTy));
7508         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7509     }
7510 
7511     initExprs.append(exprs, exprs + numExprs);
7512   }
7513   // FIXME: This means that pretty-printing the final AST will produce curly
7514   // braces instead of the original commas.
7515   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7516                                                    initExprs, LiteralRParenLoc);
7517   initE->setType(Ty);
7518   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7519 }
7520 
7521 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7522 /// the ParenListExpr into a sequence of comma binary operators.
7523 ExprResult
7524 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7525   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7526   if (!E)
7527     return OrigExpr;
7528 
7529   ExprResult Result(E->getExpr(0));
7530 
7531   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7532     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7533                         E->getExpr(i));
7534 
7535   if (Result.isInvalid()) return ExprError();
7536 
7537   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7538 }
7539 
7540 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7541                                     SourceLocation R,
7542                                     MultiExprArg Val) {
7543   return ParenListExpr::Create(Context, L, Val, R);
7544 }
7545 
7546 /// Emit a specialized diagnostic when one expression is a null pointer
7547 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7548 /// emitted.
7549 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7550                                       SourceLocation QuestionLoc) {
7551   Expr *NullExpr = LHSExpr;
7552   Expr *NonPointerExpr = RHSExpr;
7553   Expr::NullPointerConstantKind NullKind =
7554       NullExpr->isNullPointerConstant(Context,
7555                                       Expr::NPC_ValueDependentIsNotNull);
7556 
7557   if (NullKind == Expr::NPCK_NotNull) {
7558     NullExpr = RHSExpr;
7559     NonPointerExpr = LHSExpr;
7560     NullKind =
7561         NullExpr->isNullPointerConstant(Context,
7562                                         Expr::NPC_ValueDependentIsNotNull);
7563   }
7564 
7565   if (NullKind == Expr::NPCK_NotNull)
7566     return false;
7567 
7568   if (NullKind == Expr::NPCK_ZeroExpression)
7569     return false;
7570 
7571   if (NullKind == Expr::NPCK_ZeroLiteral) {
7572     // In this case, check to make sure that we got here from a "NULL"
7573     // string in the source code.
7574     NullExpr = NullExpr->IgnoreParenImpCasts();
7575     SourceLocation loc = NullExpr->getExprLoc();
7576     if (!findMacroSpelling(loc, "NULL"))
7577       return false;
7578   }
7579 
7580   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7581   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7582       << NonPointerExpr->getType() << DiagType
7583       << NonPointerExpr->getSourceRange();
7584   return true;
7585 }
7586 
7587 /// Return false if the condition expression is valid, true otherwise.
7588 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7589   QualType CondTy = Cond->getType();
7590 
7591   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7592   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7593     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7594       << CondTy << Cond->getSourceRange();
7595     return true;
7596   }
7597 
7598   // C99 6.5.15p2
7599   if (CondTy->isScalarType()) return false;
7600 
7601   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7602     << CondTy << Cond->getSourceRange();
7603   return true;
7604 }
7605 
7606 /// Handle when one or both operands are void type.
7607 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7608                                          ExprResult &RHS) {
7609     Expr *LHSExpr = LHS.get();
7610     Expr *RHSExpr = RHS.get();
7611 
7612     if (!LHSExpr->getType()->isVoidType())
7613       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7614           << RHSExpr->getSourceRange();
7615     if (!RHSExpr->getType()->isVoidType())
7616       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7617           << LHSExpr->getSourceRange();
7618     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7619     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7620     return S.Context.VoidTy;
7621 }
7622 
7623 /// Return false if the NullExpr can be promoted to PointerTy,
7624 /// true otherwise.
7625 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7626                                         QualType PointerTy) {
7627   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7628       !NullExpr.get()->isNullPointerConstant(S.Context,
7629                                             Expr::NPC_ValueDependentIsNull))
7630     return true;
7631 
7632   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7633   return false;
7634 }
7635 
7636 /// Checks compatibility between two pointers and return the resulting
7637 /// type.
7638 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7639                                                      ExprResult &RHS,
7640                                                      SourceLocation Loc) {
7641   QualType LHSTy = LHS.get()->getType();
7642   QualType RHSTy = RHS.get()->getType();
7643 
7644   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7645     // Two identical pointers types are always compatible.
7646     return LHSTy;
7647   }
7648 
7649   QualType lhptee, rhptee;
7650 
7651   // Get the pointee types.
7652   bool IsBlockPointer = false;
7653   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7654     lhptee = LHSBTy->getPointeeType();
7655     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7656     IsBlockPointer = true;
7657   } else {
7658     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7659     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7660   }
7661 
7662   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7663   // differently qualified versions of compatible types, the result type is
7664   // a pointer to an appropriately qualified version of the composite
7665   // type.
7666 
7667   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7668   // clause doesn't make sense for our extensions. E.g. address space 2 should
7669   // be incompatible with address space 3: they may live on different devices or
7670   // anything.
7671   Qualifiers lhQual = lhptee.getQualifiers();
7672   Qualifiers rhQual = rhptee.getQualifiers();
7673 
7674   LangAS ResultAddrSpace = LangAS::Default;
7675   LangAS LAddrSpace = lhQual.getAddressSpace();
7676   LangAS RAddrSpace = rhQual.getAddressSpace();
7677 
7678   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7679   // spaces is disallowed.
7680   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7681     ResultAddrSpace = LAddrSpace;
7682   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7683     ResultAddrSpace = RAddrSpace;
7684   else {
7685     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7686         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7687         << RHS.get()->getSourceRange();
7688     return QualType();
7689   }
7690 
7691   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7692   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7693   lhQual.removeCVRQualifiers();
7694   rhQual.removeCVRQualifiers();
7695 
7696   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7697   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7698   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7699   // qual types are compatible iff
7700   //  * corresponded types are compatible
7701   //  * CVR qualifiers are equal
7702   //  * address spaces are equal
7703   // Thus for conditional operator we merge CVR and address space unqualified
7704   // pointees and if there is a composite type we return a pointer to it with
7705   // merged qualifiers.
7706   LHSCastKind =
7707       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7708   RHSCastKind =
7709       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7710   lhQual.removeAddressSpace();
7711   rhQual.removeAddressSpace();
7712 
7713   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7714   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7715 
7716   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7717 
7718   if (CompositeTy.isNull()) {
7719     // In this situation, we assume void* type. No especially good
7720     // reason, but this is what gcc does, and we do have to pick
7721     // to get a consistent AST.
7722     QualType incompatTy;
7723     incompatTy = S.Context.getPointerType(
7724         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7725     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7726     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7727 
7728     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7729     // for casts between types with incompatible address space qualifiers.
7730     // For the following code the compiler produces casts between global and
7731     // local address spaces of the corresponded innermost pointees:
7732     // local int *global *a;
7733     // global int *global *b;
7734     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7735     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7736         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7737         << RHS.get()->getSourceRange();
7738 
7739     return incompatTy;
7740   }
7741 
7742   // The pointer types are compatible.
7743   // In case of OpenCL ResultTy should have the address space qualifier
7744   // which is a superset of address spaces of both the 2nd and the 3rd
7745   // operands of the conditional operator.
7746   QualType ResultTy = [&, ResultAddrSpace]() {
7747     if (S.getLangOpts().OpenCL) {
7748       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7749       CompositeQuals.setAddressSpace(ResultAddrSpace);
7750       return S.Context
7751           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7752           .withCVRQualifiers(MergedCVRQual);
7753     }
7754     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7755   }();
7756   if (IsBlockPointer)
7757     ResultTy = S.Context.getBlockPointerType(ResultTy);
7758   else
7759     ResultTy = S.Context.getPointerType(ResultTy);
7760 
7761   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7762   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7763   return ResultTy;
7764 }
7765 
7766 /// Return the resulting type when the operands are both block pointers.
7767 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7768                                                           ExprResult &LHS,
7769                                                           ExprResult &RHS,
7770                                                           SourceLocation Loc) {
7771   QualType LHSTy = LHS.get()->getType();
7772   QualType RHSTy = RHS.get()->getType();
7773 
7774   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7775     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7776       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7777       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7778       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7779       return destType;
7780     }
7781     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7782       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7783       << RHS.get()->getSourceRange();
7784     return QualType();
7785   }
7786 
7787   // We have 2 block pointer types.
7788   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7789 }
7790 
7791 /// Return the resulting type when the operands are both pointers.
7792 static QualType
7793 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7794                                             ExprResult &RHS,
7795                                             SourceLocation Loc) {
7796   // get the pointer types
7797   QualType LHSTy = LHS.get()->getType();
7798   QualType RHSTy = RHS.get()->getType();
7799 
7800   // get the "pointed to" types
7801   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7802   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7803 
7804   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7805   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7806     // Figure out necessary qualifiers (C99 6.5.15p6)
7807     QualType destPointee
7808       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7809     QualType destType = S.Context.getPointerType(destPointee);
7810     // Add qualifiers if necessary.
7811     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7812     // Promote to void*.
7813     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7814     return destType;
7815   }
7816   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7817     QualType destPointee
7818       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7819     QualType destType = S.Context.getPointerType(destPointee);
7820     // Add qualifiers if necessary.
7821     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7822     // Promote to void*.
7823     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7824     return destType;
7825   }
7826 
7827   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7828 }
7829 
7830 /// Return false if the first expression is not an integer and the second
7831 /// expression is not a pointer, true otherwise.
7832 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7833                                         Expr* PointerExpr, SourceLocation Loc,
7834                                         bool IsIntFirstExpr) {
7835   if (!PointerExpr->getType()->isPointerType() ||
7836       !Int.get()->getType()->isIntegerType())
7837     return false;
7838 
7839   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7840   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7841 
7842   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7843     << Expr1->getType() << Expr2->getType()
7844     << Expr1->getSourceRange() << Expr2->getSourceRange();
7845   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7846                             CK_IntegralToPointer);
7847   return true;
7848 }
7849 
7850 /// Simple conversion between integer and floating point types.
7851 ///
7852 /// Used when handling the OpenCL conditional operator where the
7853 /// condition is a vector while the other operands are scalar.
7854 ///
7855 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7856 /// types are either integer or floating type. Between the two
7857 /// operands, the type with the higher rank is defined as the "result
7858 /// type". The other operand needs to be promoted to the same type. No
7859 /// other type promotion is allowed. We cannot use
7860 /// UsualArithmeticConversions() for this purpose, since it always
7861 /// promotes promotable types.
7862 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7863                                             ExprResult &RHS,
7864                                             SourceLocation QuestionLoc) {
7865   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7866   if (LHS.isInvalid())
7867     return QualType();
7868   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7869   if (RHS.isInvalid())
7870     return QualType();
7871 
7872   // For conversion purposes, we ignore any qualifiers.
7873   // For example, "const float" and "float" are equivalent.
7874   QualType LHSType =
7875     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7876   QualType RHSType =
7877     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7878 
7879   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7880     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7881       << LHSType << LHS.get()->getSourceRange();
7882     return QualType();
7883   }
7884 
7885   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7886     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7887       << RHSType << RHS.get()->getSourceRange();
7888     return QualType();
7889   }
7890 
7891   // If both types are identical, no conversion is needed.
7892   if (LHSType == RHSType)
7893     return LHSType;
7894 
7895   // Now handle "real" floating types (i.e. float, double, long double).
7896   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7897     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7898                                  /*IsCompAssign = */ false);
7899 
7900   // Finally, we have two differing integer types.
7901   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7902   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7903 }
7904 
7905 /// Convert scalar operands to a vector that matches the
7906 ///        condition in length.
7907 ///
7908 /// Used when handling the OpenCL conditional operator where the
7909 /// condition is a vector while the other operands are scalar.
7910 ///
7911 /// We first compute the "result type" for the scalar operands
7912 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7913 /// into a vector of that type where the length matches the condition
7914 /// vector type. s6.11.6 requires that the element types of the result
7915 /// and the condition must have the same number of bits.
7916 static QualType
7917 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7918                               QualType CondTy, SourceLocation QuestionLoc) {
7919   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7920   if (ResTy.isNull()) return QualType();
7921 
7922   const VectorType *CV = CondTy->getAs<VectorType>();
7923   assert(CV);
7924 
7925   // Determine the vector result type
7926   unsigned NumElements = CV->getNumElements();
7927   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7928 
7929   // Ensure that all types have the same number of bits
7930   if (S.Context.getTypeSize(CV->getElementType())
7931       != S.Context.getTypeSize(ResTy)) {
7932     // Since VectorTy is created internally, it does not pretty print
7933     // with an OpenCL name. Instead, we just print a description.
7934     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7935     SmallString<64> Str;
7936     llvm::raw_svector_ostream OS(Str);
7937     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7938     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7939       << CondTy << OS.str();
7940     return QualType();
7941   }
7942 
7943   // Convert operands to the vector result type
7944   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7945   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7946 
7947   return VectorTy;
7948 }
7949 
7950 /// Return false if this is a valid OpenCL condition vector
7951 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7952                                        SourceLocation QuestionLoc) {
7953   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7954   // integral type.
7955   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7956   assert(CondTy);
7957   QualType EleTy = CondTy->getElementType();
7958   if (EleTy->isIntegerType()) return false;
7959 
7960   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7961     << Cond->getType() << Cond->getSourceRange();
7962   return true;
7963 }
7964 
7965 /// Return false if the vector condition type and the vector
7966 ///        result type are compatible.
7967 ///
7968 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7969 /// number of elements, and their element types have the same number
7970 /// of bits.
7971 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7972                               SourceLocation QuestionLoc) {
7973   const VectorType *CV = CondTy->getAs<VectorType>();
7974   const VectorType *RV = VecResTy->getAs<VectorType>();
7975   assert(CV && RV);
7976 
7977   if (CV->getNumElements() != RV->getNumElements()) {
7978     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7979       << CondTy << VecResTy;
7980     return true;
7981   }
7982 
7983   QualType CVE = CV->getElementType();
7984   QualType RVE = RV->getElementType();
7985 
7986   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7987     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7988       << CondTy << VecResTy;
7989     return true;
7990   }
7991 
7992   return false;
7993 }
7994 
7995 /// Return the resulting type for the conditional operator in
7996 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7997 ///        s6.3.i) when the condition is a vector type.
7998 static QualType
7999 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8000                              ExprResult &LHS, ExprResult &RHS,
8001                              SourceLocation QuestionLoc) {
8002   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8003   if (Cond.isInvalid())
8004     return QualType();
8005   QualType CondTy = Cond.get()->getType();
8006 
8007   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8008     return QualType();
8009 
8010   // If either operand is a vector then find the vector type of the
8011   // result as specified in OpenCL v1.1 s6.3.i.
8012   if (LHS.get()->getType()->isVectorType() ||
8013       RHS.get()->getType()->isVectorType()) {
8014     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8015                                               /*isCompAssign*/false,
8016                                               /*AllowBothBool*/true,
8017                                               /*AllowBoolConversions*/false);
8018     if (VecResTy.isNull()) return QualType();
8019     // The result type must match the condition type as specified in
8020     // OpenCL v1.1 s6.11.6.
8021     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8022       return QualType();
8023     return VecResTy;
8024   }
8025 
8026   // Both operands are scalar.
8027   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8028 }
8029 
8030 /// Return true if the Expr is block type
8031 static bool checkBlockType(Sema &S, const Expr *E) {
8032   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8033     QualType Ty = CE->getCallee()->getType();
8034     if (Ty->isBlockPointerType()) {
8035       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8036       return true;
8037     }
8038   }
8039   return false;
8040 }
8041 
8042 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8043 /// In that case, LHS = cond.
8044 /// C99 6.5.15
8045 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8046                                         ExprResult &RHS, ExprValueKind &VK,
8047                                         ExprObjectKind &OK,
8048                                         SourceLocation QuestionLoc) {
8049 
8050   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8051   if (!LHSResult.isUsable()) return QualType();
8052   LHS = LHSResult;
8053 
8054   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8055   if (!RHSResult.isUsable()) return QualType();
8056   RHS = RHSResult;
8057 
8058   // C++ is sufficiently different to merit its own checker.
8059   if (getLangOpts().CPlusPlus)
8060     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8061 
8062   VK = VK_RValue;
8063   OK = OK_Ordinary;
8064 
8065   // The OpenCL operator with a vector condition is sufficiently
8066   // different to merit its own checker.
8067   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8068       Cond.get()->getType()->isExtVectorType())
8069     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8070 
8071   // First, check the condition.
8072   Cond = UsualUnaryConversions(Cond.get());
8073   if (Cond.isInvalid())
8074     return QualType();
8075   if (checkCondition(*this, Cond.get(), QuestionLoc))
8076     return QualType();
8077 
8078   // Now check the two expressions.
8079   if (LHS.get()->getType()->isVectorType() ||
8080       RHS.get()->getType()->isVectorType())
8081     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8082                                /*AllowBothBool*/true,
8083                                /*AllowBoolConversions*/false);
8084 
8085   QualType ResTy =
8086       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8087   if (LHS.isInvalid() || RHS.isInvalid())
8088     return QualType();
8089 
8090   QualType LHSTy = LHS.get()->getType();
8091   QualType RHSTy = RHS.get()->getType();
8092 
8093   // Diagnose attempts to convert between __float128 and long double where
8094   // such conversions currently can't be handled.
8095   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8096     Diag(QuestionLoc,
8097          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8098       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8099     return QualType();
8100   }
8101 
8102   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8103   // selection operator (?:).
8104   if (getLangOpts().OpenCL &&
8105       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8106     return QualType();
8107   }
8108 
8109   // If both operands have arithmetic type, do the usual arithmetic conversions
8110   // to find a common type: C99 6.5.15p3,5.
8111   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8112     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8113     // different sizes, or between ExtInts and other types.
8114     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8115       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8116           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8117           << RHS.get()->getSourceRange();
8118       return QualType();
8119     }
8120 
8121     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8122     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8123 
8124     return ResTy;
8125   }
8126 
8127   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8128   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8129     return LHSTy;
8130   }
8131 
8132   // If both operands are the same structure or union type, the result is that
8133   // type.
8134   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8135     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8136       if (LHSRT->getDecl() == RHSRT->getDecl())
8137         // "If both the operands have structure or union type, the result has
8138         // that type."  This implies that CV qualifiers are dropped.
8139         return LHSTy.getUnqualifiedType();
8140     // FIXME: Type of conditional expression must be complete in C mode.
8141   }
8142 
8143   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8144   // The following || allows only one side to be void (a GCC-ism).
8145   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8146     return checkConditionalVoidType(*this, LHS, RHS);
8147   }
8148 
8149   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8150   // the type of the other operand."
8151   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8152   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8153 
8154   // All objective-c pointer type analysis is done here.
8155   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8156                                                         QuestionLoc);
8157   if (LHS.isInvalid() || RHS.isInvalid())
8158     return QualType();
8159   if (!compositeType.isNull())
8160     return compositeType;
8161 
8162 
8163   // Handle block pointer types.
8164   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8165     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8166                                                      QuestionLoc);
8167 
8168   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8169   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8170     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8171                                                        QuestionLoc);
8172 
8173   // GCC compatibility: soften pointer/integer mismatch.  Note that
8174   // null pointers have been filtered out by this point.
8175   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8176       /*IsIntFirstExpr=*/true))
8177     return RHSTy;
8178   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8179       /*IsIntFirstExpr=*/false))
8180     return LHSTy;
8181 
8182   // Allow ?: operations in which both operands have the same
8183   // built-in sizeless type.
8184   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8185     return LHSTy;
8186 
8187   // Emit a better diagnostic if one of the expressions is a null pointer
8188   // constant and the other is not a pointer type. In this case, the user most
8189   // likely forgot to take the address of the other expression.
8190   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8191     return QualType();
8192 
8193   // Otherwise, the operands are not compatible.
8194   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8195     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8196     << RHS.get()->getSourceRange();
8197   return QualType();
8198 }
8199 
8200 /// FindCompositeObjCPointerType - Helper method to find composite type of
8201 /// two objective-c pointer types of the two input expressions.
8202 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8203                                             SourceLocation QuestionLoc) {
8204   QualType LHSTy = LHS.get()->getType();
8205   QualType RHSTy = RHS.get()->getType();
8206 
8207   // Handle things like Class and struct objc_class*.  Here we case the result
8208   // to the pseudo-builtin, because that will be implicitly cast back to the
8209   // redefinition type if an attempt is made to access its fields.
8210   if (LHSTy->isObjCClassType() &&
8211       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8212     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8213     return LHSTy;
8214   }
8215   if (RHSTy->isObjCClassType() &&
8216       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8217     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8218     return RHSTy;
8219   }
8220   // And the same for struct objc_object* / id
8221   if (LHSTy->isObjCIdType() &&
8222       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8223     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8224     return LHSTy;
8225   }
8226   if (RHSTy->isObjCIdType() &&
8227       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8228     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8229     return RHSTy;
8230   }
8231   // And the same for struct objc_selector* / SEL
8232   if (Context.isObjCSelType(LHSTy) &&
8233       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8234     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8235     return LHSTy;
8236   }
8237   if (Context.isObjCSelType(RHSTy) &&
8238       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8239     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8240     return RHSTy;
8241   }
8242   // Check constraints for Objective-C object pointers types.
8243   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8244 
8245     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8246       // Two identical object pointer types are always compatible.
8247       return LHSTy;
8248     }
8249     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8250     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8251     QualType compositeType = LHSTy;
8252 
8253     // If both operands are interfaces and either operand can be
8254     // assigned to the other, use that type as the composite
8255     // type. This allows
8256     //   xxx ? (A*) a : (B*) b
8257     // where B is a subclass of A.
8258     //
8259     // Additionally, as for assignment, if either type is 'id'
8260     // allow silent coercion. Finally, if the types are
8261     // incompatible then make sure to use 'id' as the composite
8262     // type so the result is acceptable for sending messages to.
8263 
8264     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8265     // It could return the composite type.
8266     if (!(compositeType =
8267           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8268       // Nothing more to do.
8269     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8270       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8271     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8272       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8273     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8274                 RHSOPT->isObjCQualifiedIdType()) &&
8275                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8276                                                          true)) {
8277       // Need to handle "id<xx>" explicitly.
8278       // GCC allows qualified id and any Objective-C type to devolve to
8279       // id. Currently localizing to here until clear this should be
8280       // part of ObjCQualifiedIdTypesAreCompatible.
8281       compositeType = Context.getObjCIdType();
8282     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8283       compositeType = Context.getObjCIdType();
8284     } else {
8285       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8286       << LHSTy << RHSTy
8287       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8288       QualType incompatTy = Context.getObjCIdType();
8289       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8290       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8291       return incompatTy;
8292     }
8293     // The object pointer types are compatible.
8294     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8295     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8296     return compositeType;
8297   }
8298   // Check Objective-C object pointer types and 'void *'
8299   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8300     if (getLangOpts().ObjCAutoRefCount) {
8301       // ARC forbids the implicit conversion of object pointers to 'void *',
8302       // so these types are not compatible.
8303       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8304           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8305       LHS = RHS = true;
8306       return QualType();
8307     }
8308     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8309     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8310     QualType destPointee
8311     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8312     QualType destType = Context.getPointerType(destPointee);
8313     // Add qualifiers if necessary.
8314     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8315     // Promote to void*.
8316     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8317     return destType;
8318   }
8319   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8320     if (getLangOpts().ObjCAutoRefCount) {
8321       // ARC forbids the implicit conversion of object pointers to 'void *',
8322       // so these types are not compatible.
8323       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8324           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8325       LHS = RHS = true;
8326       return QualType();
8327     }
8328     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8329     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8330     QualType destPointee
8331     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8332     QualType destType = Context.getPointerType(destPointee);
8333     // Add qualifiers if necessary.
8334     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8335     // Promote to void*.
8336     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8337     return destType;
8338   }
8339   return QualType();
8340 }
8341 
8342 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8343 /// ParenRange in parentheses.
8344 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8345                                const PartialDiagnostic &Note,
8346                                SourceRange ParenRange) {
8347   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8348   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8349       EndLoc.isValid()) {
8350     Self.Diag(Loc, Note)
8351       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8352       << FixItHint::CreateInsertion(EndLoc, ")");
8353   } else {
8354     // We can't display the parentheses, so just show the bare note.
8355     Self.Diag(Loc, Note) << ParenRange;
8356   }
8357 }
8358 
8359 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8360   return BinaryOperator::isAdditiveOp(Opc) ||
8361          BinaryOperator::isMultiplicativeOp(Opc) ||
8362          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8363   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8364   // not any of the logical operators.  Bitwise-xor is commonly used as a
8365   // logical-xor because there is no logical-xor operator.  The logical
8366   // operators, including uses of xor, have a high false positive rate for
8367   // precedence warnings.
8368 }
8369 
8370 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8371 /// expression, either using a built-in or overloaded operator,
8372 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8373 /// expression.
8374 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8375                                    Expr **RHSExprs) {
8376   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8377   E = E->IgnoreImpCasts();
8378   E = E->IgnoreConversionOperator();
8379   E = E->IgnoreImpCasts();
8380   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8381     E = MTE->getSubExpr();
8382     E = E->IgnoreImpCasts();
8383   }
8384 
8385   // Built-in binary operator.
8386   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8387     if (IsArithmeticOp(OP->getOpcode())) {
8388       *Opcode = OP->getOpcode();
8389       *RHSExprs = OP->getRHS();
8390       return true;
8391     }
8392   }
8393 
8394   // Overloaded operator.
8395   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8396     if (Call->getNumArgs() != 2)
8397       return false;
8398 
8399     // Make sure this is really a binary operator that is safe to pass into
8400     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8401     OverloadedOperatorKind OO = Call->getOperator();
8402     if (OO < OO_Plus || OO > OO_Arrow ||
8403         OO == OO_PlusPlus || OO == OO_MinusMinus)
8404       return false;
8405 
8406     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8407     if (IsArithmeticOp(OpKind)) {
8408       *Opcode = OpKind;
8409       *RHSExprs = Call->getArg(1);
8410       return true;
8411     }
8412   }
8413 
8414   return false;
8415 }
8416 
8417 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8418 /// or is a logical expression such as (x==y) which has int type, but is
8419 /// commonly interpreted as boolean.
8420 static bool ExprLooksBoolean(Expr *E) {
8421   E = E->IgnoreParenImpCasts();
8422 
8423   if (E->getType()->isBooleanType())
8424     return true;
8425   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8426     return OP->isComparisonOp() || OP->isLogicalOp();
8427   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8428     return OP->getOpcode() == UO_LNot;
8429   if (E->getType()->isPointerType())
8430     return true;
8431   // FIXME: What about overloaded operator calls returning "unspecified boolean
8432   // type"s (commonly pointer-to-members)?
8433 
8434   return false;
8435 }
8436 
8437 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8438 /// and binary operator are mixed in a way that suggests the programmer assumed
8439 /// the conditional operator has higher precedence, for example:
8440 /// "int x = a + someBinaryCondition ? 1 : 2".
8441 static void DiagnoseConditionalPrecedence(Sema &Self,
8442                                           SourceLocation OpLoc,
8443                                           Expr *Condition,
8444                                           Expr *LHSExpr,
8445                                           Expr *RHSExpr) {
8446   BinaryOperatorKind CondOpcode;
8447   Expr *CondRHS;
8448 
8449   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8450     return;
8451   if (!ExprLooksBoolean(CondRHS))
8452     return;
8453 
8454   // The condition is an arithmetic binary expression, with a right-
8455   // hand side that looks boolean, so warn.
8456 
8457   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8458                         ? diag::warn_precedence_bitwise_conditional
8459                         : diag::warn_precedence_conditional;
8460 
8461   Self.Diag(OpLoc, DiagID)
8462       << Condition->getSourceRange()
8463       << BinaryOperator::getOpcodeStr(CondOpcode);
8464 
8465   SuggestParentheses(
8466       Self, OpLoc,
8467       Self.PDiag(diag::note_precedence_silence)
8468           << BinaryOperator::getOpcodeStr(CondOpcode),
8469       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8470 
8471   SuggestParentheses(Self, OpLoc,
8472                      Self.PDiag(diag::note_precedence_conditional_first),
8473                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8474 }
8475 
8476 /// Compute the nullability of a conditional expression.
8477 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8478                                               QualType LHSTy, QualType RHSTy,
8479                                               ASTContext &Ctx) {
8480   if (!ResTy->isAnyPointerType())
8481     return ResTy;
8482 
8483   auto GetNullability = [&Ctx](QualType Ty) {
8484     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8485     if (Kind)
8486       return *Kind;
8487     return NullabilityKind::Unspecified;
8488   };
8489 
8490   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8491   NullabilityKind MergedKind;
8492 
8493   // Compute nullability of a binary conditional expression.
8494   if (IsBin) {
8495     if (LHSKind == NullabilityKind::NonNull)
8496       MergedKind = NullabilityKind::NonNull;
8497     else
8498       MergedKind = RHSKind;
8499   // Compute nullability of a normal conditional expression.
8500   } else {
8501     if (LHSKind == NullabilityKind::Nullable ||
8502         RHSKind == NullabilityKind::Nullable)
8503       MergedKind = NullabilityKind::Nullable;
8504     else if (LHSKind == NullabilityKind::NonNull)
8505       MergedKind = RHSKind;
8506     else if (RHSKind == NullabilityKind::NonNull)
8507       MergedKind = LHSKind;
8508     else
8509       MergedKind = NullabilityKind::Unspecified;
8510   }
8511 
8512   // Return if ResTy already has the correct nullability.
8513   if (GetNullability(ResTy) == MergedKind)
8514     return ResTy;
8515 
8516   // Strip all nullability from ResTy.
8517   while (ResTy->getNullability(Ctx))
8518     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8519 
8520   // Create a new AttributedType with the new nullability kind.
8521   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8522   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8523 }
8524 
8525 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8526 /// in the case of a the GNU conditional expr extension.
8527 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8528                                     SourceLocation ColonLoc,
8529                                     Expr *CondExpr, Expr *LHSExpr,
8530                                     Expr *RHSExpr) {
8531   if (!getLangOpts().CPlusPlus) {
8532     // C cannot handle TypoExpr nodes in the condition because it
8533     // doesn't handle dependent types properly, so make sure any TypoExprs have
8534     // been dealt with before checking the operands.
8535     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8536     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8537     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8538 
8539     if (!CondResult.isUsable())
8540       return ExprError();
8541 
8542     if (LHSExpr) {
8543       if (!LHSResult.isUsable())
8544         return ExprError();
8545     }
8546 
8547     if (!RHSResult.isUsable())
8548       return ExprError();
8549 
8550     CondExpr = CondResult.get();
8551     LHSExpr = LHSResult.get();
8552     RHSExpr = RHSResult.get();
8553   }
8554 
8555   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8556   // was the condition.
8557   OpaqueValueExpr *opaqueValue = nullptr;
8558   Expr *commonExpr = nullptr;
8559   if (!LHSExpr) {
8560     commonExpr = CondExpr;
8561     // Lower out placeholder types first.  This is important so that we don't
8562     // try to capture a placeholder. This happens in few cases in C++; such
8563     // as Objective-C++'s dictionary subscripting syntax.
8564     if (commonExpr->hasPlaceholderType()) {
8565       ExprResult result = CheckPlaceholderExpr(commonExpr);
8566       if (!result.isUsable()) return ExprError();
8567       commonExpr = result.get();
8568     }
8569     // We usually want to apply unary conversions *before* saving, except
8570     // in the special case of a C++ l-value conditional.
8571     if (!(getLangOpts().CPlusPlus
8572           && !commonExpr->isTypeDependent()
8573           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8574           && commonExpr->isGLValue()
8575           && commonExpr->isOrdinaryOrBitFieldObject()
8576           && RHSExpr->isOrdinaryOrBitFieldObject()
8577           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8578       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8579       if (commonRes.isInvalid())
8580         return ExprError();
8581       commonExpr = commonRes.get();
8582     }
8583 
8584     // If the common expression is a class or array prvalue, materialize it
8585     // so that we can safely refer to it multiple times.
8586     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8587                                    commonExpr->getType()->isArrayType())) {
8588       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8589       if (MatExpr.isInvalid())
8590         return ExprError();
8591       commonExpr = MatExpr.get();
8592     }
8593 
8594     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8595                                                 commonExpr->getType(),
8596                                                 commonExpr->getValueKind(),
8597                                                 commonExpr->getObjectKind(),
8598                                                 commonExpr);
8599     LHSExpr = CondExpr = opaqueValue;
8600   }
8601 
8602   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8603   ExprValueKind VK = VK_RValue;
8604   ExprObjectKind OK = OK_Ordinary;
8605   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8606   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8607                                              VK, OK, QuestionLoc);
8608   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8609       RHS.isInvalid())
8610     return ExprError();
8611 
8612   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8613                                 RHS.get());
8614 
8615   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8616 
8617   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8618                                          Context);
8619 
8620   if (!commonExpr)
8621     return new (Context)
8622         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8623                             RHS.get(), result, VK, OK);
8624 
8625   return new (Context) BinaryConditionalOperator(
8626       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8627       ColonLoc, result, VK, OK);
8628 }
8629 
8630 // Check if we have a conversion between incompatible cmse function pointer
8631 // types, that is, a conversion between a function pointer with the
8632 // cmse_nonsecure_call attribute and one without.
8633 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8634                                           QualType ToType) {
8635   if (const auto *ToFn =
8636           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8637     if (const auto *FromFn =
8638             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8639       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8640       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8641 
8642       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8643     }
8644   }
8645   return false;
8646 }
8647 
8648 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8649 // being closely modeled after the C99 spec:-). The odd characteristic of this
8650 // routine is it effectively iqnores the qualifiers on the top level pointee.
8651 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8652 // FIXME: add a couple examples in this comment.
8653 static Sema::AssignConvertType
8654 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8655   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8656   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8657 
8658   // get the "pointed to" type (ignoring qualifiers at the top level)
8659   const Type *lhptee, *rhptee;
8660   Qualifiers lhq, rhq;
8661   std::tie(lhptee, lhq) =
8662       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8663   std::tie(rhptee, rhq) =
8664       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8665 
8666   Sema::AssignConvertType ConvTy = Sema::Compatible;
8667 
8668   // C99 6.5.16.1p1: This following citation is common to constraints
8669   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8670   // qualifiers of the type *pointed to* by the right;
8671 
8672   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8673   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8674       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8675     // Ignore lifetime for further calculation.
8676     lhq.removeObjCLifetime();
8677     rhq.removeObjCLifetime();
8678   }
8679 
8680   if (!lhq.compatiblyIncludes(rhq)) {
8681     // Treat address-space mismatches as fatal.
8682     if (!lhq.isAddressSpaceSupersetOf(rhq))
8683       return Sema::IncompatiblePointerDiscardsQualifiers;
8684 
8685     // It's okay to add or remove GC or lifetime qualifiers when converting to
8686     // and from void*.
8687     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8688                         .compatiblyIncludes(
8689                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8690              && (lhptee->isVoidType() || rhptee->isVoidType()))
8691       ; // keep old
8692 
8693     // Treat lifetime mismatches as fatal.
8694     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8695       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8696 
8697     // For GCC/MS compatibility, other qualifier mismatches are treated
8698     // as still compatible in C.
8699     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8700   }
8701 
8702   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8703   // incomplete type and the other is a pointer to a qualified or unqualified
8704   // version of void...
8705   if (lhptee->isVoidType()) {
8706     if (rhptee->isIncompleteOrObjectType())
8707       return ConvTy;
8708 
8709     // As an extension, we allow cast to/from void* to function pointer.
8710     assert(rhptee->isFunctionType());
8711     return Sema::FunctionVoidPointer;
8712   }
8713 
8714   if (rhptee->isVoidType()) {
8715     if (lhptee->isIncompleteOrObjectType())
8716       return ConvTy;
8717 
8718     // As an extension, we allow cast to/from void* to function pointer.
8719     assert(lhptee->isFunctionType());
8720     return Sema::FunctionVoidPointer;
8721   }
8722 
8723   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8724   // unqualified versions of compatible types, ...
8725   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8726   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8727     // Check if the pointee types are compatible ignoring the sign.
8728     // We explicitly check for char so that we catch "char" vs
8729     // "unsigned char" on systems where "char" is unsigned.
8730     if (lhptee->isCharType())
8731       ltrans = S.Context.UnsignedCharTy;
8732     else if (lhptee->hasSignedIntegerRepresentation())
8733       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8734 
8735     if (rhptee->isCharType())
8736       rtrans = S.Context.UnsignedCharTy;
8737     else if (rhptee->hasSignedIntegerRepresentation())
8738       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8739 
8740     if (ltrans == rtrans) {
8741       // Types are compatible ignoring the sign. Qualifier incompatibility
8742       // takes priority over sign incompatibility because the sign
8743       // warning can be disabled.
8744       if (ConvTy != Sema::Compatible)
8745         return ConvTy;
8746 
8747       return Sema::IncompatiblePointerSign;
8748     }
8749 
8750     // If we are a multi-level pointer, it's possible that our issue is simply
8751     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8752     // the eventual target type is the same and the pointers have the same
8753     // level of indirection, this must be the issue.
8754     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8755       do {
8756         std::tie(lhptee, lhq) =
8757           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8758         std::tie(rhptee, rhq) =
8759           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8760 
8761         // Inconsistent address spaces at this point is invalid, even if the
8762         // address spaces would be compatible.
8763         // FIXME: This doesn't catch address space mismatches for pointers of
8764         // different nesting levels, like:
8765         //   __local int *** a;
8766         //   int ** b = a;
8767         // It's not clear how to actually determine when such pointers are
8768         // invalidly incompatible.
8769         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8770           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8771 
8772       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8773 
8774       if (lhptee == rhptee)
8775         return Sema::IncompatibleNestedPointerQualifiers;
8776     }
8777 
8778     // General pointer incompatibility takes priority over qualifiers.
8779     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8780       return Sema::IncompatibleFunctionPointer;
8781     return Sema::IncompatiblePointer;
8782   }
8783   if (!S.getLangOpts().CPlusPlus &&
8784       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8785     return Sema::IncompatibleFunctionPointer;
8786   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8787     return Sema::IncompatibleFunctionPointer;
8788   return ConvTy;
8789 }
8790 
8791 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8792 /// block pointer types are compatible or whether a block and normal pointer
8793 /// are compatible. It is more restrict than comparing two function pointer
8794 // types.
8795 static Sema::AssignConvertType
8796 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8797                                     QualType RHSType) {
8798   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8799   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8800 
8801   QualType lhptee, rhptee;
8802 
8803   // get the "pointed to" type (ignoring qualifiers at the top level)
8804   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8805   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8806 
8807   // In C++, the types have to match exactly.
8808   if (S.getLangOpts().CPlusPlus)
8809     return Sema::IncompatibleBlockPointer;
8810 
8811   Sema::AssignConvertType ConvTy = Sema::Compatible;
8812 
8813   // For blocks we enforce that qualifiers are identical.
8814   Qualifiers LQuals = lhptee.getLocalQualifiers();
8815   Qualifiers RQuals = rhptee.getLocalQualifiers();
8816   if (S.getLangOpts().OpenCL) {
8817     LQuals.removeAddressSpace();
8818     RQuals.removeAddressSpace();
8819   }
8820   if (LQuals != RQuals)
8821     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8822 
8823   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8824   // assignment.
8825   // The current behavior is similar to C++ lambdas. A block might be
8826   // assigned to a variable iff its return type and parameters are compatible
8827   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8828   // an assignment. Presumably it should behave in way that a function pointer
8829   // assignment does in C, so for each parameter and return type:
8830   //  * CVR and address space of LHS should be a superset of CVR and address
8831   //  space of RHS.
8832   //  * unqualified types should be compatible.
8833   if (S.getLangOpts().OpenCL) {
8834     if (!S.Context.typesAreBlockPointerCompatible(
8835             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8836             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8837       return Sema::IncompatibleBlockPointer;
8838   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8839     return Sema::IncompatibleBlockPointer;
8840 
8841   return ConvTy;
8842 }
8843 
8844 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8845 /// for assignment compatibility.
8846 static Sema::AssignConvertType
8847 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8848                                    QualType RHSType) {
8849   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8850   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8851 
8852   if (LHSType->isObjCBuiltinType()) {
8853     // Class is not compatible with ObjC object pointers.
8854     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8855         !RHSType->isObjCQualifiedClassType())
8856       return Sema::IncompatiblePointer;
8857     return Sema::Compatible;
8858   }
8859   if (RHSType->isObjCBuiltinType()) {
8860     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8861         !LHSType->isObjCQualifiedClassType())
8862       return Sema::IncompatiblePointer;
8863     return Sema::Compatible;
8864   }
8865   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8866   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8867 
8868   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8869       // make an exception for id<P>
8870       !LHSType->isObjCQualifiedIdType())
8871     return Sema::CompatiblePointerDiscardsQualifiers;
8872 
8873   if (S.Context.typesAreCompatible(LHSType, RHSType))
8874     return Sema::Compatible;
8875   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8876     return Sema::IncompatibleObjCQualifiedId;
8877   return Sema::IncompatiblePointer;
8878 }
8879 
8880 Sema::AssignConvertType
8881 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8882                                  QualType LHSType, QualType RHSType) {
8883   // Fake up an opaque expression.  We don't actually care about what
8884   // cast operations are required, so if CheckAssignmentConstraints
8885   // adds casts to this they'll be wasted, but fortunately that doesn't
8886   // usually happen on valid code.
8887   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8888   ExprResult RHSPtr = &RHSExpr;
8889   CastKind K;
8890 
8891   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8892 }
8893 
8894 /// This helper function returns true if QT is a vector type that has element
8895 /// type ElementType.
8896 static bool isVector(QualType QT, QualType ElementType) {
8897   if (const VectorType *VT = QT->getAs<VectorType>())
8898     return VT->getElementType().getCanonicalType() == ElementType;
8899   return false;
8900 }
8901 
8902 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8903 /// has code to accommodate several GCC extensions when type checking
8904 /// pointers. Here are some objectionable examples that GCC considers warnings:
8905 ///
8906 ///  int a, *pint;
8907 ///  short *pshort;
8908 ///  struct foo *pfoo;
8909 ///
8910 ///  pint = pshort; // warning: assignment from incompatible pointer type
8911 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8912 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8913 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8914 ///
8915 /// As a result, the code for dealing with pointers is more complex than the
8916 /// C99 spec dictates.
8917 ///
8918 /// Sets 'Kind' for any result kind except Incompatible.
8919 Sema::AssignConvertType
8920 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8921                                  CastKind &Kind, bool ConvertRHS) {
8922   QualType RHSType = RHS.get()->getType();
8923   QualType OrigLHSType = LHSType;
8924 
8925   // Get canonical types.  We're not formatting these types, just comparing
8926   // them.
8927   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8928   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8929 
8930   // Common case: no conversion required.
8931   if (LHSType == RHSType) {
8932     Kind = CK_NoOp;
8933     return Compatible;
8934   }
8935 
8936   // If we have an atomic type, try a non-atomic assignment, then just add an
8937   // atomic qualification step.
8938   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8939     Sema::AssignConvertType result =
8940       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8941     if (result != Compatible)
8942       return result;
8943     if (Kind != CK_NoOp && ConvertRHS)
8944       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8945     Kind = CK_NonAtomicToAtomic;
8946     return Compatible;
8947   }
8948 
8949   // If the left-hand side is a reference type, then we are in a
8950   // (rare!) case where we've allowed the use of references in C,
8951   // e.g., as a parameter type in a built-in function. In this case,
8952   // just make sure that the type referenced is compatible with the
8953   // right-hand side type. The caller is responsible for adjusting
8954   // LHSType so that the resulting expression does not have reference
8955   // type.
8956   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8957     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8958       Kind = CK_LValueBitCast;
8959       return Compatible;
8960     }
8961     return Incompatible;
8962   }
8963 
8964   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8965   // to the same ExtVector type.
8966   if (LHSType->isExtVectorType()) {
8967     if (RHSType->isExtVectorType())
8968       return Incompatible;
8969     if (RHSType->isArithmeticType()) {
8970       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8971       if (ConvertRHS)
8972         RHS = prepareVectorSplat(LHSType, RHS.get());
8973       Kind = CK_VectorSplat;
8974       return Compatible;
8975     }
8976   }
8977 
8978   // Conversions to or from vector type.
8979   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8980     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8981       // Allow assignments of an AltiVec vector type to an equivalent GCC
8982       // vector type and vice versa
8983       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8984         Kind = CK_BitCast;
8985         return Compatible;
8986       }
8987 
8988       // If we are allowing lax vector conversions, and LHS and RHS are both
8989       // vectors, the total size only needs to be the same. This is a bitcast;
8990       // no bits are changed but the result type is different.
8991       if (isLaxVectorConversion(RHSType, LHSType)) {
8992         Kind = CK_BitCast;
8993         return IncompatibleVectors;
8994       }
8995     }
8996 
8997     // When the RHS comes from another lax conversion (e.g. binops between
8998     // scalars and vectors) the result is canonicalized as a vector. When the
8999     // LHS is also a vector, the lax is allowed by the condition above. Handle
9000     // the case where LHS is a scalar.
9001     if (LHSType->isScalarType()) {
9002       const VectorType *VecType = RHSType->getAs<VectorType>();
9003       if (VecType && VecType->getNumElements() == 1 &&
9004           isLaxVectorConversion(RHSType, LHSType)) {
9005         ExprResult *VecExpr = &RHS;
9006         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9007         Kind = CK_BitCast;
9008         return Compatible;
9009       }
9010     }
9011 
9012     // Allow assignments between fixed-length and sizeless SVE vectors.
9013     if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9014          (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) &&
9015         Context.areCompatibleSveTypes(LHSType, RHSType)) {
9016       Kind = CK_BitCast;
9017       return Compatible;
9018     }
9019 
9020     return Incompatible;
9021   }
9022 
9023   // Diagnose attempts to convert between __float128 and long double where
9024   // such conversions currently can't be handled.
9025   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9026     return Incompatible;
9027 
9028   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9029   // discards the imaginary part.
9030   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9031       !LHSType->getAs<ComplexType>())
9032     return Incompatible;
9033 
9034   // Arithmetic conversions.
9035   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9036       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9037     if (ConvertRHS)
9038       Kind = PrepareScalarCast(RHS, LHSType);
9039     return Compatible;
9040   }
9041 
9042   // Conversions to normal pointers.
9043   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9044     // U* -> T*
9045     if (isa<PointerType>(RHSType)) {
9046       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9047       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9048       if (AddrSpaceL != AddrSpaceR)
9049         Kind = CK_AddressSpaceConversion;
9050       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9051         Kind = CK_NoOp;
9052       else
9053         Kind = CK_BitCast;
9054       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9055     }
9056 
9057     // int -> T*
9058     if (RHSType->isIntegerType()) {
9059       Kind = CK_IntegralToPointer; // FIXME: null?
9060       return IntToPointer;
9061     }
9062 
9063     // C pointers are not compatible with ObjC object pointers,
9064     // with two exceptions:
9065     if (isa<ObjCObjectPointerType>(RHSType)) {
9066       //  - conversions to void*
9067       if (LHSPointer->getPointeeType()->isVoidType()) {
9068         Kind = CK_BitCast;
9069         return Compatible;
9070       }
9071 
9072       //  - conversions from 'Class' to the redefinition type
9073       if (RHSType->isObjCClassType() &&
9074           Context.hasSameType(LHSType,
9075                               Context.getObjCClassRedefinitionType())) {
9076         Kind = CK_BitCast;
9077         return Compatible;
9078       }
9079 
9080       Kind = CK_BitCast;
9081       return IncompatiblePointer;
9082     }
9083 
9084     // U^ -> void*
9085     if (RHSType->getAs<BlockPointerType>()) {
9086       if (LHSPointer->getPointeeType()->isVoidType()) {
9087         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9088         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9089                                 ->getPointeeType()
9090                                 .getAddressSpace();
9091         Kind =
9092             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9093         return Compatible;
9094       }
9095     }
9096 
9097     return Incompatible;
9098   }
9099 
9100   // Conversions to block pointers.
9101   if (isa<BlockPointerType>(LHSType)) {
9102     // U^ -> T^
9103     if (RHSType->isBlockPointerType()) {
9104       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9105                               ->getPointeeType()
9106                               .getAddressSpace();
9107       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9108                               ->getPointeeType()
9109                               .getAddressSpace();
9110       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9111       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9112     }
9113 
9114     // int or null -> T^
9115     if (RHSType->isIntegerType()) {
9116       Kind = CK_IntegralToPointer; // FIXME: null
9117       return IntToBlockPointer;
9118     }
9119 
9120     // id -> T^
9121     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9122       Kind = CK_AnyPointerToBlockPointerCast;
9123       return Compatible;
9124     }
9125 
9126     // void* -> T^
9127     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9128       if (RHSPT->getPointeeType()->isVoidType()) {
9129         Kind = CK_AnyPointerToBlockPointerCast;
9130         return Compatible;
9131       }
9132 
9133     return Incompatible;
9134   }
9135 
9136   // Conversions to Objective-C pointers.
9137   if (isa<ObjCObjectPointerType>(LHSType)) {
9138     // A* -> B*
9139     if (RHSType->isObjCObjectPointerType()) {
9140       Kind = CK_BitCast;
9141       Sema::AssignConvertType result =
9142         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9143       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9144           result == Compatible &&
9145           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9146         result = IncompatibleObjCWeakRef;
9147       return result;
9148     }
9149 
9150     // int or null -> A*
9151     if (RHSType->isIntegerType()) {
9152       Kind = CK_IntegralToPointer; // FIXME: null
9153       return IntToPointer;
9154     }
9155 
9156     // In general, C pointers are not compatible with ObjC object pointers,
9157     // with two exceptions:
9158     if (isa<PointerType>(RHSType)) {
9159       Kind = CK_CPointerToObjCPointerCast;
9160 
9161       //  - conversions from 'void*'
9162       if (RHSType->isVoidPointerType()) {
9163         return Compatible;
9164       }
9165 
9166       //  - conversions to 'Class' from its redefinition type
9167       if (LHSType->isObjCClassType() &&
9168           Context.hasSameType(RHSType,
9169                               Context.getObjCClassRedefinitionType())) {
9170         return Compatible;
9171       }
9172 
9173       return IncompatiblePointer;
9174     }
9175 
9176     // Only under strict condition T^ is compatible with an Objective-C pointer.
9177     if (RHSType->isBlockPointerType() &&
9178         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9179       if (ConvertRHS)
9180         maybeExtendBlockObject(RHS);
9181       Kind = CK_BlockPointerToObjCPointerCast;
9182       return Compatible;
9183     }
9184 
9185     return Incompatible;
9186   }
9187 
9188   // Conversions from pointers that are not covered by the above.
9189   if (isa<PointerType>(RHSType)) {
9190     // T* -> _Bool
9191     if (LHSType == Context.BoolTy) {
9192       Kind = CK_PointerToBoolean;
9193       return Compatible;
9194     }
9195 
9196     // T* -> int
9197     if (LHSType->isIntegerType()) {
9198       Kind = CK_PointerToIntegral;
9199       return PointerToInt;
9200     }
9201 
9202     return Incompatible;
9203   }
9204 
9205   // Conversions from Objective-C pointers that are not covered by the above.
9206   if (isa<ObjCObjectPointerType>(RHSType)) {
9207     // T* -> _Bool
9208     if (LHSType == Context.BoolTy) {
9209       Kind = CK_PointerToBoolean;
9210       return Compatible;
9211     }
9212 
9213     // T* -> int
9214     if (LHSType->isIntegerType()) {
9215       Kind = CK_PointerToIntegral;
9216       return PointerToInt;
9217     }
9218 
9219     return Incompatible;
9220   }
9221 
9222   // struct A -> struct B
9223   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9224     if (Context.typesAreCompatible(LHSType, RHSType)) {
9225       Kind = CK_NoOp;
9226       return Compatible;
9227     }
9228   }
9229 
9230   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9231     Kind = CK_IntToOCLSampler;
9232     return Compatible;
9233   }
9234 
9235   return Incompatible;
9236 }
9237 
9238 /// Constructs a transparent union from an expression that is
9239 /// used to initialize the transparent union.
9240 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9241                                       ExprResult &EResult, QualType UnionType,
9242                                       FieldDecl *Field) {
9243   // Build an initializer list that designates the appropriate member
9244   // of the transparent union.
9245   Expr *E = EResult.get();
9246   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9247                                                    E, SourceLocation());
9248   Initializer->setType(UnionType);
9249   Initializer->setInitializedFieldInUnion(Field);
9250 
9251   // Build a compound literal constructing a value of the transparent
9252   // union type from this initializer list.
9253   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9254   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9255                                         VK_RValue, Initializer, false);
9256 }
9257 
9258 Sema::AssignConvertType
9259 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9260                                                ExprResult &RHS) {
9261   QualType RHSType = RHS.get()->getType();
9262 
9263   // If the ArgType is a Union type, we want to handle a potential
9264   // transparent_union GCC extension.
9265   const RecordType *UT = ArgType->getAsUnionType();
9266   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9267     return Incompatible;
9268 
9269   // The field to initialize within the transparent union.
9270   RecordDecl *UD = UT->getDecl();
9271   FieldDecl *InitField = nullptr;
9272   // It's compatible if the expression matches any of the fields.
9273   for (auto *it : UD->fields()) {
9274     if (it->getType()->isPointerType()) {
9275       // If the transparent union contains a pointer type, we allow:
9276       // 1) void pointer
9277       // 2) null pointer constant
9278       if (RHSType->isPointerType())
9279         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9280           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9281           InitField = it;
9282           break;
9283         }
9284 
9285       if (RHS.get()->isNullPointerConstant(Context,
9286                                            Expr::NPC_ValueDependentIsNull)) {
9287         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9288                                 CK_NullToPointer);
9289         InitField = it;
9290         break;
9291       }
9292     }
9293 
9294     CastKind Kind;
9295     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9296           == Compatible) {
9297       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9298       InitField = it;
9299       break;
9300     }
9301   }
9302 
9303   if (!InitField)
9304     return Incompatible;
9305 
9306   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9307   return Compatible;
9308 }
9309 
9310 Sema::AssignConvertType
9311 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9312                                        bool Diagnose,
9313                                        bool DiagnoseCFAudited,
9314                                        bool ConvertRHS) {
9315   // We need to be able to tell the caller whether we diagnosed a problem, if
9316   // they ask us to issue diagnostics.
9317   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9318 
9319   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9320   // we can't avoid *all* modifications at the moment, so we need some somewhere
9321   // to put the updated value.
9322   ExprResult LocalRHS = CallerRHS;
9323   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9324 
9325   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9326     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9327       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9328           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9329         Diag(RHS.get()->getExprLoc(),
9330              diag::warn_noderef_to_dereferenceable_pointer)
9331             << RHS.get()->getSourceRange();
9332       }
9333     }
9334   }
9335 
9336   if (getLangOpts().CPlusPlus) {
9337     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9338       // C++ 5.17p3: If the left operand is not of class type, the
9339       // expression is implicitly converted (C++ 4) to the
9340       // cv-unqualified type of the left operand.
9341       QualType RHSType = RHS.get()->getType();
9342       if (Diagnose) {
9343         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9344                                         AA_Assigning);
9345       } else {
9346         ImplicitConversionSequence ICS =
9347             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9348                                   /*SuppressUserConversions=*/false,
9349                                   AllowedExplicit::None,
9350                                   /*InOverloadResolution=*/false,
9351                                   /*CStyle=*/false,
9352                                   /*AllowObjCWritebackConversion=*/false);
9353         if (ICS.isFailure())
9354           return Incompatible;
9355         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9356                                         ICS, AA_Assigning);
9357       }
9358       if (RHS.isInvalid())
9359         return Incompatible;
9360       Sema::AssignConvertType result = Compatible;
9361       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9362           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9363         result = IncompatibleObjCWeakRef;
9364       return result;
9365     }
9366 
9367     // FIXME: Currently, we fall through and treat C++ classes like C
9368     // structures.
9369     // FIXME: We also fall through for atomics; not sure what should
9370     // happen there, though.
9371   } else if (RHS.get()->getType() == Context.OverloadTy) {
9372     // As a set of extensions to C, we support overloading on functions. These
9373     // functions need to be resolved here.
9374     DeclAccessPair DAP;
9375     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9376             RHS.get(), LHSType, /*Complain=*/false, DAP))
9377       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9378     else
9379       return Incompatible;
9380   }
9381 
9382   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9383   // a null pointer constant.
9384   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9385        LHSType->isBlockPointerType()) &&
9386       RHS.get()->isNullPointerConstant(Context,
9387                                        Expr::NPC_ValueDependentIsNull)) {
9388     if (Diagnose || ConvertRHS) {
9389       CastKind Kind;
9390       CXXCastPath Path;
9391       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9392                              /*IgnoreBaseAccess=*/false, Diagnose);
9393       if (ConvertRHS)
9394         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9395     }
9396     return Compatible;
9397   }
9398 
9399   // OpenCL queue_t type assignment.
9400   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9401                                  Context, Expr::NPC_ValueDependentIsNull)) {
9402     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9403     return Compatible;
9404   }
9405 
9406   // This check seems unnatural, however it is necessary to ensure the proper
9407   // conversion of functions/arrays. If the conversion were done for all
9408   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9409   // expressions that suppress this implicit conversion (&, sizeof).
9410   //
9411   // Suppress this for references: C++ 8.5.3p5.
9412   if (!LHSType->isReferenceType()) {
9413     // FIXME: We potentially allocate here even if ConvertRHS is false.
9414     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9415     if (RHS.isInvalid())
9416       return Incompatible;
9417   }
9418   CastKind Kind;
9419   Sema::AssignConvertType result =
9420     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9421 
9422   // C99 6.5.16.1p2: The value of the right operand is converted to the
9423   // type of the assignment expression.
9424   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9425   // so that we can use references in built-in functions even in C.
9426   // The getNonReferenceType() call makes sure that the resulting expression
9427   // does not have reference type.
9428   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9429     QualType Ty = LHSType.getNonLValueExprType(Context);
9430     Expr *E = RHS.get();
9431 
9432     // Check for various Objective-C errors. If we are not reporting
9433     // diagnostics and just checking for errors, e.g., during overload
9434     // resolution, return Incompatible to indicate the failure.
9435     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9436         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9437                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9438       if (!Diagnose)
9439         return Incompatible;
9440     }
9441     if (getLangOpts().ObjC &&
9442         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9443                                            E->getType(), E, Diagnose) ||
9444          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9445       if (!Diagnose)
9446         return Incompatible;
9447       // Replace the expression with a corrected version and continue so we
9448       // can find further errors.
9449       RHS = E;
9450       return Compatible;
9451     }
9452 
9453     if (ConvertRHS)
9454       RHS = ImpCastExprToType(E, Ty, Kind);
9455   }
9456 
9457   return result;
9458 }
9459 
9460 namespace {
9461 /// The original operand to an operator, prior to the application of the usual
9462 /// arithmetic conversions and converting the arguments of a builtin operator
9463 /// candidate.
9464 struct OriginalOperand {
9465   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9466     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9467       Op = MTE->getSubExpr();
9468     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9469       Op = BTE->getSubExpr();
9470     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9471       Orig = ICE->getSubExprAsWritten();
9472       Conversion = ICE->getConversionFunction();
9473     }
9474   }
9475 
9476   QualType getType() const { return Orig->getType(); }
9477 
9478   Expr *Orig;
9479   NamedDecl *Conversion;
9480 };
9481 }
9482 
9483 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9484                                ExprResult &RHS) {
9485   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9486 
9487   Diag(Loc, diag::err_typecheck_invalid_operands)
9488     << OrigLHS.getType() << OrigRHS.getType()
9489     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9490 
9491   // If a user-defined conversion was applied to either of the operands prior
9492   // to applying the built-in operator rules, tell the user about it.
9493   if (OrigLHS.Conversion) {
9494     Diag(OrigLHS.Conversion->getLocation(),
9495          diag::note_typecheck_invalid_operands_converted)
9496       << 0 << LHS.get()->getType();
9497   }
9498   if (OrigRHS.Conversion) {
9499     Diag(OrigRHS.Conversion->getLocation(),
9500          diag::note_typecheck_invalid_operands_converted)
9501       << 1 << RHS.get()->getType();
9502   }
9503 
9504   return QualType();
9505 }
9506 
9507 // Diagnose cases where a scalar was implicitly converted to a vector and
9508 // diagnose the underlying types. Otherwise, diagnose the error
9509 // as invalid vector logical operands for non-C++ cases.
9510 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9511                                             ExprResult &RHS) {
9512   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9513   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9514 
9515   bool LHSNatVec = LHSType->isVectorType();
9516   bool RHSNatVec = RHSType->isVectorType();
9517 
9518   if (!(LHSNatVec && RHSNatVec)) {
9519     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9520     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9521     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9522         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9523         << Vector->getSourceRange();
9524     return QualType();
9525   }
9526 
9527   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9528       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9529       << RHS.get()->getSourceRange();
9530 
9531   return QualType();
9532 }
9533 
9534 /// Try to convert a value of non-vector type to a vector type by converting
9535 /// the type to the element type of the vector and then performing a splat.
9536 /// If the language is OpenCL, we only use conversions that promote scalar
9537 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9538 /// for float->int.
9539 ///
9540 /// OpenCL V2.0 6.2.6.p2:
9541 /// An error shall occur if any scalar operand type has greater rank
9542 /// than the type of the vector element.
9543 ///
9544 /// \param scalar - if non-null, actually perform the conversions
9545 /// \return true if the operation fails (but without diagnosing the failure)
9546 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9547                                      QualType scalarTy,
9548                                      QualType vectorEltTy,
9549                                      QualType vectorTy,
9550                                      unsigned &DiagID) {
9551   // The conversion to apply to the scalar before splatting it,
9552   // if necessary.
9553   CastKind scalarCast = CK_NoOp;
9554 
9555   if (vectorEltTy->isIntegralType(S.Context)) {
9556     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9557         (scalarTy->isIntegerType() &&
9558          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9559       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9560       return true;
9561     }
9562     if (!scalarTy->isIntegralType(S.Context))
9563       return true;
9564     scalarCast = CK_IntegralCast;
9565   } else if (vectorEltTy->isRealFloatingType()) {
9566     if (scalarTy->isRealFloatingType()) {
9567       if (S.getLangOpts().OpenCL &&
9568           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9569         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9570         return true;
9571       }
9572       scalarCast = CK_FloatingCast;
9573     }
9574     else if (scalarTy->isIntegralType(S.Context))
9575       scalarCast = CK_IntegralToFloating;
9576     else
9577       return true;
9578   } else {
9579     return true;
9580   }
9581 
9582   // Adjust scalar if desired.
9583   if (scalar) {
9584     if (scalarCast != CK_NoOp)
9585       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9586     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9587   }
9588   return false;
9589 }
9590 
9591 /// Convert vector E to a vector with the same number of elements but different
9592 /// element type.
9593 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9594   const auto *VecTy = E->getType()->getAs<VectorType>();
9595   assert(VecTy && "Expression E must be a vector");
9596   QualType NewVecTy = S.Context.getVectorType(ElementType,
9597                                               VecTy->getNumElements(),
9598                                               VecTy->getVectorKind());
9599 
9600   // Look through the implicit cast. Return the subexpression if its type is
9601   // NewVecTy.
9602   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9603     if (ICE->getSubExpr()->getType() == NewVecTy)
9604       return ICE->getSubExpr();
9605 
9606   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9607   return S.ImpCastExprToType(E, NewVecTy, Cast);
9608 }
9609 
9610 /// Test if a (constant) integer Int can be casted to another integer type
9611 /// IntTy without losing precision.
9612 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9613                                       QualType OtherIntTy) {
9614   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9615 
9616   // Reject cases where the value of the Int is unknown as that would
9617   // possibly cause truncation, but accept cases where the scalar can be
9618   // demoted without loss of precision.
9619   Expr::EvalResult EVResult;
9620   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9621   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9622   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9623   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9624 
9625   if (CstInt) {
9626     // If the scalar is constant and is of a higher order and has more active
9627     // bits that the vector element type, reject it.
9628     llvm::APSInt Result = EVResult.Val.getInt();
9629     unsigned NumBits = IntSigned
9630                            ? (Result.isNegative() ? Result.getMinSignedBits()
9631                                                   : Result.getActiveBits())
9632                            : Result.getActiveBits();
9633     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9634       return true;
9635 
9636     // If the signedness of the scalar type and the vector element type
9637     // differs and the number of bits is greater than that of the vector
9638     // element reject it.
9639     return (IntSigned != OtherIntSigned &&
9640             NumBits > S.Context.getIntWidth(OtherIntTy));
9641   }
9642 
9643   // Reject cases where the value of the scalar is not constant and it's
9644   // order is greater than that of the vector element type.
9645   return (Order < 0);
9646 }
9647 
9648 /// Test if a (constant) integer Int can be casted to floating point type
9649 /// FloatTy without losing precision.
9650 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9651                                      QualType FloatTy) {
9652   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9653 
9654   // Determine if the integer constant can be expressed as a floating point
9655   // number of the appropriate type.
9656   Expr::EvalResult EVResult;
9657   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9658 
9659   uint64_t Bits = 0;
9660   if (CstInt) {
9661     // Reject constants that would be truncated if they were converted to
9662     // the floating point type. Test by simple to/from conversion.
9663     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9664     //        could be avoided if there was a convertFromAPInt method
9665     //        which could signal back if implicit truncation occurred.
9666     llvm::APSInt Result = EVResult.Val.getInt();
9667     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9668     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9669                            llvm::APFloat::rmTowardZero);
9670     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9671                              !IntTy->hasSignedIntegerRepresentation());
9672     bool Ignored = false;
9673     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9674                            &Ignored);
9675     if (Result != ConvertBack)
9676       return true;
9677   } else {
9678     // Reject types that cannot be fully encoded into the mantissa of
9679     // the float.
9680     Bits = S.Context.getTypeSize(IntTy);
9681     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9682         S.Context.getFloatTypeSemantics(FloatTy));
9683     if (Bits > FloatPrec)
9684       return true;
9685   }
9686 
9687   return false;
9688 }
9689 
9690 /// Attempt to convert and splat Scalar into a vector whose types matches
9691 /// Vector following GCC conversion rules. The rule is that implicit
9692 /// conversion can occur when Scalar can be casted to match Vector's element
9693 /// type without causing truncation of Scalar.
9694 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9695                                         ExprResult *Vector) {
9696   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9697   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9698   const VectorType *VT = VectorTy->getAs<VectorType>();
9699 
9700   assert(!isa<ExtVectorType>(VT) &&
9701          "ExtVectorTypes should not be handled here!");
9702 
9703   QualType VectorEltTy = VT->getElementType();
9704 
9705   // Reject cases where the vector element type or the scalar element type are
9706   // not integral or floating point types.
9707   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9708     return true;
9709 
9710   // The conversion to apply to the scalar before splatting it,
9711   // if necessary.
9712   CastKind ScalarCast = CK_NoOp;
9713 
9714   // Accept cases where the vector elements are integers and the scalar is
9715   // an integer.
9716   // FIXME: Notionally if the scalar was a floating point value with a precise
9717   //        integral representation, we could cast it to an appropriate integer
9718   //        type and then perform the rest of the checks here. GCC will perform
9719   //        this conversion in some cases as determined by the input language.
9720   //        We should accept it on a language independent basis.
9721   if (VectorEltTy->isIntegralType(S.Context) &&
9722       ScalarTy->isIntegralType(S.Context) &&
9723       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9724 
9725     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9726       return true;
9727 
9728     ScalarCast = CK_IntegralCast;
9729   } else if (VectorEltTy->isIntegralType(S.Context) &&
9730              ScalarTy->isRealFloatingType()) {
9731     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9732       ScalarCast = CK_FloatingToIntegral;
9733     else
9734       return true;
9735   } else if (VectorEltTy->isRealFloatingType()) {
9736     if (ScalarTy->isRealFloatingType()) {
9737 
9738       // Reject cases where the scalar type is not a constant and has a higher
9739       // Order than the vector element type.
9740       llvm::APFloat Result(0.0);
9741 
9742       // Determine whether this is a constant scalar. In the event that the
9743       // value is dependent (and thus cannot be evaluated by the constant
9744       // evaluator), skip the evaluation. This will then diagnose once the
9745       // expression is instantiated.
9746       bool CstScalar = Scalar->get()->isValueDependent() ||
9747                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9748       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9749       if (!CstScalar && Order < 0)
9750         return true;
9751 
9752       // If the scalar cannot be safely casted to the vector element type,
9753       // reject it.
9754       if (CstScalar) {
9755         bool Truncated = false;
9756         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9757                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9758         if (Truncated)
9759           return true;
9760       }
9761 
9762       ScalarCast = CK_FloatingCast;
9763     } else if (ScalarTy->isIntegralType(S.Context)) {
9764       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9765         return true;
9766 
9767       ScalarCast = CK_IntegralToFloating;
9768     } else
9769       return true;
9770   } else if (ScalarTy->isEnumeralType())
9771     return true;
9772 
9773   // Adjust scalar if desired.
9774   if (Scalar) {
9775     if (ScalarCast != CK_NoOp)
9776       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9777     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9778   }
9779   return false;
9780 }
9781 
9782 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9783                                    SourceLocation Loc, bool IsCompAssign,
9784                                    bool AllowBothBool,
9785                                    bool AllowBoolConversions) {
9786   if (!IsCompAssign) {
9787     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9788     if (LHS.isInvalid())
9789       return QualType();
9790   }
9791   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9792   if (RHS.isInvalid())
9793     return QualType();
9794 
9795   // For conversion purposes, we ignore any qualifiers.
9796   // For example, "const float" and "float" are equivalent.
9797   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9798   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9799 
9800   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9801   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9802   assert(LHSVecType || RHSVecType);
9803 
9804   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9805       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9806     return InvalidOperands(Loc, LHS, RHS);
9807 
9808   // AltiVec-style "vector bool op vector bool" combinations are allowed
9809   // for some operators but not others.
9810   if (!AllowBothBool &&
9811       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9812       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9813     return InvalidOperands(Loc, LHS, RHS);
9814 
9815   // If the vector types are identical, return.
9816   if (Context.hasSameType(LHSType, RHSType))
9817     return LHSType;
9818 
9819   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9820   if (LHSVecType && RHSVecType &&
9821       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9822     if (isa<ExtVectorType>(LHSVecType)) {
9823       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9824       return LHSType;
9825     }
9826 
9827     if (!IsCompAssign)
9828       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9829     return RHSType;
9830   }
9831 
9832   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9833   // can be mixed, with the result being the non-bool type.  The non-bool
9834   // operand must have integer element type.
9835   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9836       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9837       (Context.getTypeSize(LHSVecType->getElementType()) ==
9838        Context.getTypeSize(RHSVecType->getElementType()))) {
9839     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9840         LHSVecType->getElementType()->isIntegerType() &&
9841         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9842       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9843       return LHSType;
9844     }
9845     if (!IsCompAssign &&
9846         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9847         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9848         RHSVecType->getElementType()->isIntegerType()) {
9849       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9850       return RHSType;
9851     }
9852   }
9853 
9854   // If there's a vector type and a scalar, try to convert the scalar to
9855   // the vector element type and splat.
9856   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9857   if (!RHSVecType) {
9858     if (isa<ExtVectorType>(LHSVecType)) {
9859       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9860                                     LHSVecType->getElementType(), LHSType,
9861                                     DiagID))
9862         return LHSType;
9863     } else {
9864       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9865         return LHSType;
9866     }
9867   }
9868   if (!LHSVecType) {
9869     if (isa<ExtVectorType>(RHSVecType)) {
9870       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9871                                     LHSType, RHSVecType->getElementType(),
9872                                     RHSType, DiagID))
9873         return RHSType;
9874     } else {
9875       if (LHS.get()->getValueKind() == VK_LValue ||
9876           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9877         return RHSType;
9878     }
9879   }
9880 
9881   // FIXME: The code below also handles conversion between vectors and
9882   // non-scalars, we should break this down into fine grained specific checks
9883   // and emit proper diagnostics.
9884   QualType VecType = LHSVecType ? LHSType : RHSType;
9885   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9886   QualType OtherType = LHSVecType ? RHSType : LHSType;
9887   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9888   if (isLaxVectorConversion(OtherType, VecType)) {
9889     // If we're allowing lax vector conversions, only the total (data) size
9890     // needs to be the same. For non compound assignment, if one of the types is
9891     // scalar, the result is always the vector type.
9892     if (!IsCompAssign) {
9893       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9894       return VecType;
9895     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9896     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9897     // type. Note that this is already done by non-compound assignments in
9898     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9899     // <1 x T> -> T. The result is also a vector type.
9900     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9901                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9902       ExprResult *RHSExpr = &RHS;
9903       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9904       return VecType;
9905     }
9906   }
9907 
9908   // Okay, the expression is invalid.
9909 
9910   // Returns true if the operands are SVE VLA and VLS types.
9911   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9912     const VectorType *VecType = SecondType->getAs<VectorType>();
9913     return FirstType->isSizelessBuiltinType() && VecType &&
9914            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9915             VecType->getVectorKind() ==
9916                 VectorType::SveFixedLengthPredicateVector);
9917   };
9918 
9919   // If there's a sizeless and fixed-length operand, diagnose that.
9920   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9921     Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless)
9922         << LHSType << RHSType;
9923     return QualType();
9924   }
9925 
9926   // If there's a non-vector, non-real operand, diagnose that.
9927   if ((!RHSVecType && !RHSType->isRealType()) ||
9928       (!LHSVecType && !LHSType->isRealType())) {
9929     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9930       << LHSType << RHSType
9931       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9932     return QualType();
9933   }
9934 
9935   // OpenCL V1.1 6.2.6.p1:
9936   // If the operands are of more than one vector type, then an error shall
9937   // occur. Implicit conversions between vector types are not permitted, per
9938   // section 6.2.1.
9939   if (getLangOpts().OpenCL &&
9940       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9941       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9942     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9943                                                            << RHSType;
9944     return QualType();
9945   }
9946 
9947 
9948   // If there is a vector type that is not a ExtVector and a scalar, we reach
9949   // this point if scalar could not be converted to the vector's element type
9950   // without truncation.
9951   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9952       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9953     QualType Scalar = LHSVecType ? RHSType : LHSType;
9954     QualType Vector = LHSVecType ? LHSType : RHSType;
9955     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9956     Diag(Loc,
9957          diag::err_typecheck_vector_not_convertable_implict_truncation)
9958         << ScalarOrVector << Scalar << Vector;
9959 
9960     return QualType();
9961   }
9962 
9963   // Otherwise, use the generic diagnostic.
9964   Diag(Loc, DiagID)
9965     << LHSType << RHSType
9966     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9967   return QualType();
9968 }
9969 
9970 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9971 // expression.  These are mainly cases where the null pointer is used as an
9972 // integer instead of a pointer.
9973 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9974                                 SourceLocation Loc, bool IsCompare) {
9975   // The canonical way to check for a GNU null is with isNullPointerConstant,
9976   // but we use a bit of a hack here for speed; this is a relatively
9977   // hot path, and isNullPointerConstant is slow.
9978   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9979   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9980 
9981   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9982 
9983   // Avoid analyzing cases where the result will either be invalid (and
9984   // diagnosed as such) or entirely valid and not something to warn about.
9985   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9986       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9987     return;
9988 
9989   // Comparison operations would not make sense with a null pointer no matter
9990   // what the other expression is.
9991   if (!IsCompare) {
9992     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9993         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9994         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9995     return;
9996   }
9997 
9998   // The rest of the operations only make sense with a null pointer
9999   // if the other expression is a pointer.
10000   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10001       NonNullType->canDecayToPointerType())
10002     return;
10003 
10004   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10005       << LHSNull /* LHS is NULL */ << NonNullType
10006       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10007 }
10008 
10009 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10010                                           SourceLocation Loc) {
10011   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10012   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10013   if (!LUE || !RUE)
10014     return;
10015   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10016       RUE->getKind() != UETT_SizeOf)
10017     return;
10018 
10019   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10020   QualType LHSTy = LHSArg->getType();
10021   QualType RHSTy;
10022 
10023   if (RUE->isArgumentType())
10024     RHSTy = RUE->getArgumentType();
10025   else
10026     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10027 
10028   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10029     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10030       return;
10031 
10032     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10033     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10034       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10035         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10036             << LHSArgDecl;
10037     }
10038   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10039     QualType ArrayElemTy = ArrayTy->getElementType();
10040     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10041         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10042         ArrayElemTy->isCharType() ||
10043         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10044       return;
10045     S.Diag(Loc, diag::warn_division_sizeof_array)
10046         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10047     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10048       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10049         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10050             << LHSArgDecl;
10051     }
10052 
10053     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10054   }
10055 }
10056 
10057 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10058                                                ExprResult &RHS,
10059                                                SourceLocation Loc, bool IsDiv) {
10060   // Check for division/remainder by zero.
10061   Expr::EvalResult RHSValue;
10062   if (!RHS.get()->isValueDependent() &&
10063       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10064       RHSValue.Val.getInt() == 0)
10065     S.DiagRuntimeBehavior(Loc, RHS.get(),
10066                           S.PDiag(diag::warn_remainder_division_by_zero)
10067                             << IsDiv << RHS.get()->getSourceRange());
10068 }
10069 
10070 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10071                                            SourceLocation Loc,
10072                                            bool IsCompAssign, bool IsDiv) {
10073   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10074 
10075   if (LHS.get()->getType()->isVectorType() ||
10076       RHS.get()->getType()->isVectorType())
10077     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10078                                /*AllowBothBool*/getLangOpts().AltiVec,
10079                                /*AllowBoolConversions*/false);
10080   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10081                  RHS.get()->getType()->isConstantMatrixType()))
10082     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10083 
10084   QualType compType = UsualArithmeticConversions(
10085       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10086   if (LHS.isInvalid() || RHS.isInvalid())
10087     return QualType();
10088 
10089 
10090   if (compType.isNull() || !compType->isArithmeticType())
10091     return InvalidOperands(Loc, LHS, RHS);
10092   if (IsDiv) {
10093     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10094     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10095   }
10096   return compType;
10097 }
10098 
10099 QualType Sema::CheckRemainderOperands(
10100   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10101   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10102 
10103   if (LHS.get()->getType()->isVectorType() ||
10104       RHS.get()->getType()->isVectorType()) {
10105     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10106         RHS.get()->getType()->hasIntegerRepresentation())
10107       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10108                                  /*AllowBothBool*/getLangOpts().AltiVec,
10109                                  /*AllowBoolConversions*/false);
10110     return InvalidOperands(Loc, LHS, RHS);
10111   }
10112 
10113   QualType compType = UsualArithmeticConversions(
10114       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10115   if (LHS.isInvalid() || RHS.isInvalid())
10116     return QualType();
10117 
10118   if (compType.isNull() || !compType->isIntegerType())
10119     return InvalidOperands(Loc, LHS, RHS);
10120   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10121   return compType;
10122 }
10123 
10124 /// Diagnose invalid arithmetic on two void pointers.
10125 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10126                                                 Expr *LHSExpr, Expr *RHSExpr) {
10127   S.Diag(Loc, S.getLangOpts().CPlusPlus
10128                 ? diag::err_typecheck_pointer_arith_void_type
10129                 : diag::ext_gnu_void_ptr)
10130     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10131                             << RHSExpr->getSourceRange();
10132 }
10133 
10134 /// Diagnose invalid arithmetic on a void pointer.
10135 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10136                                             Expr *Pointer) {
10137   S.Diag(Loc, S.getLangOpts().CPlusPlus
10138                 ? diag::err_typecheck_pointer_arith_void_type
10139                 : diag::ext_gnu_void_ptr)
10140     << 0 /* one pointer */ << Pointer->getSourceRange();
10141 }
10142 
10143 /// Diagnose invalid arithmetic on a null pointer.
10144 ///
10145 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10146 /// idiom, which we recognize as a GNU extension.
10147 ///
10148 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10149                                             Expr *Pointer, bool IsGNUIdiom) {
10150   if (IsGNUIdiom)
10151     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10152       << Pointer->getSourceRange();
10153   else
10154     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10155       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10156 }
10157 
10158 /// Diagnose invalid arithmetic on two function pointers.
10159 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10160                                                     Expr *LHS, Expr *RHS) {
10161   assert(LHS->getType()->isAnyPointerType());
10162   assert(RHS->getType()->isAnyPointerType());
10163   S.Diag(Loc, S.getLangOpts().CPlusPlus
10164                 ? diag::err_typecheck_pointer_arith_function_type
10165                 : diag::ext_gnu_ptr_func_arith)
10166     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10167     // We only show the second type if it differs from the first.
10168     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10169                                                    RHS->getType())
10170     << RHS->getType()->getPointeeType()
10171     << LHS->getSourceRange() << RHS->getSourceRange();
10172 }
10173 
10174 /// Diagnose invalid arithmetic on a function pointer.
10175 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10176                                                 Expr *Pointer) {
10177   assert(Pointer->getType()->isAnyPointerType());
10178   S.Diag(Loc, S.getLangOpts().CPlusPlus
10179                 ? diag::err_typecheck_pointer_arith_function_type
10180                 : diag::ext_gnu_ptr_func_arith)
10181     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10182     << 0 /* one pointer, so only one type */
10183     << Pointer->getSourceRange();
10184 }
10185 
10186 /// Emit error if Operand is incomplete pointer type
10187 ///
10188 /// \returns True if pointer has incomplete type
10189 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10190                                                  Expr *Operand) {
10191   QualType ResType = Operand->getType();
10192   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10193     ResType = ResAtomicType->getValueType();
10194 
10195   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10196   QualType PointeeTy = ResType->getPointeeType();
10197   return S.RequireCompleteSizedType(
10198       Loc, PointeeTy,
10199       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10200       Operand->getSourceRange());
10201 }
10202 
10203 /// Check the validity of an arithmetic pointer operand.
10204 ///
10205 /// If the operand has pointer type, this code will check for pointer types
10206 /// which are invalid in arithmetic operations. These will be diagnosed
10207 /// appropriately, including whether or not the use is supported as an
10208 /// extension.
10209 ///
10210 /// \returns True when the operand is valid to use (even if as an extension).
10211 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10212                                             Expr *Operand) {
10213   QualType ResType = Operand->getType();
10214   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10215     ResType = ResAtomicType->getValueType();
10216 
10217   if (!ResType->isAnyPointerType()) return true;
10218 
10219   QualType PointeeTy = ResType->getPointeeType();
10220   if (PointeeTy->isVoidType()) {
10221     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10222     return !S.getLangOpts().CPlusPlus;
10223   }
10224   if (PointeeTy->isFunctionType()) {
10225     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10226     return !S.getLangOpts().CPlusPlus;
10227   }
10228 
10229   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10230 
10231   return true;
10232 }
10233 
10234 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10235 /// operands.
10236 ///
10237 /// This routine will diagnose any invalid arithmetic on pointer operands much
10238 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10239 /// for emitting a single diagnostic even for operations where both LHS and RHS
10240 /// are (potentially problematic) pointers.
10241 ///
10242 /// \returns True when the operand is valid to use (even if as an extension).
10243 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10244                                                 Expr *LHSExpr, Expr *RHSExpr) {
10245   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10246   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10247   if (!isLHSPointer && !isRHSPointer) return true;
10248 
10249   QualType LHSPointeeTy, RHSPointeeTy;
10250   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10251   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10252 
10253   // if both are pointers check if operation is valid wrt address spaces
10254   if (isLHSPointer && isRHSPointer) {
10255     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10256       S.Diag(Loc,
10257              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10258           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10259           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10260       return false;
10261     }
10262   }
10263 
10264   // Check for arithmetic on pointers to incomplete types.
10265   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10266   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10267   if (isLHSVoidPtr || isRHSVoidPtr) {
10268     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10269     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10270     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10271 
10272     return !S.getLangOpts().CPlusPlus;
10273   }
10274 
10275   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10276   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10277   if (isLHSFuncPtr || isRHSFuncPtr) {
10278     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10279     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10280                                                                 RHSExpr);
10281     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10282 
10283     return !S.getLangOpts().CPlusPlus;
10284   }
10285 
10286   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10287     return false;
10288   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10289     return false;
10290 
10291   return true;
10292 }
10293 
10294 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10295 /// literal.
10296 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10297                                   Expr *LHSExpr, Expr *RHSExpr) {
10298   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10299   Expr* IndexExpr = RHSExpr;
10300   if (!StrExpr) {
10301     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10302     IndexExpr = LHSExpr;
10303   }
10304 
10305   bool IsStringPlusInt = StrExpr &&
10306       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10307   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10308     return;
10309 
10310   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10311   Self.Diag(OpLoc, diag::warn_string_plus_int)
10312       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10313 
10314   // Only print a fixit for "str" + int, not for int + "str".
10315   if (IndexExpr == RHSExpr) {
10316     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10317     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10318         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10319         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10320         << FixItHint::CreateInsertion(EndLoc, "]");
10321   } else
10322     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10323 }
10324 
10325 /// Emit a warning when adding a char literal to a string.
10326 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10327                                    Expr *LHSExpr, Expr *RHSExpr) {
10328   const Expr *StringRefExpr = LHSExpr;
10329   const CharacterLiteral *CharExpr =
10330       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10331 
10332   if (!CharExpr) {
10333     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10334     StringRefExpr = RHSExpr;
10335   }
10336 
10337   if (!CharExpr || !StringRefExpr)
10338     return;
10339 
10340   const QualType StringType = StringRefExpr->getType();
10341 
10342   // Return if not a PointerType.
10343   if (!StringType->isAnyPointerType())
10344     return;
10345 
10346   // Return if not a CharacterType.
10347   if (!StringType->getPointeeType()->isAnyCharacterType())
10348     return;
10349 
10350   ASTContext &Ctx = Self.getASTContext();
10351   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10352 
10353   const QualType CharType = CharExpr->getType();
10354   if (!CharType->isAnyCharacterType() &&
10355       CharType->isIntegerType() &&
10356       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10357     Self.Diag(OpLoc, diag::warn_string_plus_char)
10358         << DiagRange << Ctx.CharTy;
10359   } else {
10360     Self.Diag(OpLoc, diag::warn_string_plus_char)
10361         << DiagRange << CharExpr->getType();
10362   }
10363 
10364   // Only print a fixit for str + char, not for char + str.
10365   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10366     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10367     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10368         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10369         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10370         << FixItHint::CreateInsertion(EndLoc, "]");
10371   } else {
10372     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10373   }
10374 }
10375 
10376 /// Emit error when two pointers are incompatible.
10377 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10378                                            Expr *LHSExpr, Expr *RHSExpr) {
10379   assert(LHSExpr->getType()->isAnyPointerType());
10380   assert(RHSExpr->getType()->isAnyPointerType());
10381   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10382     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10383     << RHSExpr->getSourceRange();
10384 }
10385 
10386 // C99 6.5.6
10387 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10388                                      SourceLocation Loc, BinaryOperatorKind Opc,
10389                                      QualType* CompLHSTy) {
10390   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10391 
10392   if (LHS.get()->getType()->isVectorType() ||
10393       RHS.get()->getType()->isVectorType()) {
10394     QualType compType = CheckVectorOperands(
10395         LHS, RHS, Loc, CompLHSTy,
10396         /*AllowBothBool*/getLangOpts().AltiVec,
10397         /*AllowBoolConversions*/getLangOpts().ZVector);
10398     if (CompLHSTy) *CompLHSTy = compType;
10399     return compType;
10400   }
10401 
10402   if (LHS.get()->getType()->isConstantMatrixType() ||
10403       RHS.get()->getType()->isConstantMatrixType()) {
10404     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10405   }
10406 
10407   QualType compType = UsualArithmeticConversions(
10408       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10409   if (LHS.isInvalid() || RHS.isInvalid())
10410     return QualType();
10411 
10412   // Diagnose "string literal" '+' int and string '+' "char literal".
10413   if (Opc == BO_Add) {
10414     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10415     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10416   }
10417 
10418   // handle the common case first (both operands are arithmetic).
10419   if (!compType.isNull() && compType->isArithmeticType()) {
10420     if (CompLHSTy) *CompLHSTy = compType;
10421     return compType;
10422   }
10423 
10424   // Type-checking.  Ultimately the pointer's going to be in PExp;
10425   // note that we bias towards the LHS being the pointer.
10426   Expr *PExp = LHS.get(), *IExp = RHS.get();
10427 
10428   bool isObjCPointer;
10429   if (PExp->getType()->isPointerType()) {
10430     isObjCPointer = false;
10431   } else if (PExp->getType()->isObjCObjectPointerType()) {
10432     isObjCPointer = true;
10433   } else {
10434     std::swap(PExp, IExp);
10435     if (PExp->getType()->isPointerType()) {
10436       isObjCPointer = false;
10437     } else if (PExp->getType()->isObjCObjectPointerType()) {
10438       isObjCPointer = true;
10439     } else {
10440       return InvalidOperands(Loc, LHS, RHS);
10441     }
10442   }
10443   assert(PExp->getType()->isAnyPointerType());
10444 
10445   if (!IExp->getType()->isIntegerType())
10446     return InvalidOperands(Loc, LHS, RHS);
10447 
10448   // Adding to a null pointer results in undefined behavior.
10449   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10450           Context, Expr::NPC_ValueDependentIsNotNull)) {
10451     // In C++ adding zero to a null pointer is defined.
10452     Expr::EvalResult KnownVal;
10453     if (!getLangOpts().CPlusPlus ||
10454         (!IExp->isValueDependent() &&
10455          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10456           KnownVal.Val.getInt() != 0))) {
10457       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10458       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10459           Context, BO_Add, PExp, IExp);
10460       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10461     }
10462   }
10463 
10464   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10465     return QualType();
10466 
10467   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10468     return QualType();
10469 
10470   // Check array bounds for pointer arithemtic
10471   CheckArrayAccess(PExp, IExp);
10472 
10473   if (CompLHSTy) {
10474     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10475     if (LHSTy.isNull()) {
10476       LHSTy = LHS.get()->getType();
10477       if (LHSTy->isPromotableIntegerType())
10478         LHSTy = Context.getPromotedIntegerType(LHSTy);
10479     }
10480     *CompLHSTy = LHSTy;
10481   }
10482 
10483   return PExp->getType();
10484 }
10485 
10486 // C99 6.5.6
10487 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10488                                         SourceLocation Loc,
10489                                         QualType* CompLHSTy) {
10490   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10491 
10492   if (LHS.get()->getType()->isVectorType() ||
10493       RHS.get()->getType()->isVectorType()) {
10494     QualType compType = CheckVectorOperands(
10495         LHS, RHS, Loc, CompLHSTy,
10496         /*AllowBothBool*/getLangOpts().AltiVec,
10497         /*AllowBoolConversions*/getLangOpts().ZVector);
10498     if (CompLHSTy) *CompLHSTy = compType;
10499     return compType;
10500   }
10501 
10502   if (LHS.get()->getType()->isConstantMatrixType() ||
10503       RHS.get()->getType()->isConstantMatrixType()) {
10504     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10505   }
10506 
10507   QualType compType = UsualArithmeticConversions(
10508       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10509   if (LHS.isInvalid() || RHS.isInvalid())
10510     return QualType();
10511 
10512   // Enforce type constraints: C99 6.5.6p3.
10513 
10514   // Handle the common case first (both operands are arithmetic).
10515   if (!compType.isNull() && compType->isArithmeticType()) {
10516     if (CompLHSTy) *CompLHSTy = compType;
10517     return compType;
10518   }
10519 
10520   // Either ptr - int   or   ptr - ptr.
10521   if (LHS.get()->getType()->isAnyPointerType()) {
10522     QualType lpointee = LHS.get()->getType()->getPointeeType();
10523 
10524     // Diagnose bad cases where we step over interface counts.
10525     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10526         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10527       return QualType();
10528 
10529     // The result type of a pointer-int computation is the pointer type.
10530     if (RHS.get()->getType()->isIntegerType()) {
10531       // Subtracting from a null pointer should produce a warning.
10532       // The last argument to the diagnose call says this doesn't match the
10533       // GNU int-to-pointer idiom.
10534       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10535                                            Expr::NPC_ValueDependentIsNotNull)) {
10536         // In C++ adding zero to a null pointer is defined.
10537         Expr::EvalResult KnownVal;
10538         if (!getLangOpts().CPlusPlus ||
10539             (!RHS.get()->isValueDependent() &&
10540              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10541               KnownVal.Val.getInt() != 0))) {
10542           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10543         }
10544       }
10545 
10546       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10547         return QualType();
10548 
10549       // Check array bounds for pointer arithemtic
10550       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10551                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10552 
10553       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10554       return LHS.get()->getType();
10555     }
10556 
10557     // Handle pointer-pointer subtractions.
10558     if (const PointerType *RHSPTy
10559           = RHS.get()->getType()->getAs<PointerType>()) {
10560       QualType rpointee = RHSPTy->getPointeeType();
10561 
10562       if (getLangOpts().CPlusPlus) {
10563         // Pointee types must be the same: C++ [expr.add]
10564         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10565           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10566         }
10567       } else {
10568         // Pointee types must be compatible C99 6.5.6p3
10569         if (!Context.typesAreCompatible(
10570                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10571                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10572           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10573           return QualType();
10574         }
10575       }
10576 
10577       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10578                                                LHS.get(), RHS.get()))
10579         return QualType();
10580 
10581       // FIXME: Add warnings for nullptr - ptr.
10582 
10583       // The pointee type may have zero size.  As an extension, a structure or
10584       // union may have zero size or an array may have zero length.  In this
10585       // case subtraction does not make sense.
10586       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10587         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10588         if (ElementSize.isZero()) {
10589           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10590             << rpointee.getUnqualifiedType()
10591             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10592         }
10593       }
10594 
10595       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10596       return Context.getPointerDiffType();
10597     }
10598   }
10599 
10600   return InvalidOperands(Loc, LHS, RHS);
10601 }
10602 
10603 static bool isScopedEnumerationType(QualType T) {
10604   if (const EnumType *ET = T->getAs<EnumType>())
10605     return ET->getDecl()->isScoped();
10606   return false;
10607 }
10608 
10609 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10610                                    SourceLocation Loc, BinaryOperatorKind Opc,
10611                                    QualType LHSType) {
10612   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10613   // so skip remaining warnings as we don't want to modify values within Sema.
10614   if (S.getLangOpts().OpenCL)
10615     return;
10616 
10617   // Check right/shifter operand
10618   Expr::EvalResult RHSResult;
10619   if (RHS.get()->isValueDependent() ||
10620       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10621     return;
10622   llvm::APSInt Right = RHSResult.Val.getInt();
10623 
10624   if (Right.isNegative()) {
10625     S.DiagRuntimeBehavior(Loc, RHS.get(),
10626                           S.PDiag(diag::warn_shift_negative)
10627                             << RHS.get()->getSourceRange());
10628     return;
10629   }
10630 
10631   QualType LHSExprType = LHS.get()->getType();
10632   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10633   if (LHSExprType->isExtIntType())
10634     LeftSize = S.Context.getIntWidth(LHSExprType);
10635   else if (LHSExprType->isFixedPointType()) {
10636     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10637     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10638   }
10639   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10640   if (Right.uge(LeftBits)) {
10641     S.DiagRuntimeBehavior(Loc, RHS.get(),
10642                           S.PDiag(diag::warn_shift_gt_typewidth)
10643                             << RHS.get()->getSourceRange());
10644     return;
10645   }
10646 
10647   // FIXME: We probably need to handle fixed point types specially here.
10648   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10649     return;
10650 
10651   // When left shifting an ICE which is signed, we can check for overflow which
10652   // according to C++ standards prior to C++2a has undefined behavior
10653   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10654   // more than the maximum value representable in the result type, so never
10655   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10656   // expression is still probably a bug.)
10657   Expr::EvalResult LHSResult;
10658   if (LHS.get()->isValueDependent() ||
10659       LHSType->hasUnsignedIntegerRepresentation() ||
10660       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10661     return;
10662   llvm::APSInt Left = LHSResult.Val.getInt();
10663 
10664   // If LHS does not have a signed type and non-negative value
10665   // then, the behavior is undefined before C++2a. Warn about it.
10666   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10667       !S.getLangOpts().CPlusPlus20) {
10668     S.DiagRuntimeBehavior(Loc, LHS.get(),
10669                           S.PDiag(diag::warn_shift_lhs_negative)
10670                             << LHS.get()->getSourceRange());
10671     return;
10672   }
10673 
10674   llvm::APInt ResultBits =
10675       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10676   if (LeftBits.uge(ResultBits))
10677     return;
10678   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10679   Result = Result.shl(Right);
10680 
10681   // Print the bit representation of the signed integer as an unsigned
10682   // hexadecimal number.
10683   SmallString<40> HexResult;
10684   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10685 
10686   // If we are only missing a sign bit, this is less likely to result in actual
10687   // bugs -- if the result is cast back to an unsigned type, it will have the
10688   // expected value. Thus we place this behind a different warning that can be
10689   // turned off separately if needed.
10690   if (LeftBits == ResultBits - 1) {
10691     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10692         << HexResult << LHSType
10693         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10694     return;
10695   }
10696 
10697   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10698     << HexResult.str() << Result.getMinSignedBits() << LHSType
10699     << Left.getBitWidth() << LHS.get()->getSourceRange()
10700     << RHS.get()->getSourceRange();
10701 }
10702 
10703 /// Return the resulting type when a vector is shifted
10704 ///        by a scalar or vector shift amount.
10705 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10706                                  SourceLocation Loc, bool IsCompAssign) {
10707   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10708   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10709       !LHS.get()->getType()->isVectorType()) {
10710     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10711       << RHS.get()->getType() << LHS.get()->getType()
10712       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10713     return QualType();
10714   }
10715 
10716   if (!IsCompAssign) {
10717     LHS = S.UsualUnaryConversions(LHS.get());
10718     if (LHS.isInvalid()) return QualType();
10719   }
10720 
10721   RHS = S.UsualUnaryConversions(RHS.get());
10722   if (RHS.isInvalid()) return QualType();
10723 
10724   QualType LHSType = LHS.get()->getType();
10725   // Note that LHS might be a scalar because the routine calls not only in
10726   // OpenCL case.
10727   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10728   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10729 
10730   // Note that RHS might not be a vector.
10731   QualType RHSType = RHS.get()->getType();
10732   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10733   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10734 
10735   // The operands need to be integers.
10736   if (!LHSEleType->isIntegerType()) {
10737     S.Diag(Loc, diag::err_typecheck_expect_int)
10738       << LHS.get()->getType() << LHS.get()->getSourceRange();
10739     return QualType();
10740   }
10741 
10742   if (!RHSEleType->isIntegerType()) {
10743     S.Diag(Loc, diag::err_typecheck_expect_int)
10744       << RHS.get()->getType() << RHS.get()->getSourceRange();
10745     return QualType();
10746   }
10747 
10748   if (!LHSVecTy) {
10749     assert(RHSVecTy);
10750     if (IsCompAssign)
10751       return RHSType;
10752     if (LHSEleType != RHSEleType) {
10753       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10754       LHSEleType = RHSEleType;
10755     }
10756     QualType VecTy =
10757         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10758     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10759     LHSType = VecTy;
10760   } else if (RHSVecTy) {
10761     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10762     // are applied component-wise. So if RHS is a vector, then ensure
10763     // that the number of elements is the same as LHS...
10764     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10765       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10766         << LHS.get()->getType() << RHS.get()->getType()
10767         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10768       return QualType();
10769     }
10770     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10771       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10772       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10773       if (LHSBT != RHSBT &&
10774           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10775         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10776             << LHS.get()->getType() << RHS.get()->getType()
10777             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10778       }
10779     }
10780   } else {
10781     // ...else expand RHS to match the number of elements in LHS.
10782     QualType VecTy =
10783       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10784     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10785   }
10786 
10787   return LHSType;
10788 }
10789 
10790 // C99 6.5.7
10791 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10792                                   SourceLocation Loc, BinaryOperatorKind Opc,
10793                                   bool IsCompAssign) {
10794   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10795 
10796   // Vector shifts promote their scalar inputs to vector type.
10797   if (LHS.get()->getType()->isVectorType() ||
10798       RHS.get()->getType()->isVectorType()) {
10799     if (LangOpts.ZVector) {
10800       // The shift operators for the z vector extensions work basically
10801       // like general shifts, except that neither the LHS nor the RHS is
10802       // allowed to be a "vector bool".
10803       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10804         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10805           return InvalidOperands(Loc, LHS, RHS);
10806       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10807         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10808           return InvalidOperands(Loc, LHS, RHS);
10809     }
10810     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10811   }
10812 
10813   // Shifts don't perform usual arithmetic conversions, they just do integer
10814   // promotions on each operand. C99 6.5.7p3
10815 
10816   // For the LHS, do usual unary conversions, but then reset them away
10817   // if this is a compound assignment.
10818   ExprResult OldLHS = LHS;
10819   LHS = UsualUnaryConversions(LHS.get());
10820   if (LHS.isInvalid())
10821     return QualType();
10822   QualType LHSType = LHS.get()->getType();
10823   if (IsCompAssign) LHS = OldLHS;
10824 
10825   // The RHS is simpler.
10826   RHS = UsualUnaryConversions(RHS.get());
10827   if (RHS.isInvalid())
10828     return QualType();
10829   QualType RHSType = RHS.get()->getType();
10830 
10831   // C99 6.5.7p2: Each of the operands shall have integer type.
10832   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10833   if ((!LHSType->isFixedPointOrIntegerType() &&
10834        !LHSType->hasIntegerRepresentation()) ||
10835       !RHSType->hasIntegerRepresentation())
10836     return InvalidOperands(Loc, LHS, RHS);
10837 
10838   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10839   // hasIntegerRepresentation() above instead of this.
10840   if (isScopedEnumerationType(LHSType) ||
10841       isScopedEnumerationType(RHSType)) {
10842     return InvalidOperands(Loc, LHS, RHS);
10843   }
10844   // Sanity-check shift operands
10845   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10846 
10847   // "The type of the result is that of the promoted left operand."
10848   return LHSType;
10849 }
10850 
10851 /// Diagnose bad pointer comparisons.
10852 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10853                                               ExprResult &LHS, ExprResult &RHS,
10854                                               bool IsError) {
10855   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10856                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10857     << LHS.get()->getType() << RHS.get()->getType()
10858     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10859 }
10860 
10861 /// Returns false if the pointers are converted to a composite type,
10862 /// true otherwise.
10863 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10864                                            ExprResult &LHS, ExprResult &RHS) {
10865   // C++ [expr.rel]p2:
10866   //   [...] Pointer conversions (4.10) and qualification
10867   //   conversions (4.4) are performed on pointer operands (or on
10868   //   a pointer operand and a null pointer constant) to bring
10869   //   them to their composite pointer type. [...]
10870   //
10871   // C++ [expr.eq]p1 uses the same notion for (in)equality
10872   // comparisons of pointers.
10873 
10874   QualType LHSType = LHS.get()->getType();
10875   QualType RHSType = RHS.get()->getType();
10876   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10877          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10878 
10879   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10880   if (T.isNull()) {
10881     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10882         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10883       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10884     else
10885       S.InvalidOperands(Loc, LHS, RHS);
10886     return true;
10887   }
10888 
10889   return false;
10890 }
10891 
10892 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10893                                                     ExprResult &LHS,
10894                                                     ExprResult &RHS,
10895                                                     bool IsError) {
10896   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10897                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10898     << LHS.get()->getType() << RHS.get()->getType()
10899     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10900 }
10901 
10902 static bool isObjCObjectLiteral(ExprResult &E) {
10903   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10904   case Stmt::ObjCArrayLiteralClass:
10905   case Stmt::ObjCDictionaryLiteralClass:
10906   case Stmt::ObjCStringLiteralClass:
10907   case Stmt::ObjCBoxedExprClass:
10908     return true;
10909   default:
10910     // Note that ObjCBoolLiteral is NOT an object literal!
10911     return false;
10912   }
10913 }
10914 
10915 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10916   const ObjCObjectPointerType *Type =
10917     LHS->getType()->getAs<ObjCObjectPointerType>();
10918 
10919   // If this is not actually an Objective-C object, bail out.
10920   if (!Type)
10921     return false;
10922 
10923   // Get the LHS object's interface type.
10924   QualType InterfaceType = Type->getPointeeType();
10925 
10926   // If the RHS isn't an Objective-C object, bail out.
10927   if (!RHS->getType()->isObjCObjectPointerType())
10928     return false;
10929 
10930   // Try to find the -isEqual: method.
10931   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10932   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10933                                                       InterfaceType,
10934                                                       /*IsInstance=*/true);
10935   if (!Method) {
10936     if (Type->isObjCIdType()) {
10937       // For 'id', just check the global pool.
10938       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10939                                                   /*receiverId=*/true);
10940     } else {
10941       // Check protocols.
10942       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10943                                              /*IsInstance=*/true);
10944     }
10945   }
10946 
10947   if (!Method)
10948     return false;
10949 
10950   QualType T = Method->parameters()[0]->getType();
10951   if (!T->isObjCObjectPointerType())
10952     return false;
10953 
10954   QualType R = Method->getReturnType();
10955   if (!R->isScalarType())
10956     return false;
10957 
10958   return true;
10959 }
10960 
10961 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10962   FromE = FromE->IgnoreParenImpCasts();
10963   switch (FromE->getStmtClass()) {
10964     default:
10965       break;
10966     case Stmt::ObjCStringLiteralClass:
10967       // "string literal"
10968       return LK_String;
10969     case Stmt::ObjCArrayLiteralClass:
10970       // "array literal"
10971       return LK_Array;
10972     case Stmt::ObjCDictionaryLiteralClass:
10973       // "dictionary literal"
10974       return LK_Dictionary;
10975     case Stmt::BlockExprClass:
10976       return LK_Block;
10977     case Stmt::ObjCBoxedExprClass: {
10978       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10979       switch (Inner->getStmtClass()) {
10980         case Stmt::IntegerLiteralClass:
10981         case Stmt::FloatingLiteralClass:
10982         case Stmt::CharacterLiteralClass:
10983         case Stmt::ObjCBoolLiteralExprClass:
10984         case Stmt::CXXBoolLiteralExprClass:
10985           // "numeric literal"
10986           return LK_Numeric;
10987         case Stmt::ImplicitCastExprClass: {
10988           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10989           // Boolean literals can be represented by implicit casts.
10990           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10991             return LK_Numeric;
10992           break;
10993         }
10994         default:
10995           break;
10996       }
10997       return LK_Boxed;
10998     }
10999   }
11000   return LK_None;
11001 }
11002 
11003 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11004                                           ExprResult &LHS, ExprResult &RHS,
11005                                           BinaryOperator::Opcode Opc){
11006   Expr *Literal;
11007   Expr *Other;
11008   if (isObjCObjectLiteral(LHS)) {
11009     Literal = LHS.get();
11010     Other = RHS.get();
11011   } else {
11012     Literal = RHS.get();
11013     Other = LHS.get();
11014   }
11015 
11016   // Don't warn on comparisons against nil.
11017   Other = Other->IgnoreParenCasts();
11018   if (Other->isNullPointerConstant(S.getASTContext(),
11019                                    Expr::NPC_ValueDependentIsNotNull))
11020     return;
11021 
11022   // This should be kept in sync with warn_objc_literal_comparison.
11023   // LK_String should always be after the other literals, since it has its own
11024   // warning flag.
11025   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11026   assert(LiteralKind != Sema::LK_Block);
11027   if (LiteralKind == Sema::LK_None) {
11028     llvm_unreachable("Unknown Objective-C object literal kind");
11029   }
11030 
11031   if (LiteralKind == Sema::LK_String)
11032     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11033       << Literal->getSourceRange();
11034   else
11035     S.Diag(Loc, diag::warn_objc_literal_comparison)
11036       << LiteralKind << Literal->getSourceRange();
11037 
11038   if (BinaryOperator::isEqualityOp(Opc) &&
11039       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11040     SourceLocation Start = LHS.get()->getBeginLoc();
11041     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11042     CharSourceRange OpRange =
11043       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11044 
11045     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11046       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11047       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11048       << FixItHint::CreateInsertion(End, "]");
11049   }
11050 }
11051 
11052 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11053 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11054                                            ExprResult &RHS, SourceLocation Loc,
11055                                            BinaryOperatorKind Opc) {
11056   // Check that left hand side is !something.
11057   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11058   if (!UO || UO->getOpcode() != UO_LNot) return;
11059 
11060   // Only check if the right hand side is non-bool arithmetic type.
11061   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11062 
11063   // Make sure that the something in !something is not bool.
11064   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11065   if (SubExpr->isKnownToHaveBooleanValue()) return;
11066 
11067   // Emit warning.
11068   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11069   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11070       << Loc << IsBitwiseOp;
11071 
11072   // First note suggest !(x < y)
11073   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11074   SourceLocation FirstClose = RHS.get()->getEndLoc();
11075   FirstClose = S.getLocForEndOfToken(FirstClose);
11076   if (FirstClose.isInvalid())
11077     FirstOpen = SourceLocation();
11078   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11079       << IsBitwiseOp
11080       << FixItHint::CreateInsertion(FirstOpen, "(")
11081       << FixItHint::CreateInsertion(FirstClose, ")");
11082 
11083   // Second note suggests (!x) < y
11084   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11085   SourceLocation SecondClose = LHS.get()->getEndLoc();
11086   SecondClose = S.getLocForEndOfToken(SecondClose);
11087   if (SecondClose.isInvalid())
11088     SecondOpen = SourceLocation();
11089   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11090       << FixItHint::CreateInsertion(SecondOpen, "(")
11091       << FixItHint::CreateInsertion(SecondClose, ")");
11092 }
11093 
11094 // Returns true if E refers to a non-weak array.
11095 static bool checkForArray(const Expr *E) {
11096   const ValueDecl *D = nullptr;
11097   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11098     D = DR->getDecl();
11099   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11100     if (Mem->isImplicitAccess())
11101       D = Mem->getMemberDecl();
11102   }
11103   if (!D)
11104     return false;
11105   return D->getType()->isArrayType() && !D->isWeak();
11106 }
11107 
11108 /// Diagnose some forms of syntactically-obvious tautological comparison.
11109 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11110                                            Expr *LHS, Expr *RHS,
11111                                            BinaryOperatorKind Opc) {
11112   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11113   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11114 
11115   QualType LHSType = LHS->getType();
11116   QualType RHSType = RHS->getType();
11117   if (LHSType->hasFloatingRepresentation() ||
11118       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11119       S.inTemplateInstantiation())
11120     return;
11121 
11122   // Comparisons between two array types are ill-formed for operator<=>, so
11123   // we shouldn't emit any additional warnings about it.
11124   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11125     return;
11126 
11127   // For non-floating point types, check for self-comparisons of the form
11128   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11129   // often indicate logic errors in the program.
11130   //
11131   // NOTE: Don't warn about comparison expressions resulting from macro
11132   // expansion. Also don't warn about comparisons which are only self
11133   // comparisons within a template instantiation. The warnings should catch
11134   // obvious cases in the definition of the template anyways. The idea is to
11135   // warn when the typed comparison operator will always evaluate to the same
11136   // result.
11137 
11138   // Used for indexing into %select in warn_comparison_always
11139   enum {
11140     AlwaysConstant,
11141     AlwaysTrue,
11142     AlwaysFalse,
11143     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11144   };
11145 
11146   // C++2a [depr.array.comp]:
11147   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11148   //   operands of array type are deprecated.
11149   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11150       RHSStripped->getType()->isArrayType()) {
11151     S.Diag(Loc, diag::warn_depr_array_comparison)
11152         << LHS->getSourceRange() << RHS->getSourceRange()
11153         << LHSStripped->getType() << RHSStripped->getType();
11154     // Carry on to produce the tautological comparison warning, if this
11155     // expression is potentially-evaluated, we can resolve the array to a
11156     // non-weak declaration, and so on.
11157   }
11158 
11159   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11160     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11161       unsigned Result;
11162       switch (Opc) {
11163       case BO_EQ:
11164       case BO_LE:
11165       case BO_GE:
11166         Result = AlwaysTrue;
11167         break;
11168       case BO_NE:
11169       case BO_LT:
11170       case BO_GT:
11171         Result = AlwaysFalse;
11172         break;
11173       case BO_Cmp:
11174         Result = AlwaysEqual;
11175         break;
11176       default:
11177         Result = AlwaysConstant;
11178         break;
11179       }
11180       S.DiagRuntimeBehavior(Loc, nullptr,
11181                             S.PDiag(diag::warn_comparison_always)
11182                                 << 0 /*self-comparison*/
11183                                 << Result);
11184     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11185       // What is it always going to evaluate to?
11186       unsigned Result;
11187       switch (Opc) {
11188       case BO_EQ: // e.g. array1 == array2
11189         Result = AlwaysFalse;
11190         break;
11191       case BO_NE: // e.g. array1 != array2
11192         Result = AlwaysTrue;
11193         break;
11194       default: // e.g. array1 <= array2
11195         // The best we can say is 'a constant'
11196         Result = AlwaysConstant;
11197         break;
11198       }
11199       S.DiagRuntimeBehavior(Loc, nullptr,
11200                             S.PDiag(diag::warn_comparison_always)
11201                                 << 1 /*array comparison*/
11202                                 << Result);
11203     }
11204   }
11205 
11206   if (isa<CastExpr>(LHSStripped))
11207     LHSStripped = LHSStripped->IgnoreParenCasts();
11208   if (isa<CastExpr>(RHSStripped))
11209     RHSStripped = RHSStripped->IgnoreParenCasts();
11210 
11211   // Warn about comparisons against a string constant (unless the other
11212   // operand is null); the user probably wants string comparison function.
11213   Expr *LiteralString = nullptr;
11214   Expr *LiteralStringStripped = nullptr;
11215   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11216       !RHSStripped->isNullPointerConstant(S.Context,
11217                                           Expr::NPC_ValueDependentIsNull)) {
11218     LiteralString = LHS;
11219     LiteralStringStripped = LHSStripped;
11220   } else if ((isa<StringLiteral>(RHSStripped) ||
11221               isa<ObjCEncodeExpr>(RHSStripped)) &&
11222              !LHSStripped->isNullPointerConstant(S.Context,
11223                                           Expr::NPC_ValueDependentIsNull)) {
11224     LiteralString = RHS;
11225     LiteralStringStripped = RHSStripped;
11226   }
11227 
11228   if (LiteralString) {
11229     S.DiagRuntimeBehavior(Loc, nullptr,
11230                           S.PDiag(diag::warn_stringcompare)
11231                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11232                               << LiteralString->getSourceRange());
11233   }
11234 }
11235 
11236 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11237   switch (CK) {
11238   default: {
11239 #ifndef NDEBUG
11240     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11241                  << "\n";
11242 #endif
11243     llvm_unreachable("unhandled cast kind");
11244   }
11245   case CK_UserDefinedConversion:
11246     return ICK_Identity;
11247   case CK_LValueToRValue:
11248     return ICK_Lvalue_To_Rvalue;
11249   case CK_ArrayToPointerDecay:
11250     return ICK_Array_To_Pointer;
11251   case CK_FunctionToPointerDecay:
11252     return ICK_Function_To_Pointer;
11253   case CK_IntegralCast:
11254     return ICK_Integral_Conversion;
11255   case CK_FloatingCast:
11256     return ICK_Floating_Conversion;
11257   case CK_IntegralToFloating:
11258   case CK_FloatingToIntegral:
11259     return ICK_Floating_Integral;
11260   case CK_IntegralComplexCast:
11261   case CK_FloatingComplexCast:
11262   case CK_FloatingComplexToIntegralComplex:
11263   case CK_IntegralComplexToFloatingComplex:
11264     return ICK_Complex_Conversion;
11265   case CK_FloatingComplexToReal:
11266   case CK_FloatingRealToComplex:
11267   case CK_IntegralComplexToReal:
11268   case CK_IntegralRealToComplex:
11269     return ICK_Complex_Real;
11270   }
11271 }
11272 
11273 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11274                                              QualType FromType,
11275                                              SourceLocation Loc) {
11276   // Check for a narrowing implicit conversion.
11277   StandardConversionSequence SCS;
11278   SCS.setAsIdentityConversion();
11279   SCS.setToType(0, FromType);
11280   SCS.setToType(1, ToType);
11281   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11282     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11283 
11284   APValue PreNarrowingValue;
11285   QualType PreNarrowingType;
11286   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11287                                PreNarrowingType,
11288                                /*IgnoreFloatToIntegralConversion*/ true)) {
11289   case NK_Dependent_Narrowing:
11290     // Implicit conversion to a narrower type, but the expression is
11291     // value-dependent so we can't tell whether it's actually narrowing.
11292   case NK_Not_Narrowing:
11293     return false;
11294 
11295   case NK_Constant_Narrowing:
11296     // Implicit conversion to a narrower type, and the value is not a constant
11297     // expression.
11298     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11299         << /*Constant*/ 1
11300         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11301     return true;
11302 
11303   case NK_Variable_Narrowing:
11304     // Implicit conversion to a narrower type, and the value is not a constant
11305     // expression.
11306   case NK_Type_Narrowing:
11307     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11308         << /*Constant*/ 0 << FromType << ToType;
11309     // TODO: It's not a constant expression, but what if the user intended it
11310     // to be? Can we produce notes to help them figure out why it isn't?
11311     return true;
11312   }
11313   llvm_unreachable("unhandled case in switch");
11314 }
11315 
11316 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11317                                                          ExprResult &LHS,
11318                                                          ExprResult &RHS,
11319                                                          SourceLocation Loc) {
11320   QualType LHSType = LHS.get()->getType();
11321   QualType RHSType = RHS.get()->getType();
11322   // Dig out the original argument type and expression before implicit casts
11323   // were applied. These are the types/expressions we need to check the
11324   // [expr.spaceship] requirements against.
11325   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11326   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11327   QualType LHSStrippedType = LHSStripped.get()->getType();
11328   QualType RHSStrippedType = RHSStripped.get()->getType();
11329 
11330   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11331   // other is not, the program is ill-formed.
11332   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11333     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11334     return QualType();
11335   }
11336 
11337   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11338   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11339                     RHSStrippedType->isEnumeralType();
11340   if (NumEnumArgs == 1) {
11341     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11342     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11343     if (OtherTy->hasFloatingRepresentation()) {
11344       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11345       return QualType();
11346     }
11347   }
11348   if (NumEnumArgs == 2) {
11349     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11350     // type E, the operator yields the result of converting the operands
11351     // to the underlying type of E and applying <=> to the converted operands.
11352     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11353       S.InvalidOperands(Loc, LHS, RHS);
11354       return QualType();
11355     }
11356     QualType IntType =
11357         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11358     assert(IntType->isArithmeticType());
11359 
11360     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11361     // promote the boolean type, and all other promotable integer types, to
11362     // avoid this.
11363     if (IntType->isPromotableIntegerType())
11364       IntType = S.Context.getPromotedIntegerType(IntType);
11365 
11366     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11367     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11368     LHSType = RHSType = IntType;
11369   }
11370 
11371   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11372   // usual arithmetic conversions are applied to the operands.
11373   QualType Type =
11374       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11375   if (LHS.isInvalid() || RHS.isInvalid())
11376     return QualType();
11377   if (Type.isNull())
11378     return S.InvalidOperands(Loc, LHS, RHS);
11379 
11380   Optional<ComparisonCategoryType> CCT =
11381       getComparisonCategoryForBuiltinCmp(Type);
11382   if (!CCT)
11383     return S.InvalidOperands(Loc, LHS, RHS);
11384 
11385   bool HasNarrowing = checkThreeWayNarrowingConversion(
11386       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11387   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11388                                                    RHS.get()->getBeginLoc());
11389   if (HasNarrowing)
11390     return QualType();
11391 
11392   assert(!Type.isNull() && "composite type for <=> has not been set");
11393 
11394   return S.CheckComparisonCategoryType(
11395       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11396 }
11397 
11398 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11399                                                  ExprResult &RHS,
11400                                                  SourceLocation Loc,
11401                                                  BinaryOperatorKind Opc) {
11402   if (Opc == BO_Cmp)
11403     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11404 
11405   // C99 6.5.8p3 / C99 6.5.9p4
11406   QualType Type =
11407       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11408   if (LHS.isInvalid() || RHS.isInvalid())
11409     return QualType();
11410   if (Type.isNull())
11411     return S.InvalidOperands(Loc, LHS, RHS);
11412   assert(Type->isArithmeticType() || Type->isEnumeralType());
11413 
11414   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11415     return S.InvalidOperands(Loc, LHS, RHS);
11416 
11417   // Check for comparisons of floating point operands using != and ==.
11418   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11419     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11420 
11421   // The result of comparisons is 'bool' in C++, 'int' in C.
11422   return S.Context.getLogicalOperationType();
11423 }
11424 
11425 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11426   if (!NullE.get()->getType()->isAnyPointerType())
11427     return;
11428   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11429   if (!E.get()->getType()->isAnyPointerType() &&
11430       E.get()->isNullPointerConstant(Context,
11431                                      Expr::NPC_ValueDependentIsNotNull) ==
11432         Expr::NPCK_ZeroExpression) {
11433     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11434       if (CL->getValue() == 0)
11435         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11436             << NullValue
11437             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11438                                             NullValue ? "NULL" : "(void *)0");
11439     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11440         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11441         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11442         if (T == Context.CharTy)
11443           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11444               << NullValue
11445               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11446                                               NullValue ? "NULL" : "(void *)0");
11447       }
11448   }
11449 }
11450 
11451 // C99 6.5.8, C++ [expr.rel]
11452 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11453                                     SourceLocation Loc,
11454                                     BinaryOperatorKind Opc) {
11455   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11456   bool IsThreeWay = Opc == BO_Cmp;
11457   bool IsOrdered = IsRelational || IsThreeWay;
11458   auto IsAnyPointerType = [](ExprResult E) {
11459     QualType Ty = E.get()->getType();
11460     return Ty->isPointerType() || Ty->isMemberPointerType();
11461   };
11462 
11463   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11464   // type, array-to-pointer, ..., conversions are performed on both operands to
11465   // bring them to their composite type.
11466   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11467   // any type-related checks.
11468   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11469     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11470     if (LHS.isInvalid())
11471       return QualType();
11472     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11473     if (RHS.isInvalid())
11474       return QualType();
11475   } else {
11476     LHS = DefaultLvalueConversion(LHS.get());
11477     if (LHS.isInvalid())
11478       return QualType();
11479     RHS = DefaultLvalueConversion(RHS.get());
11480     if (RHS.isInvalid())
11481       return QualType();
11482   }
11483 
11484   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11485   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11486     CheckPtrComparisonWithNullChar(LHS, RHS);
11487     CheckPtrComparisonWithNullChar(RHS, LHS);
11488   }
11489 
11490   // Handle vector comparisons separately.
11491   if (LHS.get()->getType()->isVectorType() ||
11492       RHS.get()->getType()->isVectorType())
11493     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11494 
11495   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11496   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11497 
11498   QualType LHSType = LHS.get()->getType();
11499   QualType RHSType = RHS.get()->getType();
11500   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11501       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11502     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11503 
11504   const Expr::NullPointerConstantKind LHSNullKind =
11505       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11506   const Expr::NullPointerConstantKind RHSNullKind =
11507       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11508   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11509   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11510 
11511   auto computeResultTy = [&]() {
11512     if (Opc != BO_Cmp)
11513       return Context.getLogicalOperationType();
11514     assert(getLangOpts().CPlusPlus);
11515     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11516 
11517     QualType CompositeTy = LHS.get()->getType();
11518     assert(!CompositeTy->isReferenceType());
11519 
11520     Optional<ComparisonCategoryType> CCT =
11521         getComparisonCategoryForBuiltinCmp(CompositeTy);
11522     if (!CCT)
11523       return InvalidOperands(Loc, LHS, RHS);
11524 
11525     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11526       // P0946R0: Comparisons between a null pointer constant and an object
11527       // pointer result in std::strong_equality, which is ill-formed under
11528       // P1959R0.
11529       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11530           << (LHSIsNull ? LHS.get()->getSourceRange()
11531                         : RHS.get()->getSourceRange());
11532       return QualType();
11533     }
11534 
11535     return CheckComparisonCategoryType(
11536         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11537   };
11538 
11539   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11540     bool IsEquality = Opc == BO_EQ;
11541     if (RHSIsNull)
11542       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11543                                    RHS.get()->getSourceRange());
11544     else
11545       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11546                                    LHS.get()->getSourceRange());
11547   }
11548 
11549   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11550       (RHSType->isIntegerType() && !RHSIsNull)) {
11551     // Skip normal pointer conversion checks in this case; we have better
11552     // diagnostics for this below.
11553   } else if (getLangOpts().CPlusPlus) {
11554     // Equality comparison of a function pointer to a void pointer is invalid,
11555     // but we allow it as an extension.
11556     // FIXME: If we really want to allow this, should it be part of composite
11557     // pointer type computation so it works in conditionals too?
11558     if (!IsOrdered &&
11559         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11560          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11561       // This is a gcc extension compatibility comparison.
11562       // In a SFINAE context, we treat this as a hard error to maintain
11563       // conformance with the C++ standard.
11564       diagnoseFunctionPointerToVoidComparison(
11565           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11566 
11567       if (isSFINAEContext())
11568         return QualType();
11569 
11570       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11571       return computeResultTy();
11572     }
11573 
11574     // C++ [expr.eq]p2:
11575     //   If at least one operand is a pointer [...] bring them to their
11576     //   composite pointer type.
11577     // C++ [expr.spaceship]p6
11578     //  If at least one of the operands is of pointer type, [...] bring them
11579     //  to their composite pointer type.
11580     // C++ [expr.rel]p2:
11581     //   If both operands are pointers, [...] bring them to their composite
11582     //   pointer type.
11583     // For <=>, the only valid non-pointer types are arrays and functions, and
11584     // we already decayed those, so this is really the same as the relational
11585     // comparison rule.
11586     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11587             (IsOrdered ? 2 : 1) &&
11588         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11589                                          RHSType->isObjCObjectPointerType()))) {
11590       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11591         return QualType();
11592       return computeResultTy();
11593     }
11594   } else if (LHSType->isPointerType() &&
11595              RHSType->isPointerType()) { // C99 6.5.8p2
11596     // All of the following pointer-related warnings are GCC extensions, except
11597     // when handling null pointer constants.
11598     QualType LCanPointeeTy =
11599       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11600     QualType RCanPointeeTy =
11601       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11602 
11603     // C99 6.5.9p2 and C99 6.5.8p2
11604     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11605                                    RCanPointeeTy.getUnqualifiedType())) {
11606       if (IsRelational) {
11607         // Pointers both need to point to complete or incomplete types
11608         if ((LCanPointeeTy->isIncompleteType() !=
11609              RCanPointeeTy->isIncompleteType()) &&
11610             !getLangOpts().C11) {
11611           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11612               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11613               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11614               << RCanPointeeTy->isIncompleteType();
11615         }
11616         if (LCanPointeeTy->isFunctionType()) {
11617           // Valid unless a relational comparison of function pointers
11618           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11619               << LHSType << RHSType << LHS.get()->getSourceRange()
11620               << RHS.get()->getSourceRange();
11621         }
11622       }
11623     } else if (!IsRelational &&
11624                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11625       // Valid unless comparison between non-null pointer and function pointer
11626       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11627           && !LHSIsNull && !RHSIsNull)
11628         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11629                                                 /*isError*/false);
11630     } else {
11631       // Invalid
11632       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11633     }
11634     if (LCanPointeeTy != RCanPointeeTy) {
11635       // Treat NULL constant as a special case in OpenCL.
11636       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11637         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11638           Diag(Loc,
11639                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11640               << LHSType << RHSType << 0 /* comparison */
11641               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11642         }
11643       }
11644       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11645       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11646       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11647                                                : CK_BitCast;
11648       if (LHSIsNull && !RHSIsNull)
11649         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11650       else
11651         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11652     }
11653     return computeResultTy();
11654   }
11655 
11656   if (getLangOpts().CPlusPlus) {
11657     // C++ [expr.eq]p4:
11658     //   Two operands of type std::nullptr_t or one operand of type
11659     //   std::nullptr_t and the other a null pointer constant compare equal.
11660     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11661       if (LHSType->isNullPtrType()) {
11662         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11663         return computeResultTy();
11664       }
11665       if (RHSType->isNullPtrType()) {
11666         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11667         return computeResultTy();
11668       }
11669     }
11670 
11671     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11672     // These aren't covered by the composite pointer type rules.
11673     if (!IsOrdered && RHSType->isNullPtrType() &&
11674         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11675       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11676       return computeResultTy();
11677     }
11678     if (!IsOrdered && LHSType->isNullPtrType() &&
11679         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11680       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11681       return computeResultTy();
11682     }
11683 
11684     if (IsRelational &&
11685         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11686          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11687       // HACK: Relational comparison of nullptr_t against a pointer type is
11688       // invalid per DR583, but we allow it within std::less<> and friends,
11689       // since otherwise common uses of it break.
11690       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11691       // friends to have std::nullptr_t overload candidates.
11692       DeclContext *DC = CurContext;
11693       if (isa<FunctionDecl>(DC))
11694         DC = DC->getParent();
11695       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11696         if (CTSD->isInStdNamespace() &&
11697             llvm::StringSwitch<bool>(CTSD->getName())
11698                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11699                 .Default(false)) {
11700           if (RHSType->isNullPtrType())
11701             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11702           else
11703             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11704           return computeResultTy();
11705         }
11706       }
11707     }
11708 
11709     // C++ [expr.eq]p2:
11710     //   If at least one operand is a pointer to member, [...] bring them to
11711     //   their composite pointer type.
11712     if (!IsOrdered &&
11713         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11714       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11715         return QualType();
11716       else
11717         return computeResultTy();
11718     }
11719   }
11720 
11721   // Handle block pointer types.
11722   if (!IsOrdered && LHSType->isBlockPointerType() &&
11723       RHSType->isBlockPointerType()) {
11724     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11725     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11726 
11727     if (!LHSIsNull && !RHSIsNull &&
11728         !Context.typesAreCompatible(lpointee, rpointee)) {
11729       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11730         << LHSType << RHSType << LHS.get()->getSourceRange()
11731         << RHS.get()->getSourceRange();
11732     }
11733     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11734     return computeResultTy();
11735   }
11736 
11737   // Allow block pointers to be compared with null pointer constants.
11738   if (!IsOrdered
11739       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11740           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11741     if (!LHSIsNull && !RHSIsNull) {
11742       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11743              ->getPointeeType()->isVoidType())
11744             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11745                 ->getPointeeType()->isVoidType())))
11746         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11747           << LHSType << RHSType << LHS.get()->getSourceRange()
11748           << RHS.get()->getSourceRange();
11749     }
11750     if (LHSIsNull && !RHSIsNull)
11751       LHS = ImpCastExprToType(LHS.get(), RHSType,
11752                               RHSType->isPointerType() ? CK_BitCast
11753                                 : CK_AnyPointerToBlockPointerCast);
11754     else
11755       RHS = ImpCastExprToType(RHS.get(), LHSType,
11756                               LHSType->isPointerType() ? CK_BitCast
11757                                 : CK_AnyPointerToBlockPointerCast);
11758     return computeResultTy();
11759   }
11760 
11761   if (LHSType->isObjCObjectPointerType() ||
11762       RHSType->isObjCObjectPointerType()) {
11763     const PointerType *LPT = LHSType->getAs<PointerType>();
11764     const PointerType *RPT = RHSType->getAs<PointerType>();
11765     if (LPT || RPT) {
11766       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11767       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11768 
11769       if (!LPtrToVoid && !RPtrToVoid &&
11770           !Context.typesAreCompatible(LHSType, RHSType)) {
11771         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11772                                           /*isError*/false);
11773       }
11774       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11775       // the RHS, but we have test coverage for this behavior.
11776       // FIXME: Consider using convertPointersToCompositeType in C++.
11777       if (LHSIsNull && !RHSIsNull) {
11778         Expr *E = LHS.get();
11779         if (getLangOpts().ObjCAutoRefCount)
11780           CheckObjCConversion(SourceRange(), RHSType, E,
11781                               CCK_ImplicitConversion);
11782         LHS = ImpCastExprToType(E, RHSType,
11783                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11784       }
11785       else {
11786         Expr *E = RHS.get();
11787         if (getLangOpts().ObjCAutoRefCount)
11788           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11789                               /*Diagnose=*/true,
11790                               /*DiagnoseCFAudited=*/false, Opc);
11791         RHS = ImpCastExprToType(E, LHSType,
11792                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11793       }
11794       return computeResultTy();
11795     }
11796     if (LHSType->isObjCObjectPointerType() &&
11797         RHSType->isObjCObjectPointerType()) {
11798       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11799         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11800                                           /*isError*/false);
11801       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11802         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11803 
11804       if (LHSIsNull && !RHSIsNull)
11805         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11806       else
11807         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11808       return computeResultTy();
11809     }
11810 
11811     if (!IsOrdered && LHSType->isBlockPointerType() &&
11812         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11813       LHS = ImpCastExprToType(LHS.get(), RHSType,
11814                               CK_BlockPointerToObjCPointerCast);
11815       return computeResultTy();
11816     } else if (!IsOrdered &&
11817                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11818                RHSType->isBlockPointerType()) {
11819       RHS = ImpCastExprToType(RHS.get(), LHSType,
11820                               CK_BlockPointerToObjCPointerCast);
11821       return computeResultTy();
11822     }
11823   }
11824   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11825       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11826     unsigned DiagID = 0;
11827     bool isError = false;
11828     if (LangOpts.DebuggerSupport) {
11829       // Under a debugger, allow the comparison of pointers to integers,
11830       // since users tend to want to compare addresses.
11831     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11832                (RHSIsNull && RHSType->isIntegerType())) {
11833       if (IsOrdered) {
11834         isError = getLangOpts().CPlusPlus;
11835         DiagID =
11836           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11837                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11838       }
11839     } else if (getLangOpts().CPlusPlus) {
11840       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11841       isError = true;
11842     } else if (IsOrdered)
11843       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11844     else
11845       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11846 
11847     if (DiagID) {
11848       Diag(Loc, DiagID)
11849         << LHSType << RHSType << LHS.get()->getSourceRange()
11850         << RHS.get()->getSourceRange();
11851       if (isError)
11852         return QualType();
11853     }
11854 
11855     if (LHSType->isIntegerType())
11856       LHS = ImpCastExprToType(LHS.get(), RHSType,
11857                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11858     else
11859       RHS = ImpCastExprToType(RHS.get(), LHSType,
11860                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11861     return computeResultTy();
11862   }
11863 
11864   // Handle block pointers.
11865   if (!IsOrdered && RHSIsNull
11866       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11867     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11868     return computeResultTy();
11869   }
11870   if (!IsOrdered && LHSIsNull
11871       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11872     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11873     return computeResultTy();
11874   }
11875 
11876   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11877     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11878       return computeResultTy();
11879     }
11880 
11881     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11882       return computeResultTy();
11883     }
11884 
11885     if (LHSIsNull && RHSType->isQueueT()) {
11886       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11887       return computeResultTy();
11888     }
11889 
11890     if (LHSType->isQueueT() && RHSIsNull) {
11891       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11892       return computeResultTy();
11893     }
11894   }
11895 
11896   return InvalidOperands(Loc, LHS, RHS);
11897 }
11898 
11899 // Return a signed ext_vector_type that is of identical size and number of
11900 // elements. For floating point vectors, return an integer type of identical
11901 // size and number of elements. In the non ext_vector_type case, search from
11902 // the largest type to the smallest type to avoid cases where long long == long,
11903 // where long gets picked over long long.
11904 QualType Sema::GetSignedVectorType(QualType V) {
11905   const VectorType *VTy = V->castAs<VectorType>();
11906   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11907 
11908   if (isa<ExtVectorType>(VTy)) {
11909     if (TypeSize == Context.getTypeSize(Context.CharTy))
11910       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11911     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11912       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11913     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11914       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11915     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11916       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11917     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11918            "Unhandled vector element size in vector compare");
11919     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11920   }
11921 
11922   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11923     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11924                                  VectorType::GenericVector);
11925   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11926     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11927                                  VectorType::GenericVector);
11928   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11929     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11930                                  VectorType::GenericVector);
11931   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11932     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11933                                  VectorType::GenericVector);
11934   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11935          "Unhandled vector element size in vector compare");
11936   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11937                                VectorType::GenericVector);
11938 }
11939 
11940 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11941 /// operates on extended vector types.  Instead of producing an IntTy result,
11942 /// like a scalar comparison, a vector comparison produces a vector of integer
11943 /// types.
11944 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11945                                           SourceLocation Loc,
11946                                           BinaryOperatorKind Opc) {
11947   if (Opc == BO_Cmp) {
11948     Diag(Loc, diag::err_three_way_vector_comparison);
11949     return QualType();
11950   }
11951 
11952   // Check to make sure we're operating on vectors of the same type and width,
11953   // Allowing one side to be a scalar of element type.
11954   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11955                               /*AllowBothBool*/true,
11956                               /*AllowBoolConversions*/getLangOpts().ZVector);
11957   if (vType.isNull())
11958     return vType;
11959 
11960   QualType LHSType = LHS.get()->getType();
11961 
11962   // If AltiVec, the comparison results in a numeric type, i.e.
11963   // bool for C++, int for C
11964   if (getLangOpts().AltiVec &&
11965       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11966     return Context.getLogicalOperationType();
11967 
11968   // For non-floating point types, check for self-comparisons of the form
11969   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11970   // often indicate logic errors in the program.
11971   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11972 
11973   // Check for comparisons of floating point operands using != and ==.
11974   if (BinaryOperator::isEqualityOp(Opc) &&
11975       LHSType->hasFloatingRepresentation()) {
11976     assert(RHS.get()->getType()->hasFloatingRepresentation());
11977     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11978   }
11979 
11980   // Return a signed type for the vector.
11981   return GetSignedVectorType(vType);
11982 }
11983 
11984 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11985                                     const ExprResult &XorRHS,
11986                                     const SourceLocation Loc) {
11987   // Do not diagnose macros.
11988   if (Loc.isMacroID())
11989     return;
11990 
11991   bool Negative = false;
11992   bool ExplicitPlus = false;
11993   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11994   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11995 
11996   if (!LHSInt)
11997     return;
11998   if (!RHSInt) {
11999     // Check negative literals.
12000     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12001       UnaryOperatorKind Opc = UO->getOpcode();
12002       if (Opc != UO_Minus && Opc != UO_Plus)
12003         return;
12004       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12005       if (!RHSInt)
12006         return;
12007       Negative = (Opc == UO_Minus);
12008       ExplicitPlus = !Negative;
12009     } else {
12010       return;
12011     }
12012   }
12013 
12014   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12015   llvm::APInt RightSideValue = RHSInt->getValue();
12016   if (LeftSideValue != 2 && LeftSideValue != 10)
12017     return;
12018 
12019   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12020     return;
12021 
12022   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12023       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12024   llvm::StringRef ExprStr =
12025       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12026 
12027   CharSourceRange XorRange =
12028       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12029   llvm::StringRef XorStr =
12030       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12031   // Do not diagnose if xor keyword/macro is used.
12032   if (XorStr == "xor")
12033     return;
12034 
12035   std::string LHSStr = std::string(Lexer::getSourceText(
12036       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12037       S.getSourceManager(), S.getLangOpts()));
12038   std::string RHSStr = std::string(Lexer::getSourceText(
12039       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12040       S.getSourceManager(), S.getLangOpts()));
12041 
12042   if (Negative) {
12043     RightSideValue = -RightSideValue;
12044     RHSStr = "-" + RHSStr;
12045   } else if (ExplicitPlus) {
12046     RHSStr = "+" + RHSStr;
12047   }
12048 
12049   StringRef LHSStrRef = LHSStr;
12050   StringRef RHSStrRef = RHSStr;
12051   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12052   // literals.
12053   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12054       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12055       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12056       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12057       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12058       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12059       LHSStrRef.find('\'') != StringRef::npos ||
12060       RHSStrRef.find('\'') != StringRef::npos)
12061     return;
12062 
12063   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12064   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12065   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12066   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12067     std::string SuggestedExpr = "1 << " + RHSStr;
12068     bool Overflow = false;
12069     llvm::APInt One = (LeftSideValue - 1);
12070     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12071     if (Overflow) {
12072       if (RightSideIntValue < 64)
12073         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12074             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12075             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12076       else if (RightSideIntValue == 64)
12077         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12078       else
12079         return;
12080     } else {
12081       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12082           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12083           << PowValue.toString(10, true)
12084           << FixItHint::CreateReplacement(
12085                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12086     }
12087 
12088     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12089   } else if (LeftSideValue == 10) {
12090     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12091     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12092         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12093         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12094     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12095   }
12096 }
12097 
12098 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12099                                           SourceLocation Loc) {
12100   // Ensure that either both operands are of the same vector type, or
12101   // one operand is of a vector type and the other is of its element type.
12102   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12103                                        /*AllowBothBool*/true,
12104                                        /*AllowBoolConversions*/false);
12105   if (vType.isNull())
12106     return InvalidOperands(Loc, LHS, RHS);
12107   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12108       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12109     return InvalidOperands(Loc, LHS, RHS);
12110   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12111   //        usage of the logical operators && and || with vectors in C. This
12112   //        check could be notionally dropped.
12113   if (!getLangOpts().CPlusPlus &&
12114       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12115     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12116 
12117   return GetSignedVectorType(LHS.get()->getType());
12118 }
12119 
12120 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12121                                               SourceLocation Loc,
12122                                               bool IsCompAssign) {
12123   if (!IsCompAssign) {
12124     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12125     if (LHS.isInvalid())
12126       return QualType();
12127   }
12128   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12129   if (RHS.isInvalid())
12130     return QualType();
12131 
12132   // For conversion purposes, we ignore any qualifiers.
12133   // For example, "const float" and "float" are equivalent.
12134   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12135   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12136 
12137   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12138   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12139   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12140 
12141   if (Context.hasSameType(LHSType, RHSType))
12142     return LHSType;
12143 
12144   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12145   // case we have to return InvalidOperands.
12146   ExprResult OriginalLHS = LHS;
12147   ExprResult OriginalRHS = RHS;
12148   if (LHSMatType && !RHSMatType) {
12149     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12150     if (!RHS.isInvalid())
12151       return LHSType;
12152 
12153     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12154   }
12155 
12156   if (!LHSMatType && RHSMatType) {
12157     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12158     if (!LHS.isInvalid())
12159       return RHSType;
12160     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12161   }
12162 
12163   return InvalidOperands(Loc, LHS, RHS);
12164 }
12165 
12166 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12167                                            SourceLocation Loc,
12168                                            bool IsCompAssign) {
12169   if (!IsCompAssign) {
12170     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12171     if (LHS.isInvalid())
12172       return QualType();
12173   }
12174   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12175   if (RHS.isInvalid())
12176     return QualType();
12177 
12178   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12179   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12180   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12181 
12182   if (LHSMatType && RHSMatType) {
12183     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12184       return InvalidOperands(Loc, LHS, RHS);
12185 
12186     if (!Context.hasSameType(LHSMatType->getElementType(),
12187                              RHSMatType->getElementType()))
12188       return InvalidOperands(Loc, LHS, RHS);
12189 
12190     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12191                                          LHSMatType->getNumRows(),
12192                                          RHSMatType->getNumColumns());
12193   }
12194   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12195 }
12196 
12197 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12198                                            SourceLocation Loc,
12199                                            BinaryOperatorKind Opc) {
12200   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12201 
12202   bool IsCompAssign =
12203       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12204 
12205   if (LHS.get()->getType()->isVectorType() ||
12206       RHS.get()->getType()->isVectorType()) {
12207     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12208         RHS.get()->getType()->hasIntegerRepresentation())
12209       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12210                         /*AllowBothBool*/true,
12211                         /*AllowBoolConversions*/getLangOpts().ZVector);
12212     return InvalidOperands(Loc, LHS, RHS);
12213   }
12214 
12215   if (Opc == BO_And)
12216     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12217 
12218   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12219       RHS.get()->getType()->hasFloatingRepresentation())
12220     return InvalidOperands(Loc, LHS, RHS);
12221 
12222   ExprResult LHSResult = LHS, RHSResult = RHS;
12223   QualType compType = UsualArithmeticConversions(
12224       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12225   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12226     return QualType();
12227   LHS = LHSResult.get();
12228   RHS = RHSResult.get();
12229 
12230   if (Opc == BO_Xor)
12231     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12232 
12233   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12234     return compType;
12235   return InvalidOperands(Loc, LHS, RHS);
12236 }
12237 
12238 // C99 6.5.[13,14]
12239 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12240                                            SourceLocation Loc,
12241                                            BinaryOperatorKind Opc) {
12242   // Check vector operands differently.
12243   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12244     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12245 
12246   bool EnumConstantInBoolContext = false;
12247   for (const ExprResult &HS : {LHS, RHS}) {
12248     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12249       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12250       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12251         EnumConstantInBoolContext = true;
12252     }
12253   }
12254 
12255   if (EnumConstantInBoolContext)
12256     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12257 
12258   // Diagnose cases where the user write a logical and/or but probably meant a
12259   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12260   // is a constant.
12261   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12262       !LHS.get()->getType()->isBooleanType() &&
12263       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12264       // Don't warn in macros or template instantiations.
12265       !Loc.isMacroID() && !inTemplateInstantiation()) {
12266     // If the RHS can be constant folded, and if it constant folds to something
12267     // that isn't 0 or 1 (which indicate a potential logical operation that
12268     // happened to fold to true/false) then warn.
12269     // Parens on the RHS are ignored.
12270     Expr::EvalResult EVResult;
12271     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12272       llvm::APSInt Result = EVResult.Val.getInt();
12273       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12274            !RHS.get()->getExprLoc().isMacroID()) ||
12275           (Result != 0 && Result != 1)) {
12276         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12277           << RHS.get()->getSourceRange()
12278           << (Opc == BO_LAnd ? "&&" : "||");
12279         // Suggest replacing the logical operator with the bitwise version
12280         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12281             << (Opc == BO_LAnd ? "&" : "|")
12282             << FixItHint::CreateReplacement(SourceRange(
12283                                                  Loc, getLocForEndOfToken(Loc)),
12284                                             Opc == BO_LAnd ? "&" : "|");
12285         if (Opc == BO_LAnd)
12286           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12287           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12288               << FixItHint::CreateRemoval(
12289                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12290                                  RHS.get()->getEndLoc()));
12291       }
12292     }
12293   }
12294 
12295   if (!Context.getLangOpts().CPlusPlus) {
12296     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12297     // not operate on the built-in scalar and vector float types.
12298     if (Context.getLangOpts().OpenCL &&
12299         Context.getLangOpts().OpenCLVersion < 120) {
12300       if (LHS.get()->getType()->isFloatingType() ||
12301           RHS.get()->getType()->isFloatingType())
12302         return InvalidOperands(Loc, LHS, RHS);
12303     }
12304 
12305     LHS = UsualUnaryConversions(LHS.get());
12306     if (LHS.isInvalid())
12307       return QualType();
12308 
12309     RHS = UsualUnaryConversions(RHS.get());
12310     if (RHS.isInvalid())
12311       return QualType();
12312 
12313     if (!LHS.get()->getType()->isScalarType() ||
12314         !RHS.get()->getType()->isScalarType())
12315       return InvalidOperands(Loc, LHS, RHS);
12316 
12317     return Context.IntTy;
12318   }
12319 
12320   // The following is safe because we only use this method for
12321   // non-overloadable operands.
12322 
12323   // C++ [expr.log.and]p1
12324   // C++ [expr.log.or]p1
12325   // The operands are both contextually converted to type bool.
12326   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12327   if (LHSRes.isInvalid())
12328     return InvalidOperands(Loc, LHS, RHS);
12329   LHS = LHSRes;
12330 
12331   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12332   if (RHSRes.isInvalid())
12333     return InvalidOperands(Loc, LHS, RHS);
12334   RHS = RHSRes;
12335 
12336   // C++ [expr.log.and]p2
12337   // C++ [expr.log.or]p2
12338   // The result is a bool.
12339   return Context.BoolTy;
12340 }
12341 
12342 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12343   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12344   if (!ME) return false;
12345   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12346   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12347       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12348   if (!Base) return false;
12349   return Base->getMethodDecl() != nullptr;
12350 }
12351 
12352 /// Is the given expression (which must be 'const') a reference to a
12353 /// variable which was originally non-const, but which has become
12354 /// 'const' due to being captured within a block?
12355 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12356 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12357   assert(E->isLValue() && E->getType().isConstQualified());
12358   E = E->IgnoreParens();
12359 
12360   // Must be a reference to a declaration from an enclosing scope.
12361   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12362   if (!DRE) return NCCK_None;
12363   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12364 
12365   // The declaration must be a variable which is not declared 'const'.
12366   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12367   if (!var) return NCCK_None;
12368   if (var->getType().isConstQualified()) return NCCK_None;
12369   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12370 
12371   // Decide whether the first capture was for a block or a lambda.
12372   DeclContext *DC = S.CurContext, *Prev = nullptr;
12373   // Decide whether the first capture was for a block or a lambda.
12374   while (DC) {
12375     // For init-capture, it is possible that the variable belongs to the
12376     // template pattern of the current context.
12377     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12378       if (var->isInitCapture() &&
12379           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12380         break;
12381     if (DC == var->getDeclContext())
12382       break;
12383     Prev = DC;
12384     DC = DC->getParent();
12385   }
12386   // Unless we have an init-capture, we've gone one step too far.
12387   if (!var->isInitCapture())
12388     DC = Prev;
12389   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12390 }
12391 
12392 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12393   Ty = Ty.getNonReferenceType();
12394   if (IsDereference && Ty->isPointerType())
12395     Ty = Ty->getPointeeType();
12396   return !Ty.isConstQualified();
12397 }
12398 
12399 // Update err_typecheck_assign_const and note_typecheck_assign_const
12400 // when this enum is changed.
12401 enum {
12402   ConstFunction,
12403   ConstVariable,
12404   ConstMember,
12405   ConstMethod,
12406   NestedConstMember,
12407   ConstUnknown,  // Keep as last element
12408 };
12409 
12410 /// Emit the "read-only variable not assignable" error and print notes to give
12411 /// more information about why the variable is not assignable, such as pointing
12412 /// to the declaration of a const variable, showing that a method is const, or
12413 /// that the function is returning a const reference.
12414 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12415                                     SourceLocation Loc) {
12416   SourceRange ExprRange = E->getSourceRange();
12417 
12418   // Only emit one error on the first const found.  All other consts will emit
12419   // a note to the error.
12420   bool DiagnosticEmitted = false;
12421 
12422   // Track if the current expression is the result of a dereference, and if the
12423   // next checked expression is the result of a dereference.
12424   bool IsDereference = false;
12425   bool NextIsDereference = false;
12426 
12427   // Loop to process MemberExpr chains.
12428   while (true) {
12429     IsDereference = NextIsDereference;
12430 
12431     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12432     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12433       NextIsDereference = ME->isArrow();
12434       const ValueDecl *VD = ME->getMemberDecl();
12435       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12436         // Mutable fields can be modified even if the class is const.
12437         if (Field->isMutable()) {
12438           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12439           break;
12440         }
12441 
12442         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12443           if (!DiagnosticEmitted) {
12444             S.Diag(Loc, diag::err_typecheck_assign_const)
12445                 << ExprRange << ConstMember << false /*static*/ << Field
12446                 << Field->getType();
12447             DiagnosticEmitted = true;
12448           }
12449           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12450               << ConstMember << false /*static*/ << Field << Field->getType()
12451               << Field->getSourceRange();
12452         }
12453         E = ME->getBase();
12454         continue;
12455       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12456         if (VDecl->getType().isConstQualified()) {
12457           if (!DiagnosticEmitted) {
12458             S.Diag(Loc, diag::err_typecheck_assign_const)
12459                 << ExprRange << ConstMember << true /*static*/ << VDecl
12460                 << VDecl->getType();
12461             DiagnosticEmitted = true;
12462           }
12463           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12464               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12465               << VDecl->getSourceRange();
12466         }
12467         // Static fields do not inherit constness from parents.
12468         break;
12469       }
12470       break; // End MemberExpr
12471     } else if (const ArraySubscriptExpr *ASE =
12472                    dyn_cast<ArraySubscriptExpr>(E)) {
12473       E = ASE->getBase()->IgnoreParenImpCasts();
12474       continue;
12475     } else if (const ExtVectorElementExpr *EVE =
12476                    dyn_cast<ExtVectorElementExpr>(E)) {
12477       E = EVE->getBase()->IgnoreParenImpCasts();
12478       continue;
12479     }
12480     break;
12481   }
12482 
12483   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12484     // Function calls
12485     const FunctionDecl *FD = CE->getDirectCallee();
12486     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12487       if (!DiagnosticEmitted) {
12488         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12489                                                       << ConstFunction << FD;
12490         DiagnosticEmitted = true;
12491       }
12492       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12493              diag::note_typecheck_assign_const)
12494           << ConstFunction << FD << FD->getReturnType()
12495           << FD->getReturnTypeSourceRange();
12496     }
12497   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12498     // Point to variable declaration.
12499     if (const ValueDecl *VD = DRE->getDecl()) {
12500       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12501         if (!DiagnosticEmitted) {
12502           S.Diag(Loc, diag::err_typecheck_assign_const)
12503               << ExprRange << ConstVariable << VD << VD->getType();
12504           DiagnosticEmitted = true;
12505         }
12506         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12507             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12508       }
12509     }
12510   } else if (isa<CXXThisExpr>(E)) {
12511     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12512       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12513         if (MD->isConst()) {
12514           if (!DiagnosticEmitted) {
12515             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12516                                                           << ConstMethod << MD;
12517             DiagnosticEmitted = true;
12518           }
12519           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12520               << ConstMethod << MD << MD->getSourceRange();
12521         }
12522       }
12523     }
12524   }
12525 
12526   if (DiagnosticEmitted)
12527     return;
12528 
12529   // Can't determine a more specific message, so display the generic error.
12530   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12531 }
12532 
12533 enum OriginalExprKind {
12534   OEK_Variable,
12535   OEK_Member,
12536   OEK_LValue
12537 };
12538 
12539 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12540                                          const RecordType *Ty,
12541                                          SourceLocation Loc, SourceRange Range,
12542                                          OriginalExprKind OEK,
12543                                          bool &DiagnosticEmitted) {
12544   std::vector<const RecordType *> RecordTypeList;
12545   RecordTypeList.push_back(Ty);
12546   unsigned NextToCheckIndex = 0;
12547   // We walk the record hierarchy breadth-first to ensure that we print
12548   // diagnostics in field nesting order.
12549   while (RecordTypeList.size() > NextToCheckIndex) {
12550     bool IsNested = NextToCheckIndex > 0;
12551     for (const FieldDecl *Field :
12552          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12553       // First, check every field for constness.
12554       QualType FieldTy = Field->getType();
12555       if (FieldTy.isConstQualified()) {
12556         if (!DiagnosticEmitted) {
12557           S.Diag(Loc, diag::err_typecheck_assign_const)
12558               << Range << NestedConstMember << OEK << VD
12559               << IsNested << Field;
12560           DiagnosticEmitted = true;
12561         }
12562         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12563             << NestedConstMember << IsNested << Field
12564             << FieldTy << Field->getSourceRange();
12565       }
12566 
12567       // Then we append it to the list to check next in order.
12568       FieldTy = FieldTy.getCanonicalType();
12569       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12570         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12571           RecordTypeList.push_back(FieldRecTy);
12572       }
12573     }
12574     ++NextToCheckIndex;
12575   }
12576 }
12577 
12578 /// Emit an error for the case where a record we are trying to assign to has a
12579 /// const-qualified field somewhere in its hierarchy.
12580 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12581                                          SourceLocation Loc) {
12582   QualType Ty = E->getType();
12583   assert(Ty->isRecordType() && "lvalue was not record?");
12584   SourceRange Range = E->getSourceRange();
12585   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12586   bool DiagEmitted = false;
12587 
12588   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12589     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12590             Range, OEK_Member, DiagEmitted);
12591   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12592     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12593             Range, OEK_Variable, DiagEmitted);
12594   else
12595     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12596             Range, OEK_LValue, DiagEmitted);
12597   if (!DiagEmitted)
12598     DiagnoseConstAssignment(S, E, Loc);
12599 }
12600 
12601 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12602 /// emit an error and return true.  If so, return false.
12603 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12604   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12605 
12606   S.CheckShadowingDeclModification(E, Loc);
12607 
12608   SourceLocation OrigLoc = Loc;
12609   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12610                                                               &Loc);
12611   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12612     IsLV = Expr::MLV_InvalidMessageExpression;
12613   if (IsLV == Expr::MLV_Valid)
12614     return false;
12615 
12616   unsigned DiagID = 0;
12617   bool NeedType = false;
12618   switch (IsLV) { // C99 6.5.16p2
12619   case Expr::MLV_ConstQualified:
12620     // Use a specialized diagnostic when we're assigning to an object
12621     // from an enclosing function or block.
12622     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12623       if (NCCK == NCCK_Block)
12624         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12625       else
12626         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12627       break;
12628     }
12629 
12630     // In ARC, use some specialized diagnostics for occasions where we
12631     // infer 'const'.  These are always pseudo-strong variables.
12632     if (S.getLangOpts().ObjCAutoRefCount) {
12633       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12634       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12635         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12636 
12637         // Use the normal diagnostic if it's pseudo-__strong but the
12638         // user actually wrote 'const'.
12639         if (var->isARCPseudoStrong() &&
12640             (!var->getTypeSourceInfo() ||
12641              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12642           // There are three pseudo-strong cases:
12643           //  - self
12644           ObjCMethodDecl *method = S.getCurMethodDecl();
12645           if (method && var == method->getSelfDecl()) {
12646             DiagID = method->isClassMethod()
12647               ? diag::err_typecheck_arc_assign_self_class_method
12648               : diag::err_typecheck_arc_assign_self;
12649 
12650           //  - Objective-C externally_retained attribute.
12651           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12652                      isa<ParmVarDecl>(var)) {
12653             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12654 
12655           //  - fast enumeration variables
12656           } else {
12657             DiagID = diag::err_typecheck_arr_assign_enumeration;
12658           }
12659 
12660           SourceRange Assign;
12661           if (Loc != OrigLoc)
12662             Assign = SourceRange(OrigLoc, OrigLoc);
12663           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12664           // We need to preserve the AST regardless, so migration tool
12665           // can do its job.
12666           return false;
12667         }
12668       }
12669     }
12670 
12671     // If none of the special cases above are triggered, then this is a
12672     // simple const assignment.
12673     if (DiagID == 0) {
12674       DiagnoseConstAssignment(S, E, Loc);
12675       return true;
12676     }
12677 
12678     break;
12679   case Expr::MLV_ConstAddrSpace:
12680     DiagnoseConstAssignment(S, E, Loc);
12681     return true;
12682   case Expr::MLV_ConstQualifiedField:
12683     DiagnoseRecursiveConstFields(S, E, Loc);
12684     return true;
12685   case Expr::MLV_ArrayType:
12686   case Expr::MLV_ArrayTemporary:
12687     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12688     NeedType = true;
12689     break;
12690   case Expr::MLV_NotObjectType:
12691     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12692     NeedType = true;
12693     break;
12694   case Expr::MLV_LValueCast:
12695     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12696     break;
12697   case Expr::MLV_Valid:
12698     llvm_unreachable("did not take early return for MLV_Valid");
12699   case Expr::MLV_InvalidExpression:
12700   case Expr::MLV_MemberFunction:
12701   case Expr::MLV_ClassTemporary:
12702     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12703     break;
12704   case Expr::MLV_IncompleteType:
12705   case Expr::MLV_IncompleteVoidType:
12706     return S.RequireCompleteType(Loc, E->getType(),
12707              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12708   case Expr::MLV_DuplicateVectorComponents:
12709     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12710     break;
12711   case Expr::MLV_NoSetterProperty:
12712     llvm_unreachable("readonly properties should be processed differently");
12713   case Expr::MLV_InvalidMessageExpression:
12714     DiagID = diag::err_readonly_message_assignment;
12715     break;
12716   case Expr::MLV_SubObjCPropertySetting:
12717     DiagID = diag::err_no_subobject_property_setting;
12718     break;
12719   }
12720 
12721   SourceRange Assign;
12722   if (Loc != OrigLoc)
12723     Assign = SourceRange(OrigLoc, OrigLoc);
12724   if (NeedType)
12725     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12726   else
12727     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12728   return true;
12729 }
12730 
12731 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12732                                          SourceLocation Loc,
12733                                          Sema &Sema) {
12734   if (Sema.inTemplateInstantiation())
12735     return;
12736   if (Sema.isUnevaluatedContext())
12737     return;
12738   if (Loc.isInvalid() || Loc.isMacroID())
12739     return;
12740   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12741     return;
12742 
12743   // C / C++ fields
12744   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12745   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12746   if (ML && MR) {
12747     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12748       return;
12749     const ValueDecl *LHSDecl =
12750         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12751     const ValueDecl *RHSDecl =
12752         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12753     if (LHSDecl != RHSDecl)
12754       return;
12755     if (LHSDecl->getType().isVolatileQualified())
12756       return;
12757     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12758       if (RefTy->getPointeeType().isVolatileQualified())
12759         return;
12760 
12761     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12762   }
12763 
12764   // Objective-C instance variables
12765   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12766   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12767   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12768     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12769     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12770     if (RL && RR && RL->getDecl() == RR->getDecl())
12771       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12772   }
12773 }
12774 
12775 // C99 6.5.16.1
12776 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12777                                        SourceLocation Loc,
12778                                        QualType CompoundType) {
12779   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12780 
12781   // Verify that LHS is a modifiable lvalue, and emit error if not.
12782   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12783     return QualType();
12784 
12785   QualType LHSType = LHSExpr->getType();
12786   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12787                                              CompoundType;
12788   // OpenCL v1.2 s6.1.1.1 p2:
12789   // The half data type can only be used to declare a pointer to a buffer that
12790   // contains half values
12791   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12792     LHSType->isHalfType()) {
12793     Diag(Loc, diag::err_opencl_half_load_store) << 1
12794         << LHSType.getUnqualifiedType();
12795     return QualType();
12796   }
12797 
12798   AssignConvertType ConvTy;
12799   if (CompoundType.isNull()) {
12800     Expr *RHSCheck = RHS.get();
12801 
12802     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12803 
12804     QualType LHSTy(LHSType);
12805     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12806     if (RHS.isInvalid())
12807       return QualType();
12808     // Special case of NSObject attributes on c-style pointer types.
12809     if (ConvTy == IncompatiblePointer &&
12810         ((Context.isObjCNSObjectType(LHSType) &&
12811           RHSType->isObjCObjectPointerType()) ||
12812          (Context.isObjCNSObjectType(RHSType) &&
12813           LHSType->isObjCObjectPointerType())))
12814       ConvTy = Compatible;
12815 
12816     if (ConvTy == Compatible &&
12817         LHSType->isObjCObjectType())
12818         Diag(Loc, diag::err_objc_object_assignment)
12819           << LHSType;
12820 
12821     // If the RHS is a unary plus or minus, check to see if they = and + are
12822     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12823     // instead of "x += 4".
12824     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12825       RHSCheck = ICE->getSubExpr();
12826     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12827       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12828           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12829           // Only if the two operators are exactly adjacent.
12830           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12831           // And there is a space or other character before the subexpr of the
12832           // unary +/-.  We don't want to warn on "x=-1".
12833           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12834           UO->getSubExpr()->getBeginLoc().isFileID()) {
12835         Diag(Loc, diag::warn_not_compound_assign)
12836           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12837           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12838       }
12839     }
12840 
12841     if (ConvTy == Compatible) {
12842       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12843         // Warn about retain cycles where a block captures the LHS, but
12844         // not if the LHS is a simple variable into which the block is
12845         // being stored...unless that variable can be captured by reference!
12846         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12847         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12848         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12849           checkRetainCycles(LHSExpr, RHS.get());
12850       }
12851 
12852       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12853           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12854         // It is safe to assign a weak reference into a strong variable.
12855         // Although this code can still have problems:
12856         //   id x = self.weakProp;
12857         //   id y = self.weakProp;
12858         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12859         // paths through the function. This should be revisited if
12860         // -Wrepeated-use-of-weak is made flow-sensitive.
12861         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12862         // variable, which will be valid for the current autorelease scope.
12863         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12864                              RHS.get()->getBeginLoc()))
12865           getCurFunction()->markSafeWeakUse(RHS.get());
12866 
12867       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12868         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12869       }
12870     }
12871   } else {
12872     // Compound assignment "x += y"
12873     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12874   }
12875 
12876   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12877                                RHS.get(), AA_Assigning))
12878     return QualType();
12879 
12880   CheckForNullPointerDereference(*this, LHSExpr);
12881 
12882   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12883     if (CompoundType.isNull()) {
12884       // C++2a [expr.ass]p5:
12885       //   A simple-assignment whose left operand is of a volatile-qualified
12886       //   type is deprecated unless the assignment is either a discarded-value
12887       //   expression or an unevaluated operand
12888       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12889     } else {
12890       // C++2a [expr.ass]p6:
12891       //   [Compound-assignment] expressions are deprecated if E1 has
12892       //   volatile-qualified type
12893       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12894     }
12895   }
12896 
12897   // C99 6.5.16p3: The type of an assignment expression is the type of the
12898   // left operand unless the left operand has qualified type, in which case
12899   // it is the unqualified version of the type of the left operand.
12900   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12901   // is converted to the type of the assignment expression (above).
12902   // C++ 5.17p1: the type of the assignment expression is that of its left
12903   // operand.
12904   return (getLangOpts().CPlusPlus
12905           ? LHSType : LHSType.getUnqualifiedType());
12906 }
12907 
12908 // Only ignore explicit casts to void.
12909 static bool IgnoreCommaOperand(const Expr *E) {
12910   E = E->IgnoreParens();
12911 
12912   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12913     if (CE->getCastKind() == CK_ToVoid) {
12914       return true;
12915     }
12916 
12917     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12918     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12919         CE->getSubExpr()->getType()->isDependentType()) {
12920       return true;
12921     }
12922   }
12923 
12924   return false;
12925 }
12926 
12927 // Look for instances where it is likely the comma operator is confused with
12928 // another operator.  There is an explicit list of acceptable expressions for
12929 // the left hand side of the comma operator, otherwise emit a warning.
12930 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12931   // No warnings in macros
12932   if (Loc.isMacroID())
12933     return;
12934 
12935   // Don't warn in template instantiations.
12936   if (inTemplateInstantiation())
12937     return;
12938 
12939   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12940   // instead, skip more than needed, then call back into here with the
12941   // CommaVisitor in SemaStmt.cpp.
12942   // The listed locations are the initialization and increment portions
12943   // of a for loop.  The additional checks are on the condition of
12944   // if statements, do/while loops, and for loops.
12945   // Differences in scope flags for C89 mode requires the extra logic.
12946   const unsigned ForIncrementFlags =
12947       getLangOpts().C99 || getLangOpts().CPlusPlus
12948           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12949           : Scope::ContinueScope | Scope::BreakScope;
12950   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12951   const unsigned ScopeFlags = getCurScope()->getFlags();
12952   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12953       (ScopeFlags & ForInitFlags) == ForInitFlags)
12954     return;
12955 
12956   // If there are multiple comma operators used together, get the RHS of the
12957   // of the comma operator as the LHS.
12958   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12959     if (BO->getOpcode() != BO_Comma)
12960       break;
12961     LHS = BO->getRHS();
12962   }
12963 
12964   // Only allow some expressions on LHS to not warn.
12965   if (IgnoreCommaOperand(LHS))
12966     return;
12967 
12968   Diag(Loc, diag::warn_comma_operator);
12969   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12970       << LHS->getSourceRange()
12971       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12972                                     LangOpts.CPlusPlus ? "static_cast<void>("
12973                                                        : "(void)(")
12974       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12975                                     ")");
12976 }
12977 
12978 // C99 6.5.17
12979 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12980                                    SourceLocation Loc) {
12981   LHS = S.CheckPlaceholderExpr(LHS.get());
12982   RHS = S.CheckPlaceholderExpr(RHS.get());
12983   if (LHS.isInvalid() || RHS.isInvalid())
12984     return QualType();
12985 
12986   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12987   // operands, but not unary promotions.
12988   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12989 
12990   // So we treat the LHS as a ignored value, and in C++ we allow the
12991   // containing site to determine what should be done with the RHS.
12992   LHS = S.IgnoredValueConversions(LHS.get());
12993   if (LHS.isInvalid())
12994     return QualType();
12995 
12996   S.DiagnoseUnusedExprResult(LHS.get());
12997 
12998   if (!S.getLangOpts().CPlusPlus) {
12999     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13000     if (RHS.isInvalid())
13001       return QualType();
13002     if (!RHS.get()->getType()->isVoidType())
13003       S.RequireCompleteType(Loc, RHS.get()->getType(),
13004                             diag::err_incomplete_type);
13005   }
13006 
13007   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13008     S.DiagnoseCommaOperator(LHS.get(), Loc);
13009 
13010   return RHS.get()->getType();
13011 }
13012 
13013 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13014 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13015 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13016                                                ExprValueKind &VK,
13017                                                ExprObjectKind &OK,
13018                                                SourceLocation OpLoc,
13019                                                bool IsInc, bool IsPrefix) {
13020   if (Op->isTypeDependent())
13021     return S.Context.DependentTy;
13022 
13023   QualType ResType = Op->getType();
13024   // Atomic types can be used for increment / decrement where the non-atomic
13025   // versions can, so ignore the _Atomic() specifier for the purpose of
13026   // checking.
13027   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13028     ResType = ResAtomicType->getValueType();
13029 
13030   assert(!ResType.isNull() && "no type for increment/decrement expression");
13031 
13032   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13033     // Decrement of bool is not allowed.
13034     if (!IsInc) {
13035       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13036       return QualType();
13037     }
13038     // Increment of bool sets it to true, but is deprecated.
13039     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13040                                               : diag::warn_increment_bool)
13041       << Op->getSourceRange();
13042   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13043     // Error on enum increments and decrements in C++ mode
13044     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13045     return QualType();
13046   } else if (ResType->isRealType()) {
13047     // OK!
13048   } else if (ResType->isPointerType()) {
13049     // C99 6.5.2.4p2, 6.5.6p2
13050     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13051       return QualType();
13052   } else if (ResType->isObjCObjectPointerType()) {
13053     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13054     // Otherwise, we just need a complete type.
13055     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13056         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13057       return QualType();
13058   } else if (ResType->isAnyComplexType()) {
13059     // C99 does not support ++/-- on complex types, we allow as an extension.
13060     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13061       << ResType << Op->getSourceRange();
13062   } else if (ResType->isPlaceholderType()) {
13063     ExprResult PR = S.CheckPlaceholderExpr(Op);
13064     if (PR.isInvalid()) return QualType();
13065     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13066                                           IsInc, IsPrefix);
13067   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13068     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13069   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13070              (ResType->castAs<VectorType>()->getVectorKind() !=
13071               VectorType::AltiVecBool)) {
13072     // The z vector extensions allow ++ and -- for non-bool vectors.
13073   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13074             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13075     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13076   } else {
13077     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13078       << ResType << int(IsInc) << Op->getSourceRange();
13079     return QualType();
13080   }
13081   // At this point, we know we have a real, complex or pointer type.
13082   // Now make sure the operand is a modifiable lvalue.
13083   if (CheckForModifiableLvalue(Op, OpLoc, S))
13084     return QualType();
13085   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13086     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13087     //   An operand with volatile-qualified type is deprecated
13088     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13089         << IsInc << ResType;
13090   }
13091   // In C++, a prefix increment is the same type as the operand. Otherwise
13092   // (in C or with postfix), the increment is the unqualified type of the
13093   // operand.
13094   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13095     VK = VK_LValue;
13096     OK = Op->getObjectKind();
13097     return ResType;
13098   } else {
13099     VK = VK_RValue;
13100     return ResType.getUnqualifiedType();
13101   }
13102 }
13103 
13104 
13105 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13106 /// This routine allows us to typecheck complex/recursive expressions
13107 /// where the declaration is needed for type checking. We only need to
13108 /// handle cases when the expression references a function designator
13109 /// or is an lvalue. Here are some examples:
13110 ///  - &(x) => x
13111 ///  - &*****f => f for f a function designator.
13112 ///  - &s.xx => s
13113 ///  - &s.zz[1].yy -> s, if zz is an array
13114 ///  - *(x + 1) -> x, if x is an array
13115 ///  - &"123"[2] -> 0
13116 ///  - & __real__ x -> x
13117 ///
13118 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13119 /// members.
13120 static ValueDecl *getPrimaryDecl(Expr *E) {
13121   switch (E->getStmtClass()) {
13122   case Stmt::DeclRefExprClass:
13123     return cast<DeclRefExpr>(E)->getDecl();
13124   case Stmt::MemberExprClass:
13125     // If this is an arrow operator, the address is an offset from
13126     // the base's value, so the object the base refers to is
13127     // irrelevant.
13128     if (cast<MemberExpr>(E)->isArrow())
13129       return nullptr;
13130     // Otherwise, the expression refers to a part of the base
13131     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13132   case Stmt::ArraySubscriptExprClass: {
13133     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13134     // promotion of register arrays earlier.
13135     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13136     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13137       if (ICE->getSubExpr()->getType()->isArrayType())
13138         return getPrimaryDecl(ICE->getSubExpr());
13139     }
13140     return nullptr;
13141   }
13142   case Stmt::UnaryOperatorClass: {
13143     UnaryOperator *UO = cast<UnaryOperator>(E);
13144 
13145     switch(UO->getOpcode()) {
13146     case UO_Real:
13147     case UO_Imag:
13148     case UO_Extension:
13149       return getPrimaryDecl(UO->getSubExpr());
13150     default:
13151       return nullptr;
13152     }
13153   }
13154   case Stmt::ParenExprClass:
13155     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13156   case Stmt::ImplicitCastExprClass:
13157     // If the result of an implicit cast is an l-value, we care about
13158     // the sub-expression; otherwise, the result here doesn't matter.
13159     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13160   case Stmt::CXXUuidofExprClass:
13161     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13162   default:
13163     return nullptr;
13164   }
13165 }
13166 
13167 namespace {
13168 enum {
13169   AO_Bit_Field = 0,
13170   AO_Vector_Element = 1,
13171   AO_Property_Expansion = 2,
13172   AO_Register_Variable = 3,
13173   AO_Matrix_Element = 4,
13174   AO_No_Error = 5
13175 };
13176 }
13177 /// Diagnose invalid operand for address of operations.
13178 ///
13179 /// \param Type The type of operand which cannot have its address taken.
13180 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13181                                          Expr *E, unsigned Type) {
13182   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13183 }
13184 
13185 /// CheckAddressOfOperand - The operand of & must be either a function
13186 /// designator or an lvalue designating an object. If it is an lvalue, the
13187 /// object cannot be declared with storage class register or be a bit field.
13188 /// Note: The usual conversions are *not* applied to the operand of the &
13189 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13190 /// In C++, the operand might be an overloaded function name, in which case
13191 /// we allow the '&' but retain the overloaded-function type.
13192 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13193   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13194     if (PTy->getKind() == BuiltinType::Overload) {
13195       Expr *E = OrigOp.get()->IgnoreParens();
13196       if (!isa<OverloadExpr>(E)) {
13197         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13198         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13199           << OrigOp.get()->getSourceRange();
13200         return QualType();
13201       }
13202 
13203       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13204       if (isa<UnresolvedMemberExpr>(Ovl))
13205         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13206           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13207             << OrigOp.get()->getSourceRange();
13208           return QualType();
13209         }
13210 
13211       return Context.OverloadTy;
13212     }
13213 
13214     if (PTy->getKind() == BuiltinType::UnknownAny)
13215       return Context.UnknownAnyTy;
13216 
13217     if (PTy->getKind() == BuiltinType::BoundMember) {
13218       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13219         << OrigOp.get()->getSourceRange();
13220       return QualType();
13221     }
13222 
13223     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13224     if (OrigOp.isInvalid()) return QualType();
13225   }
13226 
13227   if (OrigOp.get()->isTypeDependent())
13228     return Context.DependentTy;
13229 
13230   assert(!OrigOp.get()->getType()->isPlaceholderType());
13231 
13232   // Make sure to ignore parentheses in subsequent checks
13233   Expr *op = OrigOp.get()->IgnoreParens();
13234 
13235   // In OpenCL captures for blocks called as lambda functions
13236   // are located in the private address space. Blocks used in
13237   // enqueue_kernel can be located in a different address space
13238   // depending on a vendor implementation. Thus preventing
13239   // taking an address of the capture to avoid invalid AS casts.
13240   if (LangOpts.OpenCL) {
13241     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13242     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13243       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13244       return QualType();
13245     }
13246   }
13247 
13248   if (getLangOpts().C99) {
13249     // Implement C99-only parts of addressof rules.
13250     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13251       if (uOp->getOpcode() == UO_Deref)
13252         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13253         // (assuming the deref expression is valid).
13254         return uOp->getSubExpr()->getType();
13255     }
13256     // Technically, there should be a check for array subscript
13257     // expressions here, but the result of one is always an lvalue anyway.
13258   }
13259   ValueDecl *dcl = getPrimaryDecl(op);
13260 
13261   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13262     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13263                                            op->getBeginLoc()))
13264       return QualType();
13265 
13266   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13267   unsigned AddressOfError = AO_No_Error;
13268 
13269   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13270     bool sfinae = (bool)isSFINAEContext();
13271     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13272                                   : diag::ext_typecheck_addrof_temporary)
13273       << op->getType() << op->getSourceRange();
13274     if (sfinae)
13275       return QualType();
13276     // Materialize the temporary as an lvalue so that we can take its address.
13277     OrigOp = op =
13278         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13279   } else if (isa<ObjCSelectorExpr>(op)) {
13280     return Context.getPointerType(op->getType());
13281   } else if (lval == Expr::LV_MemberFunction) {
13282     // If it's an instance method, make a member pointer.
13283     // The expression must have exactly the form &A::foo.
13284 
13285     // If the underlying expression isn't a decl ref, give up.
13286     if (!isa<DeclRefExpr>(op)) {
13287       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13288         << OrigOp.get()->getSourceRange();
13289       return QualType();
13290     }
13291     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13292     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13293 
13294     // The id-expression was parenthesized.
13295     if (OrigOp.get() != DRE) {
13296       Diag(OpLoc, diag::err_parens_pointer_member_function)
13297         << OrigOp.get()->getSourceRange();
13298 
13299     // The method was named without a qualifier.
13300     } else if (!DRE->getQualifier()) {
13301       if (MD->getParent()->getName().empty())
13302         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13303           << op->getSourceRange();
13304       else {
13305         SmallString<32> Str;
13306         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13307         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13308           << op->getSourceRange()
13309           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13310       }
13311     }
13312 
13313     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13314     if (isa<CXXDestructorDecl>(MD))
13315       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13316 
13317     QualType MPTy = Context.getMemberPointerType(
13318         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13319     // Under the MS ABI, lock down the inheritance model now.
13320     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13321       (void)isCompleteType(OpLoc, MPTy);
13322     return MPTy;
13323   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13324     // C99 6.5.3.2p1
13325     // The operand must be either an l-value or a function designator
13326     if (!op->getType()->isFunctionType()) {
13327       // Use a special diagnostic for loads from property references.
13328       if (isa<PseudoObjectExpr>(op)) {
13329         AddressOfError = AO_Property_Expansion;
13330       } else {
13331         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13332           << op->getType() << op->getSourceRange();
13333         return QualType();
13334       }
13335     }
13336   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13337     // The operand cannot be a bit-field
13338     AddressOfError = AO_Bit_Field;
13339   } else if (op->getObjectKind() == OK_VectorComponent) {
13340     // The operand cannot be an element of a vector
13341     AddressOfError = AO_Vector_Element;
13342   } else if (op->getObjectKind() == OK_MatrixComponent) {
13343     // The operand cannot be an element of a matrix.
13344     AddressOfError = AO_Matrix_Element;
13345   } else if (dcl) { // C99 6.5.3.2p1
13346     // We have an lvalue with a decl. Make sure the decl is not declared
13347     // with the register storage-class specifier.
13348     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13349       // in C++ it is not error to take address of a register
13350       // variable (c++03 7.1.1P3)
13351       if (vd->getStorageClass() == SC_Register &&
13352           !getLangOpts().CPlusPlus) {
13353         AddressOfError = AO_Register_Variable;
13354       }
13355     } else if (isa<MSPropertyDecl>(dcl)) {
13356       AddressOfError = AO_Property_Expansion;
13357     } else if (isa<FunctionTemplateDecl>(dcl)) {
13358       return Context.OverloadTy;
13359     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13360       // Okay: we can take the address of a field.
13361       // Could be a pointer to member, though, if there is an explicit
13362       // scope qualifier for the class.
13363       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13364         DeclContext *Ctx = dcl->getDeclContext();
13365         if (Ctx && Ctx->isRecord()) {
13366           if (dcl->getType()->isReferenceType()) {
13367             Diag(OpLoc,
13368                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13369               << dcl->getDeclName() << dcl->getType();
13370             return QualType();
13371           }
13372 
13373           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13374             Ctx = Ctx->getParent();
13375 
13376           QualType MPTy = Context.getMemberPointerType(
13377               op->getType(),
13378               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13379           // Under the MS ABI, lock down the inheritance model now.
13380           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13381             (void)isCompleteType(OpLoc, MPTy);
13382           return MPTy;
13383         }
13384       }
13385     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13386                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13387       llvm_unreachable("Unknown/unexpected decl type");
13388   }
13389 
13390   if (AddressOfError != AO_No_Error) {
13391     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13392     return QualType();
13393   }
13394 
13395   if (lval == Expr::LV_IncompleteVoidType) {
13396     // Taking the address of a void variable is technically illegal, but we
13397     // allow it in cases which are otherwise valid.
13398     // Example: "extern void x; void* y = &x;".
13399     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13400   }
13401 
13402   // If the operand has type "type", the result has type "pointer to type".
13403   if (op->getType()->isObjCObjectType())
13404     return Context.getObjCObjectPointerType(op->getType());
13405 
13406   CheckAddressOfPackedMember(op);
13407 
13408   return Context.getPointerType(op->getType());
13409 }
13410 
13411 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13412   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13413   if (!DRE)
13414     return;
13415   const Decl *D = DRE->getDecl();
13416   if (!D)
13417     return;
13418   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13419   if (!Param)
13420     return;
13421   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13422     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13423       return;
13424   if (FunctionScopeInfo *FD = S.getCurFunction())
13425     if (!FD->ModifiedNonNullParams.count(Param))
13426       FD->ModifiedNonNullParams.insert(Param);
13427 }
13428 
13429 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13430 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13431                                         SourceLocation OpLoc) {
13432   if (Op->isTypeDependent())
13433     return S.Context.DependentTy;
13434 
13435   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13436   if (ConvResult.isInvalid())
13437     return QualType();
13438   Op = ConvResult.get();
13439   QualType OpTy = Op->getType();
13440   QualType Result;
13441 
13442   if (isa<CXXReinterpretCastExpr>(Op)) {
13443     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13444     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13445                                      Op->getSourceRange());
13446   }
13447 
13448   if (const PointerType *PT = OpTy->getAs<PointerType>())
13449   {
13450     Result = PT->getPointeeType();
13451   }
13452   else if (const ObjCObjectPointerType *OPT =
13453              OpTy->getAs<ObjCObjectPointerType>())
13454     Result = OPT->getPointeeType();
13455   else {
13456     ExprResult PR = S.CheckPlaceholderExpr(Op);
13457     if (PR.isInvalid()) return QualType();
13458     if (PR.get() != Op)
13459       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13460   }
13461 
13462   if (Result.isNull()) {
13463     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13464       << OpTy << Op->getSourceRange();
13465     return QualType();
13466   }
13467 
13468   // Note that per both C89 and C99, indirection is always legal, even if Result
13469   // is an incomplete type or void.  It would be possible to warn about
13470   // dereferencing a void pointer, but it's completely well-defined, and such a
13471   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13472   // for pointers to 'void' but is fine for any other pointer type:
13473   //
13474   // C++ [expr.unary.op]p1:
13475   //   [...] the expression to which [the unary * operator] is applied shall
13476   //   be a pointer to an object type, or a pointer to a function type
13477   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13478     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13479       << OpTy << Op->getSourceRange();
13480 
13481   // Dereferences are usually l-values...
13482   VK = VK_LValue;
13483 
13484   // ...except that certain expressions are never l-values in C.
13485   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13486     VK = VK_RValue;
13487 
13488   return Result;
13489 }
13490 
13491 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13492   BinaryOperatorKind Opc;
13493   switch (Kind) {
13494   default: llvm_unreachable("Unknown binop!");
13495   case tok::periodstar:           Opc = BO_PtrMemD; break;
13496   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13497   case tok::star:                 Opc = BO_Mul; break;
13498   case tok::slash:                Opc = BO_Div; break;
13499   case tok::percent:              Opc = BO_Rem; break;
13500   case tok::plus:                 Opc = BO_Add; break;
13501   case tok::minus:                Opc = BO_Sub; break;
13502   case tok::lessless:             Opc = BO_Shl; break;
13503   case tok::greatergreater:       Opc = BO_Shr; break;
13504   case tok::lessequal:            Opc = BO_LE; break;
13505   case tok::less:                 Opc = BO_LT; break;
13506   case tok::greaterequal:         Opc = BO_GE; break;
13507   case tok::greater:              Opc = BO_GT; break;
13508   case tok::exclaimequal:         Opc = BO_NE; break;
13509   case tok::equalequal:           Opc = BO_EQ; break;
13510   case tok::spaceship:            Opc = BO_Cmp; break;
13511   case tok::amp:                  Opc = BO_And; break;
13512   case tok::caret:                Opc = BO_Xor; break;
13513   case tok::pipe:                 Opc = BO_Or; break;
13514   case tok::ampamp:               Opc = BO_LAnd; break;
13515   case tok::pipepipe:             Opc = BO_LOr; break;
13516   case tok::equal:                Opc = BO_Assign; break;
13517   case tok::starequal:            Opc = BO_MulAssign; break;
13518   case tok::slashequal:           Opc = BO_DivAssign; break;
13519   case tok::percentequal:         Opc = BO_RemAssign; break;
13520   case tok::plusequal:            Opc = BO_AddAssign; break;
13521   case tok::minusequal:           Opc = BO_SubAssign; break;
13522   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13523   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13524   case tok::ampequal:             Opc = BO_AndAssign; break;
13525   case tok::caretequal:           Opc = BO_XorAssign; break;
13526   case tok::pipeequal:            Opc = BO_OrAssign; break;
13527   case tok::comma:                Opc = BO_Comma; break;
13528   }
13529   return Opc;
13530 }
13531 
13532 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13533   tok::TokenKind Kind) {
13534   UnaryOperatorKind Opc;
13535   switch (Kind) {
13536   default: llvm_unreachable("Unknown unary op!");
13537   case tok::plusplus:     Opc = UO_PreInc; break;
13538   case tok::minusminus:   Opc = UO_PreDec; break;
13539   case tok::amp:          Opc = UO_AddrOf; break;
13540   case tok::star:         Opc = UO_Deref; break;
13541   case tok::plus:         Opc = UO_Plus; break;
13542   case tok::minus:        Opc = UO_Minus; break;
13543   case tok::tilde:        Opc = UO_Not; break;
13544   case tok::exclaim:      Opc = UO_LNot; break;
13545   case tok::kw___real:    Opc = UO_Real; break;
13546   case tok::kw___imag:    Opc = UO_Imag; break;
13547   case tok::kw___extension__: Opc = UO_Extension; break;
13548   }
13549   return Opc;
13550 }
13551 
13552 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13553 /// This warning suppressed in the event of macro expansions.
13554 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13555                                    SourceLocation OpLoc, bool IsBuiltin) {
13556   if (S.inTemplateInstantiation())
13557     return;
13558   if (S.isUnevaluatedContext())
13559     return;
13560   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13561     return;
13562   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13563   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13564   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13565   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13566   if (!LHSDeclRef || !RHSDeclRef ||
13567       LHSDeclRef->getLocation().isMacroID() ||
13568       RHSDeclRef->getLocation().isMacroID())
13569     return;
13570   const ValueDecl *LHSDecl =
13571     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13572   const ValueDecl *RHSDecl =
13573     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13574   if (LHSDecl != RHSDecl)
13575     return;
13576   if (LHSDecl->getType().isVolatileQualified())
13577     return;
13578   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13579     if (RefTy->getPointeeType().isVolatileQualified())
13580       return;
13581 
13582   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13583                           : diag::warn_self_assignment_overloaded)
13584       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13585       << RHSExpr->getSourceRange();
13586 }
13587 
13588 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13589 /// is usually indicative of introspection within the Objective-C pointer.
13590 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13591                                           SourceLocation OpLoc) {
13592   if (!S.getLangOpts().ObjC)
13593     return;
13594 
13595   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13596   const Expr *LHS = L.get();
13597   const Expr *RHS = R.get();
13598 
13599   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13600     ObjCPointerExpr = LHS;
13601     OtherExpr = RHS;
13602   }
13603   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13604     ObjCPointerExpr = RHS;
13605     OtherExpr = LHS;
13606   }
13607 
13608   // This warning is deliberately made very specific to reduce false
13609   // positives with logic that uses '&' for hashing.  This logic mainly
13610   // looks for code trying to introspect into tagged pointers, which
13611   // code should generally never do.
13612   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13613     unsigned Diag = diag::warn_objc_pointer_masking;
13614     // Determine if we are introspecting the result of performSelectorXXX.
13615     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13616     // Special case messages to -performSelector and friends, which
13617     // can return non-pointer values boxed in a pointer value.
13618     // Some clients may wish to silence warnings in this subcase.
13619     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13620       Selector S = ME->getSelector();
13621       StringRef SelArg0 = S.getNameForSlot(0);
13622       if (SelArg0.startswith("performSelector"))
13623         Diag = diag::warn_objc_pointer_masking_performSelector;
13624     }
13625 
13626     S.Diag(OpLoc, Diag)
13627       << ObjCPointerExpr->getSourceRange();
13628   }
13629 }
13630 
13631 static NamedDecl *getDeclFromExpr(Expr *E) {
13632   if (!E)
13633     return nullptr;
13634   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13635     return DRE->getDecl();
13636   if (auto *ME = dyn_cast<MemberExpr>(E))
13637     return ME->getMemberDecl();
13638   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13639     return IRE->getDecl();
13640   return nullptr;
13641 }
13642 
13643 // This helper function promotes a binary operator's operands (which are of a
13644 // half vector type) to a vector of floats and then truncates the result to
13645 // a vector of either half or short.
13646 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13647                                       BinaryOperatorKind Opc, QualType ResultTy,
13648                                       ExprValueKind VK, ExprObjectKind OK,
13649                                       bool IsCompAssign, SourceLocation OpLoc,
13650                                       FPOptionsOverride FPFeatures) {
13651   auto &Context = S.getASTContext();
13652   assert((isVector(ResultTy, Context.HalfTy) ||
13653           isVector(ResultTy, Context.ShortTy)) &&
13654          "Result must be a vector of half or short");
13655   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13656          isVector(RHS.get()->getType(), Context.HalfTy) &&
13657          "both operands expected to be a half vector");
13658 
13659   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13660   QualType BinOpResTy = RHS.get()->getType();
13661 
13662   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13663   // change BinOpResTy to a vector of ints.
13664   if (isVector(ResultTy, Context.ShortTy))
13665     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13666 
13667   if (IsCompAssign)
13668     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13669                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13670                                           BinOpResTy, BinOpResTy);
13671 
13672   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13673   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13674                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13675   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13676 }
13677 
13678 static std::pair<ExprResult, ExprResult>
13679 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13680                            Expr *RHSExpr) {
13681   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13682   if (!S.getLangOpts().CPlusPlus) {
13683     // C cannot handle TypoExpr nodes on either side of a binop because it
13684     // doesn't handle dependent types properly, so make sure any TypoExprs have
13685     // been dealt with before checking the operands.
13686     LHS = S.CorrectDelayedTyposInExpr(LHS);
13687     RHS = S.CorrectDelayedTyposInExpr(
13688         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13689         [Opc, LHS](Expr *E) {
13690           if (Opc != BO_Assign)
13691             return ExprResult(E);
13692           // Avoid correcting the RHS to the same Expr as the LHS.
13693           Decl *D = getDeclFromExpr(E);
13694           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13695         });
13696   }
13697   return std::make_pair(LHS, RHS);
13698 }
13699 
13700 /// Returns true if conversion between vectors of halfs and vectors of floats
13701 /// is needed.
13702 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13703                                      Expr *E0, Expr *E1 = nullptr) {
13704   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13705       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13706     return false;
13707 
13708   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13709     QualType Ty = E->IgnoreImplicit()->getType();
13710 
13711     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13712     // to vectors of floats. Although the element type of the vectors is __fp16,
13713     // the vectors shouldn't be treated as storage-only types. See the
13714     // discussion here: https://reviews.llvm.org/rG825235c140e7
13715     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13716       if (VT->getVectorKind() == VectorType::NeonVector)
13717         return false;
13718       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13719     }
13720     return false;
13721   };
13722 
13723   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13724 }
13725 
13726 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13727 /// operator @p Opc at location @c TokLoc. This routine only supports
13728 /// built-in operations; ActOnBinOp handles overloaded operators.
13729 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13730                                     BinaryOperatorKind Opc,
13731                                     Expr *LHSExpr, Expr *RHSExpr) {
13732   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13733     // The syntax only allows initializer lists on the RHS of assignment,
13734     // so we don't need to worry about accepting invalid code for
13735     // non-assignment operators.
13736     // C++11 5.17p9:
13737     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13738     //   of x = {} is x = T().
13739     InitializationKind Kind = InitializationKind::CreateDirectList(
13740         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13741     InitializedEntity Entity =
13742         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13743     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13744     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13745     if (Init.isInvalid())
13746       return Init;
13747     RHSExpr = Init.get();
13748   }
13749 
13750   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13751   QualType ResultTy;     // Result type of the binary operator.
13752   // The following two variables are used for compound assignment operators
13753   QualType CompLHSTy;    // Type of LHS after promotions for computation
13754   QualType CompResultTy; // Type of computation result
13755   ExprValueKind VK = VK_RValue;
13756   ExprObjectKind OK = OK_Ordinary;
13757   bool ConvertHalfVec = false;
13758 
13759   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13760   if (!LHS.isUsable() || !RHS.isUsable())
13761     return ExprError();
13762 
13763   if (getLangOpts().OpenCL) {
13764     QualType LHSTy = LHSExpr->getType();
13765     QualType RHSTy = RHSExpr->getType();
13766     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13767     // the ATOMIC_VAR_INIT macro.
13768     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13769       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13770       if (BO_Assign == Opc)
13771         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13772       else
13773         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13774       return ExprError();
13775     }
13776 
13777     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13778     // only with a builtin functions and therefore should be disallowed here.
13779     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13780         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13781         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13782         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13783       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13784       return ExprError();
13785     }
13786   }
13787 
13788   switch (Opc) {
13789   case BO_Assign:
13790     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13791     if (getLangOpts().CPlusPlus &&
13792         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13793       VK = LHS.get()->getValueKind();
13794       OK = LHS.get()->getObjectKind();
13795     }
13796     if (!ResultTy.isNull()) {
13797       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13798       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13799 
13800       // Avoid copying a block to the heap if the block is assigned to a local
13801       // auto variable that is declared in the same scope as the block. This
13802       // optimization is unsafe if the local variable is declared in an outer
13803       // scope. For example:
13804       //
13805       // BlockTy b;
13806       // {
13807       //   b = ^{...};
13808       // }
13809       // // It is unsafe to invoke the block here if it wasn't copied to the
13810       // // heap.
13811       // b();
13812 
13813       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13814         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13815           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13816             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13817               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13818 
13819       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13820         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13821                               NTCUC_Assignment, NTCUK_Copy);
13822     }
13823     RecordModifiableNonNullParam(*this, LHS.get());
13824     break;
13825   case BO_PtrMemD:
13826   case BO_PtrMemI:
13827     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13828                                             Opc == BO_PtrMemI);
13829     break;
13830   case BO_Mul:
13831   case BO_Div:
13832     ConvertHalfVec = true;
13833     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13834                                            Opc == BO_Div);
13835     break;
13836   case BO_Rem:
13837     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13838     break;
13839   case BO_Add:
13840     ConvertHalfVec = true;
13841     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13842     break;
13843   case BO_Sub:
13844     ConvertHalfVec = true;
13845     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13846     break;
13847   case BO_Shl:
13848   case BO_Shr:
13849     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13850     break;
13851   case BO_LE:
13852   case BO_LT:
13853   case BO_GE:
13854   case BO_GT:
13855     ConvertHalfVec = true;
13856     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13857     break;
13858   case BO_EQ:
13859   case BO_NE:
13860     ConvertHalfVec = true;
13861     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13862     break;
13863   case BO_Cmp:
13864     ConvertHalfVec = true;
13865     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13866     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13867     break;
13868   case BO_And:
13869     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13870     LLVM_FALLTHROUGH;
13871   case BO_Xor:
13872   case BO_Or:
13873     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13874     break;
13875   case BO_LAnd:
13876   case BO_LOr:
13877     ConvertHalfVec = true;
13878     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13879     break;
13880   case BO_MulAssign:
13881   case BO_DivAssign:
13882     ConvertHalfVec = true;
13883     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13884                                                Opc == BO_DivAssign);
13885     CompLHSTy = CompResultTy;
13886     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13887       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13888     break;
13889   case BO_RemAssign:
13890     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13891     CompLHSTy = CompResultTy;
13892     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13893       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13894     break;
13895   case BO_AddAssign:
13896     ConvertHalfVec = true;
13897     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13898     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13899       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13900     break;
13901   case BO_SubAssign:
13902     ConvertHalfVec = true;
13903     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13904     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13905       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13906     break;
13907   case BO_ShlAssign:
13908   case BO_ShrAssign:
13909     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13910     CompLHSTy = CompResultTy;
13911     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13912       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13913     break;
13914   case BO_AndAssign:
13915   case BO_OrAssign: // fallthrough
13916     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13917     LLVM_FALLTHROUGH;
13918   case BO_XorAssign:
13919     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13920     CompLHSTy = CompResultTy;
13921     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13922       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13923     break;
13924   case BO_Comma:
13925     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13926     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13927       VK = RHS.get()->getValueKind();
13928       OK = RHS.get()->getObjectKind();
13929     }
13930     break;
13931   }
13932   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13933     return ExprError();
13934 
13935   // Some of the binary operations require promoting operands of half vector to
13936   // float vectors and truncating the result back to half vector. For now, we do
13937   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13938   // arm64).
13939   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13940          isVector(LHS.get()->getType(), Context.HalfTy) &&
13941          "both sides are half vectors or neither sides are");
13942   ConvertHalfVec =
13943       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13944 
13945   // Check for array bounds violations for both sides of the BinaryOperator
13946   CheckArrayAccess(LHS.get());
13947   CheckArrayAccess(RHS.get());
13948 
13949   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13950     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13951                                                  &Context.Idents.get("object_setClass"),
13952                                                  SourceLocation(), LookupOrdinaryName);
13953     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13954       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13955       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13956           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13957                                         "object_setClass(")
13958           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13959                                           ",")
13960           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13961     }
13962     else
13963       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13964   }
13965   else if (const ObjCIvarRefExpr *OIRE =
13966            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13967     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13968 
13969   // Opc is not a compound assignment if CompResultTy is null.
13970   if (CompResultTy.isNull()) {
13971     if (ConvertHalfVec)
13972       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13973                                  OpLoc, CurFPFeatureOverrides());
13974     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13975                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13976   }
13977 
13978   // Handle compound assignments.
13979   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13980       OK_ObjCProperty) {
13981     VK = VK_LValue;
13982     OK = LHS.get()->getObjectKind();
13983   }
13984 
13985   // The LHS is not converted to the result type for fixed-point compound
13986   // assignment as the common type is computed on demand. Reset the CompLHSTy
13987   // to the LHS type we would have gotten after unary conversions.
13988   if (CompResultTy->isFixedPointType())
13989     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13990 
13991   if (ConvertHalfVec)
13992     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13993                                OpLoc, CurFPFeatureOverrides());
13994 
13995   return CompoundAssignOperator::Create(
13996       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13997       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13998 }
13999 
14000 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14001 /// operators are mixed in a way that suggests that the programmer forgot that
14002 /// comparison operators have higher precedence. The most typical example of
14003 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14004 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14005                                       SourceLocation OpLoc, Expr *LHSExpr,
14006                                       Expr *RHSExpr) {
14007   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14008   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14009 
14010   // Check that one of the sides is a comparison operator and the other isn't.
14011   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14012   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14013   if (isLeftComp == isRightComp)
14014     return;
14015 
14016   // Bitwise operations are sometimes used as eager logical ops.
14017   // Don't diagnose this.
14018   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14019   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14020   if (isLeftBitwise || isRightBitwise)
14021     return;
14022 
14023   SourceRange DiagRange = isLeftComp
14024                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14025                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14026   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14027   SourceRange ParensRange =
14028       isLeftComp
14029           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14030           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14031 
14032   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14033     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14034   SuggestParentheses(Self, OpLoc,
14035     Self.PDiag(diag::note_precedence_silence) << OpStr,
14036     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14037   SuggestParentheses(Self, OpLoc,
14038     Self.PDiag(diag::note_precedence_bitwise_first)
14039       << BinaryOperator::getOpcodeStr(Opc),
14040     ParensRange);
14041 }
14042 
14043 /// It accepts a '&&' expr that is inside a '||' one.
14044 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14045 /// in parentheses.
14046 static void
14047 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14048                                        BinaryOperator *Bop) {
14049   assert(Bop->getOpcode() == BO_LAnd);
14050   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14051       << Bop->getSourceRange() << OpLoc;
14052   SuggestParentheses(Self, Bop->getOperatorLoc(),
14053     Self.PDiag(diag::note_precedence_silence)
14054       << Bop->getOpcodeStr(),
14055     Bop->getSourceRange());
14056 }
14057 
14058 /// Returns true if the given expression can be evaluated as a constant
14059 /// 'true'.
14060 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14061   bool Res;
14062   return !E->isValueDependent() &&
14063          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14064 }
14065 
14066 /// Returns true if the given expression can be evaluated as a constant
14067 /// 'false'.
14068 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14069   bool Res;
14070   return !E->isValueDependent() &&
14071          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14072 }
14073 
14074 /// Look for '&&' in the left hand of a '||' expr.
14075 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14076                                              Expr *LHSExpr, Expr *RHSExpr) {
14077   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14078     if (Bop->getOpcode() == BO_LAnd) {
14079       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14080       if (EvaluatesAsFalse(S, RHSExpr))
14081         return;
14082       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14083       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14084         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14085     } else if (Bop->getOpcode() == BO_LOr) {
14086       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14087         // If it's "a || b && 1 || c" we didn't warn earlier for
14088         // "a || b && 1", but warn now.
14089         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14090           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14091       }
14092     }
14093   }
14094 }
14095 
14096 /// Look for '&&' in the right hand of a '||' expr.
14097 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14098                                              Expr *LHSExpr, Expr *RHSExpr) {
14099   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14100     if (Bop->getOpcode() == BO_LAnd) {
14101       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14102       if (EvaluatesAsFalse(S, LHSExpr))
14103         return;
14104       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14105       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14106         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14107     }
14108   }
14109 }
14110 
14111 /// Look for bitwise op in the left or right hand of a bitwise op with
14112 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14113 /// the '&' expression in parentheses.
14114 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14115                                          SourceLocation OpLoc, Expr *SubExpr) {
14116   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14117     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14118       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14119         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14120         << Bop->getSourceRange() << OpLoc;
14121       SuggestParentheses(S, Bop->getOperatorLoc(),
14122         S.PDiag(diag::note_precedence_silence)
14123           << Bop->getOpcodeStr(),
14124         Bop->getSourceRange());
14125     }
14126   }
14127 }
14128 
14129 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14130                                     Expr *SubExpr, StringRef Shift) {
14131   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14132     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14133       StringRef Op = Bop->getOpcodeStr();
14134       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14135           << Bop->getSourceRange() << OpLoc << Shift << Op;
14136       SuggestParentheses(S, Bop->getOperatorLoc(),
14137           S.PDiag(diag::note_precedence_silence) << Op,
14138           Bop->getSourceRange());
14139     }
14140   }
14141 }
14142 
14143 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14144                                  Expr *LHSExpr, Expr *RHSExpr) {
14145   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14146   if (!OCE)
14147     return;
14148 
14149   FunctionDecl *FD = OCE->getDirectCallee();
14150   if (!FD || !FD->isOverloadedOperator())
14151     return;
14152 
14153   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14154   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14155     return;
14156 
14157   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14158       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14159       << (Kind == OO_LessLess);
14160   SuggestParentheses(S, OCE->getOperatorLoc(),
14161                      S.PDiag(diag::note_precedence_silence)
14162                          << (Kind == OO_LessLess ? "<<" : ">>"),
14163                      OCE->getSourceRange());
14164   SuggestParentheses(
14165       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14166       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14167 }
14168 
14169 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14170 /// precedence.
14171 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14172                                     SourceLocation OpLoc, Expr *LHSExpr,
14173                                     Expr *RHSExpr){
14174   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14175   if (BinaryOperator::isBitwiseOp(Opc))
14176     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14177 
14178   // Diagnose "arg1 & arg2 | arg3"
14179   if ((Opc == BO_Or || Opc == BO_Xor) &&
14180       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14181     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14182     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14183   }
14184 
14185   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14186   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14187   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14188     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14189     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14190   }
14191 
14192   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14193       || Opc == BO_Shr) {
14194     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14195     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14196     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14197   }
14198 
14199   // Warn on overloaded shift operators and comparisons, such as:
14200   // cout << 5 == 4;
14201   if (BinaryOperator::isComparisonOp(Opc))
14202     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14203 }
14204 
14205 // Binary Operators.  'Tok' is the token for the operator.
14206 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14207                             tok::TokenKind Kind,
14208                             Expr *LHSExpr, Expr *RHSExpr) {
14209   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14210   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14211   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14212 
14213   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14214   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14215 
14216   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14217 }
14218 
14219 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14220                        UnresolvedSetImpl &Functions) {
14221   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14222   if (OverOp != OO_None && OverOp != OO_Equal)
14223     LookupOverloadedOperatorName(OverOp, S, Functions);
14224 
14225   // In C++20 onwards, we may have a second operator to look up.
14226   if (getLangOpts().CPlusPlus20) {
14227     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14228       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14229   }
14230 }
14231 
14232 /// Build an overloaded binary operator expression in the given scope.
14233 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14234                                        BinaryOperatorKind Opc,
14235                                        Expr *LHS, Expr *RHS) {
14236   switch (Opc) {
14237   case BO_Assign:
14238   case BO_DivAssign:
14239   case BO_RemAssign:
14240   case BO_SubAssign:
14241   case BO_AndAssign:
14242   case BO_OrAssign:
14243   case BO_XorAssign:
14244     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14245     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14246     break;
14247   default:
14248     break;
14249   }
14250 
14251   // Find all of the overloaded operators visible from this point.
14252   UnresolvedSet<16> Functions;
14253   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14254 
14255   // Build the (potentially-overloaded, potentially-dependent)
14256   // binary operation.
14257   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14258 }
14259 
14260 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14261                             BinaryOperatorKind Opc,
14262                             Expr *LHSExpr, Expr *RHSExpr) {
14263   ExprResult LHS, RHS;
14264   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14265   if (!LHS.isUsable() || !RHS.isUsable())
14266     return ExprError();
14267   LHSExpr = LHS.get();
14268   RHSExpr = RHS.get();
14269 
14270   // We want to end up calling one of checkPseudoObjectAssignment
14271   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14272   // both expressions are overloadable or either is type-dependent),
14273   // or CreateBuiltinBinOp (in any other case).  We also want to get
14274   // any placeholder types out of the way.
14275 
14276   // Handle pseudo-objects in the LHS.
14277   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14278     // Assignments with a pseudo-object l-value need special analysis.
14279     if (pty->getKind() == BuiltinType::PseudoObject &&
14280         BinaryOperator::isAssignmentOp(Opc))
14281       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14282 
14283     // Don't resolve overloads if the other type is overloadable.
14284     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14285       // We can't actually test that if we still have a placeholder,
14286       // though.  Fortunately, none of the exceptions we see in that
14287       // code below are valid when the LHS is an overload set.  Note
14288       // that an overload set can be dependently-typed, but it never
14289       // instantiates to having an overloadable type.
14290       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14291       if (resolvedRHS.isInvalid()) return ExprError();
14292       RHSExpr = resolvedRHS.get();
14293 
14294       if (RHSExpr->isTypeDependent() ||
14295           RHSExpr->getType()->isOverloadableType())
14296         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14297     }
14298 
14299     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14300     // template, diagnose the missing 'template' keyword instead of diagnosing
14301     // an invalid use of a bound member function.
14302     //
14303     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14304     // to C++1z [over.over]/1.4, but we already checked for that case above.
14305     if (Opc == BO_LT && inTemplateInstantiation() &&
14306         (pty->getKind() == BuiltinType::BoundMember ||
14307          pty->getKind() == BuiltinType::Overload)) {
14308       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14309       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14310           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14311             return isa<FunctionTemplateDecl>(ND);
14312           })) {
14313         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14314                                 : OE->getNameLoc(),
14315              diag::err_template_kw_missing)
14316           << OE->getName().getAsString() << "";
14317         return ExprError();
14318       }
14319     }
14320 
14321     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14322     if (LHS.isInvalid()) return ExprError();
14323     LHSExpr = LHS.get();
14324   }
14325 
14326   // Handle pseudo-objects in the RHS.
14327   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14328     // An overload in the RHS can potentially be resolved by the type
14329     // being assigned to.
14330     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14331       if (getLangOpts().CPlusPlus &&
14332           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14333            LHSExpr->getType()->isOverloadableType()))
14334         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14335 
14336       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14337     }
14338 
14339     // Don't resolve overloads if the other type is overloadable.
14340     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14341         LHSExpr->getType()->isOverloadableType())
14342       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14343 
14344     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14345     if (!resolvedRHS.isUsable()) return ExprError();
14346     RHSExpr = resolvedRHS.get();
14347   }
14348 
14349   if (getLangOpts().CPlusPlus) {
14350     // If either expression is type-dependent, always build an
14351     // overloaded op.
14352     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14353       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14354 
14355     // Otherwise, build an overloaded op if either expression has an
14356     // overloadable type.
14357     if (LHSExpr->getType()->isOverloadableType() ||
14358         RHSExpr->getType()->isOverloadableType())
14359       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14360   }
14361 
14362   // Build a built-in binary operation.
14363   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14364 }
14365 
14366 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14367   if (T.isNull() || T->isDependentType())
14368     return false;
14369 
14370   if (!T->isPromotableIntegerType())
14371     return true;
14372 
14373   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14374 }
14375 
14376 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14377                                       UnaryOperatorKind Opc,
14378                                       Expr *InputExpr) {
14379   ExprResult Input = InputExpr;
14380   ExprValueKind VK = VK_RValue;
14381   ExprObjectKind OK = OK_Ordinary;
14382   QualType resultType;
14383   bool CanOverflow = false;
14384 
14385   bool ConvertHalfVec = false;
14386   if (getLangOpts().OpenCL) {
14387     QualType Ty = InputExpr->getType();
14388     // The only legal unary operation for atomics is '&'.
14389     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14390     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14391     // only with a builtin functions and therefore should be disallowed here.
14392         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14393         || Ty->isBlockPointerType())) {
14394       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14395                        << InputExpr->getType()
14396                        << Input.get()->getSourceRange());
14397     }
14398   }
14399 
14400   switch (Opc) {
14401   case UO_PreInc:
14402   case UO_PreDec:
14403   case UO_PostInc:
14404   case UO_PostDec:
14405     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14406                                                 OpLoc,
14407                                                 Opc == UO_PreInc ||
14408                                                 Opc == UO_PostInc,
14409                                                 Opc == UO_PreInc ||
14410                                                 Opc == UO_PreDec);
14411     CanOverflow = isOverflowingIntegerType(Context, resultType);
14412     break;
14413   case UO_AddrOf:
14414     resultType = CheckAddressOfOperand(Input, OpLoc);
14415     CheckAddressOfNoDeref(InputExpr);
14416     RecordModifiableNonNullParam(*this, InputExpr);
14417     break;
14418   case UO_Deref: {
14419     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14420     if (Input.isInvalid()) return ExprError();
14421     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14422     break;
14423   }
14424   case UO_Plus:
14425   case UO_Minus:
14426     CanOverflow = Opc == UO_Minus &&
14427                   isOverflowingIntegerType(Context, Input.get()->getType());
14428     Input = UsualUnaryConversions(Input.get());
14429     if (Input.isInvalid()) return ExprError();
14430     // Unary plus and minus require promoting an operand of half vector to a
14431     // float vector and truncating the result back to a half vector. For now, we
14432     // do this only when HalfArgsAndReturns is set (that is, when the target is
14433     // arm or arm64).
14434     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14435 
14436     // If the operand is a half vector, promote it to a float vector.
14437     if (ConvertHalfVec)
14438       Input = convertVector(Input.get(), Context.FloatTy, *this);
14439     resultType = Input.get()->getType();
14440     if (resultType->isDependentType())
14441       break;
14442     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14443       break;
14444     else if (resultType->isVectorType() &&
14445              // The z vector extensions don't allow + or - with bool vectors.
14446              (!Context.getLangOpts().ZVector ||
14447               resultType->castAs<VectorType>()->getVectorKind() !=
14448               VectorType::AltiVecBool))
14449       break;
14450     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14451              Opc == UO_Plus &&
14452              resultType->isPointerType())
14453       break;
14454 
14455     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14456       << resultType << Input.get()->getSourceRange());
14457 
14458   case UO_Not: // bitwise complement
14459     Input = UsualUnaryConversions(Input.get());
14460     if (Input.isInvalid())
14461       return ExprError();
14462     resultType = Input.get()->getType();
14463     if (resultType->isDependentType())
14464       break;
14465     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14466     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14467       // C99 does not support '~' for complex conjugation.
14468       Diag(OpLoc, diag::ext_integer_complement_complex)
14469           << resultType << Input.get()->getSourceRange();
14470     else if (resultType->hasIntegerRepresentation())
14471       break;
14472     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14473       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14474       // on vector float types.
14475       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14476       if (!T->isIntegerType())
14477         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14478                           << resultType << Input.get()->getSourceRange());
14479     } else {
14480       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14481                        << resultType << Input.get()->getSourceRange());
14482     }
14483     break;
14484 
14485   case UO_LNot: // logical negation
14486     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14487     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14488     if (Input.isInvalid()) return ExprError();
14489     resultType = Input.get()->getType();
14490 
14491     // Though we still have to promote half FP to float...
14492     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14493       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14494       resultType = Context.FloatTy;
14495     }
14496 
14497     if (resultType->isDependentType())
14498       break;
14499     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14500       // C99 6.5.3.3p1: ok, fallthrough;
14501       if (Context.getLangOpts().CPlusPlus) {
14502         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14503         // operand contextually converted to bool.
14504         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14505                                   ScalarTypeToBooleanCastKind(resultType));
14506       } else if (Context.getLangOpts().OpenCL &&
14507                  Context.getLangOpts().OpenCLVersion < 120) {
14508         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14509         // operate on scalar float types.
14510         if (!resultType->isIntegerType() && !resultType->isPointerType())
14511           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14512                            << resultType << Input.get()->getSourceRange());
14513       }
14514     } else if (resultType->isExtVectorType()) {
14515       if (Context.getLangOpts().OpenCL &&
14516           Context.getLangOpts().OpenCLVersion < 120 &&
14517           !Context.getLangOpts().OpenCLCPlusPlus) {
14518         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14519         // operate on vector float types.
14520         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14521         if (!T->isIntegerType())
14522           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14523                            << resultType << Input.get()->getSourceRange());
14524       }
14525       // Vector logical not returns the signed variant of the operand type.
14526       resultType = GetSignedVectorType(resultType);
14527       break;
14528     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14529       const VectorType *VTy = resultType->castAs<VectorType>();
14530       if (VTy->getVectorKind() != VectorType::GenericVector)
14531         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14532                          << resultType << Input.get()->getSourceRange());
14533 
14534       // Vector logical not returns the signed variant of the operand type.
14535       resultType = GetSignedVectorType(resultType);
14536       break;
14537     } else {
14538       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14539         << resultType << Input.get()->getSourceRange());
14540     }
14541 
14542     // LNot always has type int. C99 6.5.3.3p5.
14543     // In C++, it's bool. C++ 5.3.1p8
14544     resultType = Context.getLogicalOperationType();
14545     break;
14546   case UO_Real:
14547   case UO_Imag:
14548     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14549     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14550     // complex l-values to ordinary l-values and all other values to r-values.
14551     if (Input.isInvalid()) return ExprError();
14552     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14553       if (Input.get()->getValueKind() != VK_RValue &&
14554           Input.get()->getObjectKind() == OK_Ordinary)
14555         VK = Input.get()->getValueKind();
14556     } else if (!getLangOpts().CPlusPlus) {
14557       // In C, a volatile scalar is read by __imag. In C++, it is not.
14558       Input = DefaultLvalueConversion(Input.get());
14559     }
14560     break;
14561   case UO_Extension:
14562     resultType = Input.get()->getType();
14563     VK = Input.get()->getValueKind();
14564     OK = Input.get()->getObjectKind();
14565     break;
14566   case UO_Coawait:
14567     // It's unnecessary to represent the pass-through operator co_await in the
14568     // AST; just return the input expression instead.
14569     assert(!Input.get()->getType()->isDependentType() &&
14570                    "the co_await expression must be non-dependant before "
14571                    "building operator co_await");
14572     return Input;
14573   }
14574   if (resultType.isNull() || Input.isInvalid())
14575     return ExprError();
14576 
14577   // Check for array bounds violations in the operand of the UnaryOperator,
14578   // except for the '*' and '&' operators that have to be handled specially
14579   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14580   // that are explicitly defined as valid by the standard).
14581   if (Opc != UO_AddrOf && Opc != UO_Deref)
14582     CheckArrayAccess(Input.get());
14583 
14584   auto *UO =
14585       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14586                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14587 
14588   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14589       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14590     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14591 
14592   // Convert the result back to a half vector.
14593   if (ConvertHalfVec)
14594     return convertVector(UO, Context.HalfTy, *this);
14595   return UO;
14596 }
14597 
14598 /// Determine whether the given expression is a qualified member
14599 /// access expression, of a form that could be turned into a pointer to member
14600 /// with the address-of operator.
14601 bool Sema::isQualifiedMemberAccess(Expr *E) {
14602   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14603     if (!DRE->getQualifier())
14604       return false;
14605 
14606     ValueDecl *VD = DRE->getDecl();
14607     if (!VD->isCXXClassMember())
14608       return false;
14609 
14610     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14611       return true;
14612     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14613       return Method->isInstance();
14614 
14615     return false;
14616   }
14617 
14618   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14619     if (!ULE->getQualifier())
14620       return false;
14621 
14622     for (NamedDecl *D : ULE->decls()) {
14623       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14624         if (Method->isInstance())
14625           return true;
14626       } else {
14627         // Overload set does not contain methods.
14628         break;
14629       }
14630     }
14631 
14632     return false;
14633   }
14634 
14635   return false;
14636 }
14637 
14638 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14639                               UnaryOperatorKind Opc, Expr *Input) {
14640   // First things first: handle placeholders so that the
14641   // overloaded-operator check considers the right type.
14642   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14643     // Increment and decrement of pseudo-object references.
14644     if (pty->getKind() == BuiltinType::PseudoObject &&
14645         UnaryOperator::isIncrementDecrementOp(Opc))
14646       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14647 
14648     // extension is always a builtin operator.
14649     if (Opc == UO_Extension)
14650       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14651 
14652     // & gets special logic for several kinds of placeholder.
14653     // The builtin code knows what to do.
14654     if (Opc == UO_AddrOf &&
14655         (pty->getKind() == BuiltinType::Overload ||
14656          pty->getKind() == BuiltinType::UnknownAny ||
14657          pty->getKind() == BuiltinType::BoundMember))
14658       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14659 
14660     // Anything else needs to be handled now.
14661     ExprResult Result = CheckPlaceholderExpr(Input);
14662     if (Result.isInvalid()) return ExprError();
14663     Input = Result.get();
14664   }
14665 
14666   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14667       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14668       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14669     // Find all of the overloaded operators visible from this point.
14670     UnresolvedSet<16> Functions;
14671     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14672     if (S && OverOp != OO_None)
14673       LookupOverloadedOperatorName(OverOp, S, Functions);
14674 
14675     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14676   }
14677 
14678   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14679 }
14680 
14681 // Unary Operators.  'Tok' is the token for the operator.
14682 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14683                               tok::TokenKind Op, Expr *Input) {
14684   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14685 }
14686 
14687 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14688 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14689                                 LabelDecl *TheDecl) {
14690   TheDecl->markUsed(Context);
14691   // Create the AST node.  The address of a label always has type 'void*'.
14692   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14693                                      Context.getPointerType(Context.VoidTy));
14694 }
14695 
14696 void Sema::ActOnStartStmtExpr() {
14697   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14698 }
14699 
14700 void Sema::ActOnStmtExprError() {
14701   // Note that function is also called by TreeTransform when leaving a
14702   // StmtExpr scope without rebuilding anything.
14703 
14704   DiscardCleanupsInEvaluationContext();
14705   PopExpressionEvaluationContext();
14706 }
14707 
14708 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14709                                SourceLocation RPLoc) {
14710   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14711 }
14712 
14713 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14714                                SourceLocation RPLoc, unsigned TemplateDepth) {
14715   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14716   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14717 
14718   if (hasAnyUnrecoverableErrorsInThisFunction())
14719     DiscardCleanupsInEvaluationContext();
14720   assert(!Cleanup.exprNeedsCleanups() &&
14721          "cleanups within StmtExpr not correctly bound!");
14722   PopExpressionEvaluationContext();
14723 
14724   // FIXME: there are a variety of strange constraints to enforce here, for
14725   // example, it is not possible to goto into a stmt expression apparently.
14726   // More semantic analysis is needed.
14727 
14728   // If there are sub-stmts in the compound stmt, take the type of the last one
14729   // as the type of the stmtexpr.
14730   QualType Ty = Context.VoidTy;
14731   bool StmtExprMayBindToTemp = false;
14732   if (!Compound->body_empty()) {
14733     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14734     if (const auto *LastStmt =
14735             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14736       if (const Expr *Value = LastStmt->getExprStmt()) {
14737         StmtExprMayBindToTemp = true;
14738         Ty = Value->getType();
14739       }
14740     }
14741   }
14742 
14743   // FIXME: Check that expression type is complete/non-abstract; statement
14744   // expressions are not lvalues.
14745   Expr *ResStmtExpr =
14746       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14747   if (StmtExprMayBindToTemp)
14748     return MaybeBindToTemporary(ResStmtExpr);
14749   return ResStmtExpr;
14750 }
14751 
14752 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14753   if (ER.isInvalid())
14754     return ExprError();
14755 
14756   // Do function/array conversion on the last expression, but not
14757   // lvalue-to-rvalue.  However, initialize an unqualified type.
14758   ER = DefaultFunctionArrayConversion(ER.get());
14759   if (ER.isInvalid())
14760     return ExprError();
14761   Expr *E = ER.get();
14762 
14763   if (E->isTypeDependent())
14764     return E;
14765 
14766   // In ARC, if the final expression ends in a consume, splice
14767   // the consume out and bind it later.  In the alternate case
14768   // (when dealing with a retainable type), the result
14769   // initialization will create a produce.  In both cases the
14770   // result will be +1, and we'll need to balance that out with
14771   // a bind.
14772   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14773   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14774     return Cast->getSubExpr();
14775 
14776   // FIXME: Provide a better location for the initialization.
14777   return PerformCopyInitialization(
14778       InitializedEntity::InitializeStmtExprResult(
14779           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14780       SourceLocation(), E);
14781 }
14782 
14783 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14784                                       TypeSourceInfo *TInfo,
14785                                       ArrayRef<OffsetOfComponent> Components,
14786                                       SourceLocation RParenLoc) {
14787   QualType ArgTy = TInfo->getType();
14788   bool Dependent = ArgTy->isDependentType();
14789   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14790 
14791   // We must have at least one component that refers to the type, and the first
14792   // one is known to be a field designator.  Verify that the ArgTy represents
14793   // a struct/union/class.
14794   if (!Dependent && !ArgTy->isRecordType())
14795     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14796                        << ArgTy << TypeRange);
14797 
14798   // Type must be complete per C99 7.17p3 because a declaring a variable
14799   // with an incomplete type would be ill-formed.
14800   if (!Dependent
14801       && RequireCompleteType(BuiltinLoc, ArgTy,
14802                              diag::err_offsetof_incomplete_type, TypeRange))
14803     return ExprError();
14804 
14805   bool DidWarnAboutNonPOD = false;
14806   QualType CurrentType = ArgTy;
14807   SmallVector<OffsetOfNode, 4> Comps;
14808   SmallVector<Expr*, 4> Exprs;
14809   for (const OffsetOfComponent &OC : Components) {
14810     if (OC.isBrackets) {
14811       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14812       if (!CurrentType->isDependentType()) {
14813         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14814         if(!AT)
14815           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14816                            << CurrentType);
14817         CurrentType = AT->getElementType();
14818       } else
14819         CurrentType = Context.DependentTy;
14820 
14821       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14822       if (IdxRval.isInvalid())
14823         return ExprError();
14824       Expr *Idx = IdxRval.get();
14825 
14826       // The expression must be an integral expression.
14827       // FIXME: An integral constant expression?
14828       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14829           !Idx->getType()->isIntegerType())
14830         return ExprError(
14831             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14832             << Idx->getSourceRange());
14833 
14834       // Record this array index.
14835       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14836       Exprs.push_back(Idx);
14837       continue;
14838     }
14839 
14840     // Offset of a field.
14841     if (CurrentType->isDependentType()) {
14842       // We have the offset of a field, but we can't look into the dependent
14843       // type. Just record the identifier of the field.
14844       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14845       CurrentType = Context.DependentTy;
14846       continue;
14847     }
14848 
14849     // We need to have a complete type to look into.
14850     if (RequireCompleteType(OC.LocStart, CurrentType,
14851                             diag::err_offsetof_incomplete_type))
14852       return ExprError();
14853 
14854     // Look for the designated field.
14855     const RecordType *RC = CurrentType->getAs<RecordType>();
14856     if (!RC)
14857       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14858                        << CurrentType);
14859     RecordDecl *RD = RC->getDecl();
14860 
14861     // C++ [lib.support.types]p5:
14862     //   The macro offsetof accepts a restricted set of type arguments in this
14863     //   International Standard. type shall be a POD structure or a POD union
14864     //   (clause 9).
14865     // C++11 [support.types]p4:
14866     //   If type is not a standard-layout class (Clause 9), the results are
14867     //   undefined.
14868     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14869       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14870       unsigned DiagID =
14871         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14872                             : diag::ext_offsetof_non_pod_type;
14873 
14874       if (!IsSafe && !DidWarnAboutNonPOD &&
14875           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14876                               PDiag(DiagID)
14877                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14878                               << CurrentType))
14879         DidWarnAboutNonPOD = true;
14880     }
14881 
14882     // Look for the field.
14883     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14884     LookupQualifiedName(R, RD);
14885     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14886     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14887     if (!MemberDecl) {
14888       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14889         MemberDecl = IndirectMemberDecl->getAnonField();
14890     }
14891 
14892     if (!MemberDecl)
14893       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14894                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14895                                                               OC.LocEnd));
14896 
14897     // C99 7.17p3:
14898     //   (If the specified member is a bit-field, the behavior is undefined.)
14899     //
14900     // We diagnose this as an error.
14901     if (MemberDecl->isBitField()) {
14902       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14903         << MemberDecl->getDeclName()
14904         << SourceRange(BuiltinLoc, RParenLoc);
14905       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14906       return ExprError();
14907     }
14908 
14909     RecordDecl *Parent = MemberDecl->getParent();
14910     if (IndirectMemberDecl)
14911       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14912 
14913     // If the member was found in a base class, introduce OffsetOfNodes for
14914     // the base class indirections.
14915     CXXBasePaths Paths;
14916     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14917                       Paths)) {
14918       if (Paths.getDetectedVirtual()) {
14919         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14920           << MemberDecl->getDeclName()
14921           << SourceRange(BuiltinLoc, RParenLoc);
14922         return ExprError();
14923       }
14924 
14925       CXXBasePath &Path = Paths.front();
14926       for (const CXXBasePathElement &B : Path)
14927         Comps.push_back(OffsetOfNode(B.Base));
14928     }
14929 
14930     if (IndirectMemberDecl) {
14931       for (auto *FI : IndirectMemberDecl->chain()) {
14932         assert(isa<FieldDecl>(FI));
14933         Comps.push_back(OffsetOfNode(OC.LocStart,
14934                                      cast<FieldDecl>(FI), OC.LocEnd));
14935       }
14936     } else
14937       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14938 
14939     CurrentType = MemberDecl->getType().getNonReferenceType();
14940   }
14941 
14942   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14943                               Comps, Exprs, RParenLoc);
14944 }
14945 
14946 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14947                                       SourceLocation BuiltinLoc,
14948                                       SourceLocation TypeLoc,
14949                                       ParsedType ParsedArgTy,
14950                                       ArrayRef<OffsetOfComponent> Components,
14951                                       SourceLocation RParenLoc) {
14952 
14953   TypeSourceInfo *ArgTInfo;
14954   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14955   if (ArgTy.isNull())
14956     return ExprError();
14957 
14958   if (!ArgTInfo)
14959     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14960 
14961   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14962 }
14963 
14964 
14965 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14966                                  Expr *CondExpr,
14967                                  Expr *LHSExpr, Expr *RHSExpr,
14968                                  SourceLocation RPLoc) {
14969   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14970 
14971   ExprValueKind VK = VK_RValue;
14972   ExprObjectKind OK = OK_Ordinary;
14973   QualType resType;
14974   bool CondIsTrue = false;
14975   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14976     resType = Context.DependentTy;
14977   } else {
14978     // The conditional expression is required to be a constant expression.
14979     llvm::APSInt condEval(32);
14980     ExprResult CondICE
14981       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14982           diag::err_typecheck_choose_expr_requires_constant, false);
14983     if (CondICE.isInvalid())
14984       return ExprError();
14985     CondExpr = CondICE.get();
14986     CondIsTrue = condEval.getZExtValue();
14987 
14988     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14989     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14990 
14991     resType = ActiveExpr->getType();
14992     VK = ActiveExpr->getValueKind();
14993     OK = ActiveExpr->getObjectKind();
14994   }
14995 
14996   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14997                                   resType, VK, OK, RPLoc, CondIsTrue);
14998 }
14999 
15000 //===----------------------------------------------------------------------===//
15001 // Clang Extensions.
15002 //===----------------------------------------------------------------------===//
15003 
15004 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15005 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15006   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15007 
15008   if (LangOpts.CPlusPlus) {
15009     MangleNumberingContext *MCtx;
15010     Decl *ManglingContextDecl;
15011     std::tie(MCtx, ManglingContextDecl) =
15012         getCurrentMangleNumberContext(Block->getDeclContext());
15013     if (MCtx) {
15014       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15015       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15016     }
15017   }
15018 
15019   PushBlockScope(CurScope, Block);
15020   CurContext->addDecl(Block);
15021   if (CurScope)
15022     PushDeclContext(CurScope, Block);
15023   else
15024     CurContext = Block;
15025 
15026   getCurBlock()->HasImplicitReturnType = true;
15027 
15028   // Enter a new evaluation context to insulate the block from any
15029   // cleanups from the enclosing full-expression.
15030   PushExpressionEvaluationContext(
15031       ExpressionEvaluationContext::PotentiallyEvaluated);
15032 }
15033 
15034 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15035                                Scope *CurScope) {
15036   assert(ParamInfo.getIdentifier() == nullptr &&
15037          "block-id should have no identifier!");
15038   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15039   BlockScopeInfo *CurBlock = getCurBlock();
15040 
15041   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15042   QualType T = Sig->getType();
15043 
15044   // FIXME: We should allow unexpanded parameter packs here, but that would,
15045   // in turn, make the block expression contain unexpanded parameter packs.
15046   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15047     // Drop the parameters.
15048     FunctionProtoType::ExtProtoInfo EPI;
15049     EPI.HasTrailingReturn = false;
15050     EPI.TypeQuals.addConst();
15051     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15052     Sig = Context.getTrivialTypeSourceInfo(T);
15053   }
15054 
15055   // GetTypeForDeclarator always produces a function type for a block
15056   // literal signature.  Furthermore, it is always a FunctionProtoType
15057   // unless the function was written with a typedef.
15058   assert(T->isFunctionType() &&
15059          "GetTypeForDeclarator made a non-function block signature");
15060 
15061   // Look for an explicit signature in that function type.
15062   FunctionProtoTypeLoc ExplicitSignature;
15063 
15064   if ((ExplicitSignature = Sig->getTypeLoc()
15065                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15066 
15067     // Check whether that explicit signature was synthesized by
15068     // GetTypeForDeclarator.  If so, don't save that as part of the
15069     // written signature.
15070     if (ExplicitSignature.getLocalRangeBegin() ==
15071         ExplicitSignature.getLocalRangeEnd()) {
15072       // This would be much cheaper if we stored TypeLocs instead of
15073       // TypeSourceInfos.
15074       TypeLoc Result = ExplicitSignature.getReturnLoc();
15075       unsigned Size = Result.getFullDataSize();
15076       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15077       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15078 
15079       ExplicitSignature = FunctionProtoTypeLoc();
15080     }
15081   }
15082 
15083   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15084   CurBlock->FunctionType = T;
15085 
15086   const FunctionType *Fn = T->getAs<FunctionType>();
15087   QualType RetTy = Fn->getReturnType();
15088   bool isVariadic =
15089     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15090 
15091   CurBlock->TheDecl->setIsVariadic(isVariadic);
15092 
15093   // Context.DependentTy is used as a placeholder for a missing block
15094   // return type.  TODO:  what should we do with declarators like:
15095   //   ^ * { ... }
15096   // If the answer is "apply template argument deduction"....
15097   if (RetTy != Context.DependentTy) {
15098     CurBlock->ReturnType = RetTy;
15099     CurBlock->TheDecl->setBlockMissingReturnType(false);
15100     CurBlock->HasImplicitReturnType = false;
15101   }
15102 
15103   // Push block parameters from the declarator if we had them.
15104   SmallVector<ParmVarDecl*, 8> Params;
15105   if (ExplicitSignature) {
15106     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15107       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15108       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15109           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15110         // Diagnose this as an extension in C17 and earlier.
15111         if (!getLangOpts().C2x)
15112           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15113       }
15114       Params.push_back(Param);
15115     }
15116 
15117   // Fake up parameter variables if we have a typedef, like
15118   //   ^ fntype { ... }
15119   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15120     for (const auto &I : Fn->param_types()) {
15121       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15122           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15123       Params.push_back(Param);
15124     }
15125   }
15126 
15127   // Set the parameters on the block decl.
15128   if (!Params.empty()) {
15129     CurBlock->TheDecl->setParams(Params);
15130     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15131                              /*CheckParameterNames=*/false);
15132   }
15133 
15134   // Finally we can process decl attributes.
15135   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15136 
15137   // Put the parameter variables in scope.
15138   for (auto AI : CurBlock->TheDecl->parameters()) {
15139     AI->setOwningFunction(CurBlock->TheDecl);
15140 
15141     // If this has an identifier, add it to the scope stack.
15142     if (AI->getIdentifier()) {
15143       CheckShadow(CurBlock->TheScope, AI);
15144 
15145       PushOnScopeChains(AI, CurBlock->TheScope);
15146     }
15147   }
15148 }
15149 
15150 /// ActOnBlockError - If there is an error parsing a block, this callback
15151 /// is invoked to pop the information about the block from the action impl.
15152 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15153   // Leave the expression-evaluation context.
15154   DiscardCleanupsInEvaluationContext();
15155   PopExpressionEvaluationContext();
15156 
15157   // Pop off CurBlock, handle nested blocks.
15158   PopDeclContext();
15159   PopFunctionScopeInfo();
15160 }
15161 
15162 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15163 /// literal was successfully completed.  ^(int x){...}
15164 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15165                                     Stmt *Body, Scope *CurScope) {
15166   // If blocks are disabled, emit an error.
15167   if (!LangOpts.Blocks)
15168     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15169 
15170   // Leave the expression-evaluation context.
15171   if (hasAnyUnrecoverableErrorsInThisFunction())
15172     DiscardCleanupsInEvaluationContext();
15173   assert(!Cleanup.exprNeedsCleanups() &&
15174          "cleanups within block not correctly bound!");
15175   PopExpressionEvaluationContext();
15176 
15177   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15178   BlockDecl *BD = BSI->TheDecl;
15179 
15180   if (BSI->HasImplicitReturnType)
15181     deduceClosureReturnType(*BSI);
15182 
15183   QualType RetTy = Context.VoidTy;
15184   if (!BSI->ReturnType.isNull())
15185     RetTy = BSI->ReturnType;
15186 
15187   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15188   QualType BlockTy;
15189 
15190   // If the user wrote a function type in some form, try to use that.
15191   if (!BSI->FunctionType.isNull()) {
15192     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15193 
15194     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15195     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15196 
15197     // Turn protoless block types into nullary block types.
15198     if (isa<FunctionNoProtoType>(FTy)) {
15199       FunctionProtoType::ExtProtoInfo EPI;
15200       EPI.ExtInfo = Ext;
15201       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15202 
15203     // Otherwise, if we don't need to change anything about the function type,
15204     // preserve its sugar structure.
15205     } else if (FTy->getReturnType() == RetTy &&
15206                (!NoReturn || FTy->getNoReturnAttr())) {
15207       BlockTy = BSI->FunctionType;
15208 
15209     // Otherwise, make the minimal modifications to the function type.
15210     } else {
15211       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15212       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15213       EPI.TypeQuals = Qualifiers();
15214       EPI.ExtInfo = Ext;
15215       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15216     }
15217 
15218   // If we don't have a function type, just build one from nothing.
15219   } else {
15220     FunctionProtoType::ExtProtoInfo EPI;
15221     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15222     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15223   }
15224 
15225   DiagnoseUnusedParameters(BD->parameters());
15226   BlockTy = Context.getBlockPointerType(BlockTy);
15227 
15228   // If needed, diagnose invalid gotos and switches in the block.
15229   if (getCurFunction()->NeedsScopeChecking() &&
15230       !PP.isCodeCompletionEnabled())
15231     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15232 
15233   BD->setBody(cast<CompoundStmt>(Body));
15234 
15235   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15236     DiagnoseUnguardedAvailabilityViolations(BD);
15237 
15238   // Try to apply the named return value optimization. We have to check again
15239   // if we can do this, though, because blocks keep return statements around
15240   // to deduce an implicit return type.
15241   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15242       !BD->isDependentContext())
15243     computeNRVO(Body, BSI);
15244 
15245   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15246       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15247     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15248                           NTCUK_Destruct|NTCUK_Copy);
15249 
15250   PopDeclContext();
15251 
15252   // Pop the block scope now but keep it alive to the end of this function.
15253   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15254   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15255 
15256   // Set the captured variables on the block.
15257   SmallVector<BlockDecl::Capture, 4> Captures;
15258   for (Capture &Cap : BSI->Captures) {
15259     if (Cap.isInvalid() || Cap.isThisCapture())
15260       continue;
15261 
15262     VarDecl *Var = Cap.getVariable();
15263     Expr *CopyExpr = nullptr;
15264     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15265       if (const RecordType *Record =
15266               Cap.getCaptureType()->getAs<RecordType>()) {
15267         // The capture logic needs the destructor, so make sure we mark it.
15268         // Usually this is unnecessary because most local variables have
15269         // their destructors marked at declaration time, but parameters are
15270         // an exception because it's technically only the call site that
15271         // actually requires the destructor.
15272         if (isa<ParmVarDecl>(Var))
15273           FinalizeVarWithDestructor(Var, Record);
15274 
15275         // Enter a separate potentially-evaluated context while building block
15276         // initializers to isolate their cleanups from those of the block
15277         // itself.
15278         // FIXME: Is this appropriate even when the block itself occurs in an
15279         // unevaluated operand?
15280         EnterExpressionEvaluationContext EvalContext(
15281             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15282 
15283         SourceLocation Loc = Cap.getLocation();
15284 
15285         ExprResult Result = BuildDeclarationNameExpr(
15286             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15287 
15288         // According to the blocks spec, the capture of a variable from
15289         // the stack requires a const copy constructor.  This is not true
15290         // of the copy/move done to move a __block variable to the heap.
15291         if (!Result.isInvalid() &&
15292             !Result.get()->getType().isConstQualified()) {
15293           Result = ImpCastExprToType(Result.get(),
15294                                      Result.get()->getType().withConst(),
15295                                      CK_NoOp, VK_LValue);
15296         }
15297 
15298         if (!Result.isInvalid()) {
15299           Result = PerformCopyInitialization(
15300               InitializedEntity::InitializeBlock(Var->getLocation(),
15301                                                  Cap.getCaptureType(), false),
15302               Loc, Result.get());
15303         }
15304 
15305         // Build a full-expression copy expression if initialization
15306         // succeeded and used a non-trivial constructor.  Recover from
15307         // errors by pretending that the copy isn't necessary.
15308         if (!Result.isInvalid() &&
15309             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15310                 ->isTrivial()) {
15311           Result = MaybeCreateExprWithCleanups(Result);
15312           CopyExpr = Result.get();
15313         }
15314       }
15315     }
15316 
15317     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15318                               CopyExpr);
15319     Captures.push_back(NewCap);
15320   }
15321   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15322 
15323   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15324 
15325   // If the block isn't obviously global, i.e. it captures anything at
15326   // all, then we need to do a few things in the surrounding context:
15327   if (Result->getBlockDecl()->hasCaptures()) {
15328     // First, this expression has a new cleanup object.
15329     ExprCleanupObjects.push_back(Result->getBlockDecl());
15330     Cleanup.setExprNeedsCleanups(true);
15331 
15332     // It also gets a branch-protected scope if any of the captured
15333     // variables needs destruction.
15334     for (const auto &CI : Result->getBlockDecl()->captures()) {
15335       const VarDecl *var = CI.getVariable();
15336       if (var->getType().isDestructedType() != QualType::DK_none) {
15337         setFunctionHasBranchProtectedScope();
15338         break;
15339       }
15340     }
15341   }
15342 
15343   if (getCurFunction())
15344     getCurFunction()->addBlock(BD);
15345 
15346   return Result;
15347 }
15348 
15349 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15350                             SourceLocation RPLoc) {
15351   TypeSourceInfo *TInfo;
15352   GetTypeFromParser(Ty, &TInfo);
15353   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15354 }
15355 
15356 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15357                                 Expr *E, TypeSourceInfo *TInfo,
15358                                 SourceLocation RPLoc) {
15359   Expr *OrigExpr = E;
15360   bool IsMS = false;
15361 
15362   // CUDA device code does not support varargs.
15363   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15364     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15365       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15366       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15367         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15368     }
15369   }
15370 
15371   // NVPTX does not support va_arg expression.
15372   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15373       Context.getTargetInfo().getTriple().isNVPTX())
15374     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15375 
15376   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15377   // as Microsoft ABI on an actual Microsoft platform, where
15378   // __builtin_ms_va_list and __builtin_va_list are the same.)
15379   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15380       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15381     QualType MSVaListType = Context.getBuiltinMSVaListType();
15382     if (Context.hasSameType(MSVaListType, E->getType())) {
15383       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15384         return ExprError();
15385       IsMS = true;
15386     }
15387   }
15388 
15389   // Get the va_list type
15390   QualType VaListType = Context.getBuiltinVaListType();
15391   if (!IsMS) {
15392     if (VaListType->isArrayType()) {
15393       // Deal with implicit array decay; for example, on x86-64,
15394       // va_list is an array, but it's supposed to decay to
15395       // a pointer for va_arg.
15396       VaListType = Context.getArrayDecayedType(VaListType);
15397       // Make sure the input expression also decays appropriately.
15398       ExprResult Result = UsualUnaryConversions(E);
15399       if (Result.isInvalid())
15400         return ExprError();
15401       E = Result.get();
15402     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15403       // If va_list is a record type and we are compiling in C++ mode,
15404       // check the argument using reference binding.
15405       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15406           Context, Context.getLValueReferenceType(VaListType), false);
15407       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15408       if (Init.isInvalid())
15409         return ExprError();
15410       E = Init.getAs<Expr>();
15411     } else {
15412       // Otherwise, the va_list argument must be an l-value because
15413       // it is modified by va_arg.
15414       if (!E->isTypeDependent() &&
15415           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15416         return ExprError();
15417     }
15418   }
15419 
15420   if (!IsMS && !E->isTypeDependent() &&
15421       !Context.hasSameType(VaListType, E->getType()))
15422     return ExprError(
15423         Diag(E->getBeginLoc(),
15424              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15425         << OrigExpr->getType() << E->getSourceRange());
15426 
15427   if (!TInfo->getType()->isDependentType()) {
15428     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15429                             diag::err_second_parameter_to_va_arg_incomplete,
15430                             TInfo->getTypeLoc()))
15431       return ExprError();
15432 
15433     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15434                                TInfo->getType(),
15435                                diag::err_second_parameter_to_va_arg_abstract,
15436                                TInfo->getTypeLoc()))
15437       return ExprError();
15438 
15439     if (!TInfo->getType().isPODType(Context)) {
15440       Diag(TInfo->getTypeLoc().getBeginLoc(),
15441            TInfo->getType()->isObjCLifetimeType()
15442              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15443              : diag::warn_second_parameter_to_va_arg_not_pod)
15444         << TInfo->getType()
15445         << TInfo->getTypeLoc().getSourceRange();
15446     }
15447 
15448     // Check for va_arg where arguments of the given type will be promoted
15449     // (i.e. this va_arg is guaranteed to have undefined behavior).
15450     QualType PromoteType;
15451     if (TInfo->getType()->isPromotableIntegerType()) {
15452       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15453       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15454         PromoteType = QualType();
15455     }
15456     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15457       PromoteType = Context.DoubleTy;
15458     if (!PromoteType.isNull())
15459       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15460                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15461                           << TInfo->getType()
15462                           << PromoteType
15463                           << TInfo->getTypeLoc().getSourceRange());
15464   }
15465 
15466   QualType T = TInfo->getType().getNonLValueExprType(Context);
15467   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15468 }
15469 
15470 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15471   // The type of __null will be int or long, depending on the size of
15472   // pointers on the target.
15473   QualType Ty;
15474   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15475   if (pw == Context.getTargetInfo().getIntWidth())
15476     Ty = Context.IntTy;
15477   else if (pw == Context.getTargetInfo().getLongWidth())
15478     Ty = Context.LongTy;
15479   else if (pw == Context.getTargetInfo().getLongLongWidth())
15480     Ty = Context.LongLongTy;
15481   else {
15482     llvm_unreachable("I don't know size of pointer!");
15483   }
15484 
15485   return new (Context) GNUNullExpr(Ty, TokenLoc);
15486 }
15487 
15488 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15489                                     SourceLocation BuiltinLoc,
15490                                     SourceLocation RPLoc) {
15491   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15492 }
15493 
15494 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15495                                     SourceLocation BuiltinLoc,
15496                                     SourceLocation RPLoc,
15497                                     DeclContext *ParentContext) {
15498   return new (Context)
15499       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15500 }
15501 
15502 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15503                                         bool Diagnose) {
15504   if (!getLangOpts().ObjC)
15505     return false;
15506 
15507   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15508   if (!PT)
15509     return false;
15510   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15511 
15512   // Ignore any parens, implicit casts (should only be
15513   // array-to-pointer decays), and not-so-opaque values.  The last is
15514   // important for making this trigger for property assignments.
15515   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15516   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15517     if (OV->getSourceExpr())
15518       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15519 
15520   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15521     if (!PT->isObjCIdType() &&
15522         !(ID && ID->getIdentifier()->isStr("NSString")))
15523       return false;
15524     if (!SL->isAscii())
15525       return false;
15526 
15527     if (Diagnose) {
15528       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15529           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15530       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15531     }
15532     return true;
15533   }
15534 
15535   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15536       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15537       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15538       !SrcExpr->isNullPointerConstant(
15539           getASTContext(), Expr::NPC_NeverValueDependent)) {
15540     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15541       return false;
15542     if (Diagnose) {
15543       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15544           << /*number*/1
15545           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15546       Expr *NumLit =
15547           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15548       if (NumLit)
15549         Exp = NumLit;
15550     }
15551     return true;
15552   }
15553 
15554   return false;
15555 }
15556 
15557 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15558                                               const Expr *SrcExpr) {
15559   if (!DstType->isFunctionPointerType() ||
15560       !SrcExpr->getType()->isFunctionType())
15561     return false;
15562 
15563   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15564   if (!DRE)
15565     return false;
15566 
15567   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15568   if (!FD)
15569     return false;
15570 
15571   return !S.checkAddressOfFunctionIsAvailable(FD,
15572                                               /*Complain=*/true,
15573                                               SrcExpr->getBeginLoc());
15574 }
15575 
15576 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15577                                     SourceLocation Loc,
15578                                     QualType DstType, QualType SrcType,
15579                                     Expr *SrcExpr, AssignmentAction Action,
15580                                     bool *Complained) {
15581   if (Complained)
15582     *Complained = false;
15583 
15584   // Decode the result (notice that AST's are still created for extensions).
15585   bool CheckInferredResultType = false;
15586   bool isInvalid = false;
15587   unsigned DiagKind = 0;
15588   ConversionFixItGenerator ConvHints;
15589   bool MayHaveConvFixit = false;
15590   bool MayHaveFunctionDiff = false;
15591   const ObjCInterfaceDecl *IFace = nullptr;
15592   const ObjCProtocolDecl *PDecl = nullptr;
15593 
15594   switch (ConvTy) {
15595   case Compatible:
15596       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15597       return false;
15598 
15599   case PointerToInt:
15600     if (getLangOpts().CPlusPlus) {
15601       DiagKind = diag::err_typecheck_convert_pointer_int;
15602       isInvalid = true;
15603     } else {
15604       DiagKind = diag::ext_typecheck_convert_pointer_int;
15605     }
15606     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15607     MayHaveConvFixit = true;
15608     break;
15609   case IntToPointer:
15610     if (getLangOpts().CPlusPlus) {
15611       DiagKind = diag::err_typecheck_convert_int_pointer;
15612       isInvalid = true;
15613     } else {
15614       DiagKind = diag::ext_typecheck_convert_int_pointer;
15615     }
15616     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15617     MayHaveConvFixit = true;
15618     break;
15619   case IncompatibleFunctionPointer:
15620     if (getLangOpts().CPlusPlus) {
15621       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15622       isInvalid = true;
15623     } else {
15624       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15625     }
15626     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15627     MayHaveConvFixit = true;
15628     break;
15629   case IncompatiblePointer:
15630     if (Action == AA_Passing_CFAudited) {
15631       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15632     } else if (getLangOpts().CPlusPlus) {
15633       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15634       isInvalid = true;
15635     } else {
15636       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15637     }
15638     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15639       SrcType->isObjCObjectPointerType();
15640     if (!CheckInferredResultType) {
15641       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15642     } else if (CheckInferredResultType) {
15643       SrcType = SrcType.getUnqualifiedType();
15644       DstType = DstType.getUnqualifiedType();
15645     }
15646     MayHaveConvFixit = true;
15647     break;
15648   case IncompatiblePointerSign:
15649     if (getLangOpts().CPlusPlus) {
15650       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15651       isInvalid = true;
15652     } else {
15653       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15654     }
15655     break;
15656   case FunctionVoidPointer:
15657     if (getLangOpts().CPlusPlus) {
15658       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15659       isInvalid = true;
15660     } else {
15661       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15662     }
15663     break;
15664   case IncompatiblePointerDiscardsQualifiers: {
15665     // Perform array-to-pointer decay if necessary.
15666     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15667 
15668     isInvalid = true;
15669 
15670     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15671     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15672     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15673       DiagKind = diag::err_typecheck_incompatible_address_space;
15674       break;
15675 
15676     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15677       DiagKind = diag::err_typecheck_incompatible_ownership;
15678       break;
15679     }
15680 
15681     llvm_unreachable("unknown error case for discarding qualifiers!");
15682     // fallthrough
15683   }
15684   case CompatiblePointerDiscardsQualifiers:
15685     // If the qualifiers lost were because we were applying the
15686     // (deprecated) C++ conversion from a string literal to a char*
15687     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15688     // Ideally, this check would be performed in
15689     // checkPointerTypesForAssignment. However, that would require a
15690     // bit of refactoring (so that the second argument is an
15691     // expression, rather than a type), which should be done as part
15692     // of a larger effort to fix checkPointerTypesForAssignment for
15693     // C++ semantics.
15694     if (getLangOpts().CPlusPlus &&
15695         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15696       return false;
15697     if (getLangOpts().CPlusPlus) {
15698       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15699       isInvalid = true;
15700     } else {
15701       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15702     }
15703 
15704     break;
15705   case IncompatibleNestedPointerQualifiers:
15706     if (getLangOpts().CPlusPlus) {
15707       isInvalid = true;
15708       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15709     } else {
15710       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15711     }
15712     break;
15713   case IncompatibleNestedPointerAddressSpaceMismatch:
15714     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15715     isInvalid = true;
15716     break;
15717   case IntToBlockPointer:
15718     DiagKind = diag::err_int_to_block_pointer;
15719     isInvalid = true;
15720     break;
15721   case IncompatibleBlockPointer:
15722     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15723     isInvalid = true;
15724     break;
15725   case IncompatibleObjCQualifiedId: {
15726     if (SrcType->isObjCQualifiedIdType()) {
15727       const ObjCObjectPointerType *srcOPT =
15728                 SrcType->castAs<ObjCObjectPointerType>();
15729       for (auto *srcProto : srcOPT->quals()) {
15730         PDecl = srcProto;
15731         break;
15732       }
15733       if (const ObjCInterfaceType *IFaceT =
15734             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15735         IFace = IFaceT->getDecl();
15736     }
15737     else if (DstType->isObjCQualifiedIdType()) {
15738       const ObjCObjectPointerType *dstOPT =
15739         DstType->castAs<ObjCObjectPointerType>();
15740       for (auto *dstProto : dstOPT->quals()) {
15741         PDecl = dstProto;
15742         break;
15743       }
15744       if (const ObjCInterfaceType *IFaceT =
15745             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15746         IFace = IFaceT->getDecl();
15747     }
15748     if (getLangOpts().CPlusPlus) {
15749       DiagKind = diag::err_incompatible_qualified_id;
15750       isInvalid = true;
15751     } else {
15752       DiagKind = diag::warn_incompatible_qualified_id;
15753     }
15754     break;
15755   }
15756   case IncompatibleVectors:
15757     if (getLangOpts().CPlusPlus) {
15758       DiagKind = diag::err_incompatible_vectors;
15759       isInvalid = true;
15760     } else {
15761       DiagKind = diag::warn_incompatible_vectors;
15762     }
15763     break;
15764   case IncompatibleObjCWeakRef:
15765     DiagKind = diag::err_arc_weak_unavailable_assign;
15766     isInvalid = true;
15767     break;
15768   case Incompatible:
15769     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15770       if (Complained)
15771         *Complained = true;
15772       return true;
15773     }
15774 
15775     DiagKind = diag::err_typecheck_convert_incompatible;
15776     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15777     MayHaveConvFixit = true;
15778     isInvalid = true;
15779     MayHaveFunctionDiff = true;
15780     break;
15781   }
15782 
15783   QualType FirstType, SecondType;
15784   switch (Action) {
15785   case AA_Assigning:
15786   case AA_Initializing:
15787     // The destination type comes first.
15788     FirstType = DstType;
15789     SecondType = SrcType;
15790     break;
15791 
15792   case AA_Returning:
15793   case AA_Passing:
15794   case AA_Passing_CFAudited:
15795   case AA_Converting:
15796   case AA_Sending:
15797   case AA_Casting:
15798     // The source type comes first.
15799     FirstType = SrcType;
15800     SecondType = DstType;
15801     break;
15802   }
15803 
15804   PartialDiagnostic FDiag = PDiag(DiagKind);
15805   if (Action == AA_Passing_CFAudited)
15806     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15807   else
15808     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15809 
15810   // If we can fix the conversion, suggest the FixIts.
15811   if (!ConvHints.isNull()) {
15812     for (FixItHint &H : ConvHints.Hints)
15813       FDiag << H;
15814   }
15815 
15816   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15817 
15818   if (MayHaveFunctionDiff)
15819     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15820 
15821   Diag(Loc, FDiag);
15822   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15823        DiagKind == diag::err_incompatible_qualified_id) &&
15824       PDecl && IFace && !IFace->hasDefinition())
15825     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15826         << IFace << PDecl;
15827 
15828   if (SecondType == Context.OverloadTy)
15829     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15830                               FirstType, /*TakingAddress=*/true);
15831 
15832   if (CheckInferredResultType)
15833     EmitRelatedResultTypeNote(SrcExpr);
15834 
15835   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15836     EmitRelatedResultTypeNoteForReturn(DstType);
15837 
15838   if (Complained)
15839     *Complained = true;
15840   return isInvalid;
15841 }
15842 
15843 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15844                                                  llvm::APSInt *Result) {
15845   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15846   public:
15847     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15848                                              QualType T) override {
15849       return S.Diag(Loc, diag::err_ice_not_integral)
15850              << T << S.LangOpts.CPlusPlus;
15851     }
15852     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15853       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15854     }
15855   } Diagnoser;
15856 
15857   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15858 }
15859 
15860 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15861                                                  llvm::APSInt *Result,
15862                                                  unsigned DiagID,
15863                                                  bool AllowFold) {
15864   class IDDiagnoser : public VerifyICEDiagnoser {
15865     unsigned DiagID;
15866 
15867   public:
15868     IDDiagnoser(unsigned DiagID)
15869       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15870 
15871     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15872       return S.Diag(Loc, DiagID);
15873     }
15874   } Diagnoser(DiagID);
15875 
15876   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15877 }
15878 
15879 Sema::SemaDiagnosticBuilder
15880 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15881                                              QualType T) {
15882   return diagnoseNotICE(S, Loc);
15883 }
15884 
15885 Sema::SemaDiagnosticBuilder
15886 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15887   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15888 }
15889 
15890 ExprResult
15891 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15892                                       VerifyICEDiagnoser &Diagnoser,
15893                                       bool AllowFold) {
15894   SourceLocation DiagLoc = E->getBeginLoc();
15895 
15896   if (getLangOpts().CPlusPlus11) {
15897     // C++11 [expr.const]p5:
15898     //   If an expression of literal class type is used in a context where an
15899     //   integral constant expression is required, then that class type shall
15900     //   have a single non-explicit conversion function to an integral or
15901     //   unscoped enumeration type
15902     ExprResult Converted;
15903     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15904       VerifyICEDiagnoser &BaseDiagnoser;
15905     public:
15906       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15907           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15908                                 BaseDiagnoser.Suppress, true),
15909             BaseDiagnoser(BaseDiagnoser) {}
15910 
15911       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15912                                            QualType T) override {
15913         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15914       }
15915 
15916       SemaDiagnosticBuilder diagnoseIncomplete(
15917           Sema &S, SourceLocation Loc, QualType T) override {
15918         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15919       }
15920 
15921       SemaDiagnosticBuilder diagnoseExplicitConv(
15922           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15923         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15924       }
15925 
15926       SemaDiagnosticBuilder noteExplicitConv(
15927           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15928         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15929                  << ConvTy->isEnumeralType() << ConvTy;
15930       }
15931 
15932       SemaDiagnosticBuilder diagnoseAmbiguous(
15933           Sema &S, SourceLocation Loc, QualType T) override {
15934         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15935       }
15936 
15937       SemaDiagnosticBuilder noteAmbiguous(
15938           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15939         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15940                  << ConvTy->isEnumeralType() << ConvTy;
15941       }
15942 
15943       SemaDiagnosticBuilder diagnoseConversion(
15944           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15945         llvm_unreachable("conversion functions are permitted");
15946       }
15947     } ConvertDiagnoser(Diagnoser);
15948 
15949     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15950                                                     ConvertDiagnoser);
15951     if (Converted.isInvalid())
15952       return Converted;
15953     E = Converted.get();
15954     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15955       return ExprError();
15956   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15957     // An ICE must be of integral or unscoped enumeration type.
15958     if (!Diagnoser.Suppress)
15959       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
15960           << E->getSourceRange();
15961     return ExprError();
15962   }
15963 
15964   ExprResult RValueExpr = DefaultLvalueConversion(E);
15965   if (RValueExpr.isInvalid())
15966     return ExprError();
15967 
15968   E = RValueExpr.get();
15969 
15970   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15971   // in the non-ICE case.
15972   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15973     if (Result)
15974       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15975     if (!isa<ConstantExpr>(E))
15976       E = ConstantExpr::Create(Context, E);
15977     return E;
15978   }
15979 
15980   Expr::EvalResult EvalResult;
15981   SmallVector<PartialDiagnosticAt, 8> Notes;
15982   EvalResult.Diag = &Notes;
15983 
15984   // Try to evaluate the expression, and produce diagnostics explaining why it's
15985   // not a constant expression as a side-effect.
15986   bool Folded =
15987       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15988       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15989 
15990   if (!isa<ConstantExpr>(E))
15991     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15992 
15993   // In C++11, we can rely on diagnostics being produced for any expression
15994   // which is not a constant expression. If no diagnostics were produced, then
15995   // this is a constant expression.
15996   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15997     if (Result)
15998       *Result = EvalResult.Val.getInt();
15999     return E;
16000   }
16001 
16002   // If our only note is the usual "invalid subexpression" note, just point
16003   // the caret at its location rather than producing an essentially
16004   // redundant note.
16005   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16006         diag::note_invalid_subexpr_in_const_expr) {
16007     DiagLoc = Notes[0].first;
16008     Notes.clear();
16009   }
16010 
16011   if (!Folded || !AllowFold) {
16012     if (!Diagnoser.Suppress) {
16013       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16014       for (const PartialDiagnosticAt &Note : Notes)
16015         Diag(Note.first, Note.second);
16016     }
16017 
16018     return ExprError();
16019   }
16020 
16021   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16022   for (const PartialDiagnosticAt &Note : Notes)
16023     Diag(Note.first, Note.second);
16024 
16025   if (Result)
16026     *Result = EvalResult.Val.getInt();
16027   return E;
16028 }
16029 
16030 namespace {
16031   // Handle the case where we conclude a expression which we speculatively
16032   // considered to be unevaluated is actually evaluated.
16033   class TransformToPE : public TreeTransform<TransformToPE> {
16034     typedef TreeTransform<TransformToPE> BaseTransform;
16035 
16036   public:
16037     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16038 
16039     // Make sure we redo semantic analysis
16040     bool AlwaysRebuild() { return true; }
16041     bool ReplacingOriginal() { return true; }
16042 
16043     // We need to special-case DeclRefExprs referring to FieldDecls which
16044     // are not part of a member pointer formation; normal TreeTransforming
16045     // doesn't catch this case because of the way we represent them in the AST.
16046     // FIXME: This is a bit ugly; is it really the best way to handle this
16047     // case?
16048     //
16049     // Error on DeclRefExprs referring to FieldDecls.
16050     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16051       if (isa<FieldDecl>(E->getDecl()) &&
16052           !SemaRef.isUnevaluatedContext())
16053         return SemaRef.Diag(E->getLocation(),
16054                             diag::err_invalid_non_static_member_use)
16055             << E->getDecl() << E->getSourceRange();
16056 
16057       return BaseTransform::TransformDeclRefExpr(E);
16058     }
16059 
16060     // Exception: filter out member pointer formation
16061     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16062       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16063         return E;
16064 
16065       return BaseTransform::TransformUnaryOperator(E);
16066     }
16067 
16068     // The body of a lambda-expression is in a separate expression evaluation
16069     // context so never needs to be transformed.
16070     // FIXME: Ideally we wouldn't transform the closure type either, and would
16071     // just recreate the capture expressions and lambda expression.
16072     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16073       return SkipLambdaBody(E, Body);
16074     }
16075   };
16076 }
16077 
16078 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16079   assert(isUnevaluatedContext() &&
16080          "Should only transform unevaluated expressions");
16081   ExprEvalContexts.back().Context =
16082       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16083   if (isUnevaluatedContext())
16084     return E;
16085   return TransformToPE(*this).TransformExpr(E);
16086 }
16087 
16088 void
16089 Sema::PushExpressionEvaluationContext(
16090     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16091     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16092   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16093                                 LambdaContextDecl, ExprContext);
16094   Cleanup.reset();
16095   if (!MaybeODRUseExprs.empty())
16096     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16097 }
16098 
16099 void
16100 Sema::PushExpressionEvaluationContext(
16101     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16102     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16103   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16104   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16105 }
16106 
16107 namespace {
16108 
16109 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16110   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16111   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16112     if (E->getOpcode() == UO_Deref)
16113       return CheckPossibleDeref(S, E->getSubExpr());
16114   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16115     return CheckPossibleDeref(S, E->getBase());
16116   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16117     return CheckPossibleDeref(S, E->getBase());
16118   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16119     QualType Inner;
16120     QualType Ty = E->getType();
16121     if (const auto *Ptr = Ty->getAs<PointerType>())
16122       Inner = Ptr->getPointeeType();
16123     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16124       Inner = Arr->getElementType();
16125     else
16126       return nullptr;
16127 
16128     if (Inner->hasAttr(attr::NoDeref))
16129       return E;
16130   }
16131   return nullptr;
16132 }
16133 
16134 } // namespace
16135 
16136 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16137   for (const Expr *E : Rec.PossibleDerefs) {
16138     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16139     if (DeclRef) {
16140       const ValueDecl *Decl = DeclRef->getDecl();
16141       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16142           << Decl->getName() << E->getSourceRange();
16143       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16144     } else {
16145       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16146           << E->getSourceRange();
16147     }
16148   }
16149   Rec.PossibleDerefs.clear();
16150 }
16151 
16152 /// Check whether E, which is either a discarded-value expression or an
16153 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16154 /// and if so, remove it from the list of volatile-qualified assignments that
16155 /// we are going to warn are deprecated.
16156 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16157   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16158     return;
16159 
16160   // Note: ignoring parens here is not justified by the standard rules, but
16161   // ignoring parentheses seems like a more reasonable approach, and this only
16162   // drives a deprecation warning so doesn't affect conformance.
16163   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16164     if (BO->getOpcode() == BO_Assign) {
16165       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16166       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16167                  LHSs.end());
16168     }
16169   }
16170 }
16171 
16172 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16173   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16174       RebuildingImmediateInvocation)
16175     return E;
16176 
16177   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16178   /// It's OK if this fails; we'll also remove this in
16179   /// HandleImmediateInvocations, but catching it here allows us to avoid
16180   /// walking the AST looking for it in simple cases.
16181   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16182     if (auto *DeclRef =
16183             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16184       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16185 
16186   E = MaybeCreateExprWithCleanups(E);
16187 
16188   ConstantExpr *Res = ConstantExpr::Create(
16189       getASTContext(), E.get(),
16190       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16191                                    getASTContext()),
16192       /*IsImmediateInvocation*/ true);
16193   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16194   return Res;
16195 }
16196 
16197 static void EvaluateAndDiagnoseImmediateInvocation(
16198     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16199   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16200   Expr::EvalResult Eval;
16201   Eval.Diag = &Notes;
16202   ConstantExpr *CE = Candidate.getPointer();
16203   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16204                                            SemaRef.getASTContext(), true);
16205   if (!Result || !Notes.empty()) {
16206     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16207     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16208       InnerExpr = FunctionalCast->getSubExpr();
16209     FunctionDecl *FD = nullptr;
16210     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16211       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16212     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16213       FD = Call->getConstructor();
16214     else
16215       llvm_unreachable("unhandled decl kind");
16216     assert(FD->isConsteval());
16217     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16218     for (auto &Note : Notes)
16219       SemaRef.Diag(Note.first, Note.second);
16220     return;
16221   }
16222   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16223 }
16224 
16225 static void RemoveNestedImmediateInvocation(
16226     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16227     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16228   struct ComplexRemove : TreeTransform<ComplexRemove> {
16229     using Base = TreeTransform<ComplexRemove>;
16230     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16231     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16232     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16233         CurrentII;
16234     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16235                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16236                   SmallVector<Sema::ImmediateInvocationCandidate,
16237                               4>::reverse_iterator Current)
16238         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16239     void RemoveImmediateInvocation(ConstantExpr* E) {
16240       auto It = std::find_if(CurrentII, IISet.rend(),
16241                              [E](Sema::ImmediateInvocationCandidate Elem) {
16242                                return Elem.getPointer() == E;
16243                              });
16244       assert(It != IISet.rend() &&
16245              "ConstantExpr marked IsImmediateInvocation should "
16246              "be present");
16247       It->setInt(1); // Mark as deleted
16248     }
16249     ExprResult TransformConstantExpr(ConstantExpr *E) {
16250       if (!E->isImmediateInvocation())
16251         return Base::TransformConstantExpr(E);
16252       RemoveImmediateInvocation(E);
16253       return Base::TransformExpr(E->getSubExpr());
16254     }
16255     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16256     /// we need to remove its DeclRefExpr from the DRSet.
16257     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16258       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16259       return Base::TransformCXXOperatorCallExpr(E);
16260     }
16261     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16262     /// here.
16263     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16264       if (!Init)
16265         return Init;
16266       /// ConstantExpr are the first layer of implicit node to be removed so if
16267       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16268       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16269         if (CE->isImmediateInvocation())
16270           RemoveImmediateInvocation(CE);
16271       return Base::TransformInitializer(Init, NotCopyInit);
16272     }
16273     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16274       DRSet.erase(E);
16275       return E;
16276     }
16277     bool AlwaysRebuild() { return false; }
16278     bool ReplacingOriginal() { return true; }
16279     bool AllowSkippingCXXConstructExpr() {
16280       bool Res = AllowSkippingFirstCXXConstructExpr;
16281       AllowSkippingFirstCXXConstructExpr = true;
16282       return Res;
16283     }
16284     bool AllowSkippingFirstCXXConstructExpr = true;
16285   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16286                 Rec.ImmediateInvocationCandidates, It);
16287 
16288   /// CXXConstructExpr with a single argument are getting skipped by
16289   /// TreeTransform in some situtation because they could be implicit. This
16290   /// can only occur for the top-level CXXConstructExpr because it is used
16291   /// nowhere in the expression being transformed therefore will not be rebuilt.
16292   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16293   /// skipping the first CXXConstructExpr.
16294   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16295     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16296 
16297   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16298   assert(Res.isUsable());
16299   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16300   It->getPointer()->setSubExpr(Res.get());
16301 }
16302 
16303 static void
16304 HandleImmediateInvocations(Sema &SemaRef,
16305                            Sema::ExpressionEvaluationContextRecord &Rec) {
16306   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16307        Rec.ReferenceToConsteval.size() == 0) ||
16308       SemaRef.RebuildingImmediateInvocation)
16309     return;
16310 
16311   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16312   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16313   /// need to remove ReferenceToConsteval in the immediate invocation.
16314   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16315 
16316     /// Prevent sema calls during the tree transform from adding pointers that
16317     /// are already in the sets.
16318     llvm::SaveAndRestore<bool> DisableIITracking(
16319         SemaRef.RebuildingImmediateInvocation, true);
16320 
16321     /// Prevent diagnostic during tree transfrom as they are duplicates
16322     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16323 
16324     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16325          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16326       if (!It->getInt())
16327         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16328   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16329              Rec.ReferenceToConsteval.size()) {
16330     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16331       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16332       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16333       bool VisitDeclRefExpr(DeclRefExpr *E) {
16334         DRSet.erase(E);
16335         return DRSet.size();
16336       }
16337     } Visitor(Rec.ReferenceToConsteval);
16338     Visitor.TraverseStmt(
16339         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16340   }
16341   for (auto CE : Rec.ImmediateInvocationCandidates)
16342     if (!CE.getInt())
16343       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16344   for (auto DR : Rec.ReferenceToConsteval) {
16345     auto *FD = cast<FunctionDecl>(DR->getDecl());
16346     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16347         << FD;
16348     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16349   }
16350 }
16351 
16352 void Sema::PopExpressionEvaluationContext() {
16353   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16354   unsigned NumTypos = Rec.NumTypos;
16355 
16356   if (!Rec.Lambdas.empty()) {
16357     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16358     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16359         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16360       unsigned D;
16361       if (Rec.isUnevaluated()) {
16362         // C++11 [expr.prim.lambda]p2:
16363         //   A lambda-expression shall not appear in an unevaluated operand
16364         //   (Clause 5).
16365         D = diag::err_lambda_unevaluated_operand;
16366       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16367         // C++1y [expr.const]p2:
16368         //   A conditional-expression e is a core constant expression unless the
16369         //   evaluation of e, following the rules of the abstract machine, would
16370         //   evaluate [...] a lambda-expression.
16371         D = diag::err_lambda_in_constant_expression;
16372       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16373         // C++17 [expr.prim.lamda]p2:
16374         // A lambda-expression shall not appear [...] in a template-argument.
16375         D = diag::err_lambda_in_invalid_context;
16376       } else
16377         llvm_unreachable("Couldn't infer lambda error message.");
16378 
16379       for (const auto *L : Rec.Lambdas)
16380         Diag(L->getBeginLoc(), D);
16381     }
16382   }
16383 
16384   WarnOnPendingNoDerefs(Rec);
16385   HandleImmediateInvocations(*this, Rec);
16386 
16387   // Warn on any volatile-qualified simple-assignments that are not discarded-
16388   // value expressions nor unevaluated operands (those cases get removed from
16389   // this list by CheckUnusedVolatileAssignment).
16390   for (auto *BO : Rec.VolatileAssignmentLHSs)
16391     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16392         << BO->getType();
16393 
16394   // When are coming out of an unevaluated context, clear out any
16395   // temporaries that we may have created as part of the evaluation of
16396   // the expression in that context: they aren't relevant because they
16397   // will never be constructed.
16398   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16399     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16400                              ExprCleanupObjects.end());
16401     Cleanup = Rec.ParentCleanup;
16402     CleanupVarDeclMarking();
16403     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16404   // Otherwise, merge the contexts together.
16405   } else {
16406     Cleanup.mergeFrom(Rec.ParentCleanup);
16407     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16408                             Rec.SavedMaybeODRUseExprs.end());
16409   }
16410 
16411   // Pop the current expression evaluation context off the stack.
16412   ExprEvalContexts.pop_back();
16413 
16414   // The global expression evaluation context record is never popped.
16415   ExprEvalContexts.back().NumTypos += NumTypos;
16416 }
16417 
16418 void Sema::DiscardCleanupsInEvaluationContext() {
16419   ExprCleanupObjects.erase(
16420          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16421          ExprCleanupObjects.end());
16422   Cleanup.reset();
16423   MaybeODRUseExprs.clear();
16424 }
16425 
16426 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16427   ExprResult Result = CheckPlaceholderExpr(E);
16428   if (Result.isInvalid())
16429     return ExprError();
16430   E = Result.get();
16431   if (!E->getType()->isVariablyModifiedType())
16432     return E;
16433   return TransformToPotentiallyEvaluated(E);
16434 }
16435 
16436 /// Are we in a context that is potentially constant evaluated per C++20
16437 /// [expr.const]p12?
16438 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16439   /// C++2a [expr.const]p12:
16440   //   An expression or conversion is potentially constant evaluated if it is
16441   switch (SemaRef.ExprEvalContexts.back().Context) {
16442     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16443       // -- a manifestly constant-evaluated expression,
16444     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16445     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16446     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16447       // -- a potentially-evaluated expression,
16448     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16449       // -- an immediate subexpression of a braced-init-list,
16450 
16451       // -- [FIXME] an expression of the form & cast-expression that occurs
16452       //    within a templated entity
16453       // -- a subexpression of one of the above that is not a subexpression of
16454       // a nested unevaluated operand.
16455       return true;
16456 
16457     case Sema::ExpressionEvaluationContext::Unevaluated:
16458     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16459       // Expressions in this context are never evaluated.
16460       return false;
16461   }
16462   llvm_unreachable("Invalid context");
16463 }
16464 
16465 /// Return true if this function has a calling convention that requires mangling
16466 /// in the size of the parameter pack.
16467 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16468   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16469   // we don't need parameter type sizes.
16470   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16471   if (!TT.isOSWindows() || !TT.isX86())
16472     return false;
16473 
16474   // If this is C++ and this isn't an extern "C" function, parameters do not
16475   // need to be complete. In this case, C++ mangling will apply, which doesn't
16476   // use the size of the parameters.
16477   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16478     return false;
16479 
16480   // Stdcall, fastcall, and vectorcall need this special treatment.
16481   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16482   switch (CC) {
16483   case CC_X86StdCall:
16484   case CC_X86FastCall:
16485   case CC_X86VectorCall:
16486     return true;
16487   default:
16488     break;
16489   }
16490   return false;
16491 }
16492 
16493 /// Require that all of the parameter types of function be complete. Normally,
16494 /// parameter types are only required to be complete when a function is called
16495 /// or defined, but to mangle functions with certain calling conventions, the
16496 /// mangler needs to know the size of the parameter list. In this situation,
16497 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16498 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16499 /// result in a linker error. Clang doesn't implement this behavior, and instead
16500 /// attempts to error at compile time.
16501 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16502                                                   SourceLocation Loc) {
16503   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16504     FunctionDecl *FD;
16505     ParmVarDecl *Param;
16506 
16507   public:
16508     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16509         : FD(FD), Param(Param) {}
16510 
16511     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16512       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16513       StringRef CCName;
16514       switch (CC) {
16515       case CC_X86StdCall:
16516         CCName = "stdcall";
16517         break;
16518       case CC_X86FastCall:
16519         CCName = "fastcall";
16520         break;
16521       case CC_X86VectorCall:
16522         CCName = "vectorcall";
16523         break;
16524       default:
16525         llvm_unreachable("CC does not need mangling");
16526       }
16527 
16528       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16529           << Param->getDeclName() << FD->getDeclName() << CCName;
16530     }
16531   };
16532 
16533   for (ParmVarDecl *Param : FD->parameters()) {
16534     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16535     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16536   }
16537 }
16538 
16539 namespace {
16540 enum class OdrUseContext {
16541   /// Declarations in this context are not odr-used.
16542   None,
16543   /// Declarations in this context are formally odr-used, but this is a
16544   /// dependent context.
16545   Dependent,
16546   /// Declarations in this context are odr-used but not actually used (yet).
16547   FormallyOdrUsed,
16548   /// Declarations in this context are used.
16549   Used
16550 };
16551 }
16552 
16553 /// Are we within a context in which references to resolved functions or to
16554 /// variables result in odr-use?
16555 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16556   OdrUseContext Result;
16557 
16558   switch (SemaRef.ExprEvalContexts.back().Context) {
16559     case Sema::ExpressionEvaluationContext::Unevaluated:
16560     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16561     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16562       return OdrUseContext::None;
16563 
16564     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16565     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16566       Result = OdrUseContext::Used;
16567       break;
16568 
16569     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16570       Result = OdrUseContext::FormallyOdrUsed;
16571       break;
16572 
16573     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16574       // A default argument formally results in odr-use, but doesn't actually
16575       // result in a use in any real sense until it itself is used.
16576       Result = OdrUseContext::FormallyOdrUsed;
16577       break;
16578   }
16579 
16580   if (SemaRef.CurContext->isDependentContext())
16581     return OdrUseContext::Dependent;
16582 
16583   return Result;
16584 }
16585 
16586 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16587   return Func->isConstexpr() &&
16588          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16589 }
16590 
16591 /// Mark a function referenced, and check whether it is odr-used
16592 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16593 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16594                                   bool MightBeOdrUse) {
16595   assert(Func && "No function?");
16596 
16597   Func->setReferenced();
16598 
16599   // Recursive functions aren't really used until they're used from some other
16600   // context.
16601   bool IsRecursiveCall = CurContext == Func;
16602 
16603   // C++11 [basic.def.odr]p3:
16604   //   A function whose name appears as a potentially-evaluated expression is
16605   //   odr-used if it is the unique lookup result or the selected member of a
16606   //   set of overloaded functions [...].
16607   //
16608   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16609   // can just check that here.
16610   OdrUseContext OdrUse =
16611       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16612   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16613     OdrUse = OdrUseContext::FormallyOdrUsed;
16614 
16615   // Trivial default constructors and destructors are never actually used.
16616   // FIXME: What about other special members?
16617   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16618       OdrUse == OdrUseContext::Used) {
16619     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16620       if (Constructor->isDefaultConstructor())
16621         OdrUse = OdrUseContext::FormallyOdrUsed;
16622     if (isa<CXXDestructorDecl>(Func))
16623       OdrUse = OdrUseContext::FormallyOdrUsed;
16624   }
16625 
16626   // C++20 [expr.const]p12:
16627   //   A function [...] is needed for constant evaluation if it is [...] a
16628   //   constexpr function that is named by an expression that is potentially
16629   //   constant evaluated
16630   bool NeededForConstantEvaluation =
16631       isPotentiallyConstantEvaluatedContext(*this) &&
16632       isImplicitlyDefinableConstexprFunction(Func);
16633 
16634   // Determine whether we require a function definition to exist, per
16635   // C++11 [temp.inst]p3:
16636   //   Unless a function template specialization has been explicitly
16637   //   instantiated or explicitly specialized, the function template
16638   //   specialization is implicitly instantiated when the specialization is
16639   //   referenced in a context that requires a function definition to exist.
16640   // C++20 [temp.inst]p7:
16641   //   The existence of a definition of a [...] function is considered to
16642   //   affect the semantics of the program if the [...] function is needed for
16643   //   constant evaluation by an expression
16644   // C++20 [basic.def.odr]p10:
16645   //   Every program shall contain exactly one definition of every non-inline
16646   //   function or variable that is odr-used in that program outside of a
16647   //   discarded statement
16648   // C++20 [special]p1:
16649   //   The implementation will implicitly define [defaulted special members]
16650   //   if they are odr-used or needed for constant evaluation.
16651   //
16652   // Note that we skip the implicit instantiation of templates that are only
16653   // used in unused default arguments or by recursive calls to themselves.
16654   // This is formally non-conforming, but seems reasonable in practice.
16655   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16656                                              NeededForConstantEvaluation);
16657 
16658   // C++14 [temp.expl.spec]p6:
16659   //   If a template [...] is explicitly specialized then that specialization
16660   //   shall be declared before the first use of that specialization that would
16661   //   cause an implicit instantiation to take place, in every translation unit
16662   //   in which such a use occurs
16663   if (NeedDefinition &&
16664       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16665        Func->getMemberSpecializationInfo()))
16666     checkSpecializationVisibility(Loc, Func);
16667 
16668   if (getLangOpts().CUDA)
16669     CheckCUDACall(Loc, Func);
16670 
16671   if (getLangOpts().SYCLIsDevice)
16672     checkSYCLDeviceFunction(Loc, Func);
16673 
16674   // If we need a definition, try to create one.
16675   if (NeedDefinition && !Func->getBody()) {
16676     runWithSufficientStackSpace(Loc, [&] {
16677       if (CXXConstructorDecl *Constructor =
16678               dyn_cast<CXXConstructorDecl>(Func)) {
16679         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16680         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16681           if (Constructor->isDefaultConstructor()) {
16682             if (Constructor->isTrivial() &&
16683                 !Constructor->hasAttr<DLLExportAttr>())
16684               return;
16685             DefineImplicitDefaultConstructor(Loc, Constructor);
16686           } else if (Constructor->isCopyConstructor()) {
16687             DefineImplicitCopyConstructor(Loc, Constructor);
16688           } else if (Constructor->isMoveConstructor()) {
16689             DefineImplicitMoveConstructor(Loc, Constructor);
16690           }
16691         } else if (Constructor->getInheritedConstructor()) {
16692           DefineInheritingConstructor(Loc, Constructor);
16693         }
16694       } else if (CXXDestructorDecl *Destructor =
16695                      dyn_cast<CXXDestructorDecl>(Func)) {
16696         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16697         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16698           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16699             return;
16700           DefineImplicitDestructor(Loc, Destructor);
16701         }
16702         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16703           MarkVTableUsed(Loc, Destructor->getParent());
16704       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16705         if (MethodDecl->isOverloadedOperator() &&
16706             MethodDecl->getOverloadedOperator() == OO_Equal) {
16707           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16708           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16709             if (MethodDecl->isCopyAssignmentOperator())
16710               DefineImplicitCopyAssignment(Loc, MethodDecl);
16711             else if (MethodDecl->isMoveAssignmentOperator())
16712               DefineImplicitMoveAssignment(Loc, MethodDecl);
16713           }
16714         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16715                    MethodDecl->getParent()->isLambda()) {
16716           CXXConversionDecl *Conversion =
16717               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16718           if (Conversion->isLambdaToBlockPointerConversion())
16719             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16720           else
16721             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16722         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16723           MarkVTableUsed(Loc, MethodDecl->getParent());
16724       }
16725 
16726       if (Func->isDefaulted() && !Func->isDeleted()) {
16727         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16728         if (DCK != DefaultedComparisonKind::None)
16729           DefineDefaultedComparison(Loc, Func, DCK);
16730       }
16731 
16732       // Implicit instantiation of function templates and member functions of
16733       // class templates.
16734       if (Func->isImplicitlyInstantiable()) {
16735         TemplateSpecializationKind TSK =
16736             Func->getTemplateSpecializationKindForInstantiation();
16737         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16738         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16739         if (FirstInstantiation) {
16740           PointOfInstantiation = Loc;
16741           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16742         } else if (TSK != TSK_ImplicitInstantiation) {
16743           // Use the point of use as the point of instantiation, instead of the
16744           // point of explicit instantiation (which we track as the actual point
16745           // of instantiation). This gives better backtraces in diagnostics.
16746           PointOfInstantiation = Loc;
16747         }
16748 
16749         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16750             Func->isConstexpr()) {
16751           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16752               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16753               CodeSynthesisContexts.size())
16754             PendingLocalImplicitInstantiations.push_back(
16755                 std::make_pair(Func, PointOfInstantiation));
16756           else if (Func->isConstexpr())
16757             // Do not defer instantiations of constexpr functions, to avoid the
16758             // expression evaluator needing to call back into Sema if it sees a
16759             // call to such a function.
16760             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16761           else {
16762             Func->setInstantiationIsPending(true);
16763             PendingInstantiations.push_back(
16764                 std::make_pair(Func, PointOfInstantiation));
16765             // Notify the consumer that a function was implicitly instantiated.
16766             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16767           }
16768         }
16769       } else {
16770         // Walk redefinitions, as some of them may be instantiable.
16771         for (auto i : Func->redecls()) {
16772           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16773             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16774         }
16775       }
16776     });
16777   }
16778 
16779   // C++14 [except.spec]p17:
16780   //   An exception-specification is considered to be needed when:
16781   //   - the function is odr-used or, if it appears in an unevaluated operand,
16782   //     would be odr-used if the expression were potentially-evaluated;
16783   //
16784   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16785   // function is a pure virtual function we're calling, and in that case the
16786   // function was selected by overload resolution and we need to resolve its
16787   // exception specification for a different reason.
16788   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16789   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16790     ResolveExceptionSpec(Loc, FPT);
16791 
16792   // If this is the first "real" use, act on that.
16793   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16794     // Keep track of used but undefined functions.
16795     if (!Func->isDefined()) {
16796       if (mightHaveNonExternalLinkage(Func))
16797         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16798       else if (Func->getMostRecentDecl()->isInlined() &&
16799                !LangOpts.GNUInline &&
16800                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16801         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16802       else if (isExternalWithNoLinkageType(Func))
16803         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16804     }
16805 
16806     // Some x86 Windows calling conventions mangle the size of the parameter
16807     // pack into the name. Computing the size of the parameters requires the
16808     // parameter types to be complete. Check that now.
16809     if (funcHasParameterSizeMangling(*this, Func))
16810       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16811 
16812     // In the MS C++ ABI, the compiler emits destructor variants where they are
16813     // used. If the destructor is used here but defined elsewhere, mark the
16814     // virtual base destructors referenced. If those virtual base destructors
16815     // are inline, this will ensure they are defined when emitting the complete
16816     // destructor variant. This checking may be redundant if the destructor is
16817     // provided later in this TU.
16818     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16819       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16820         CXXRecordDecl *Parent = Dtor->getParent();
16821         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16822           CheckCompleteDestructorVariant(Loc, Dtor);
16823       }
16824     }
16825 
16826     Func->markUsed(Context);
16827   }
16828 }
16829 
16830 /// Directly mark a variable odr-used. Given a choice, prefer to use
16831 /// MarkVariableReferenced since it does additional checks and then
16832 /// calls MarkVarDeclODRUsed.
16833 /// If the variable must be captured:
16834 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16835 ///  - else capture it in the DeclContext that maps to the
16836 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16837 static void
16838 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16839                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16840   // Keep track of used but undefined variables.
16841   // FIXME: We shouldn't suppress this warning for static data members.
16842   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16843       (!Var->isExternallyVisible() || Var->isInline() ||
16844        SemaRef.isExternalWithNoLinkageType(Var)) &&
16845       !(Var->isStaticDataMember() && Var->hasInit())) {
16846     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16847     if (old.isInvalid())
16848       old = Loc;
16849   }
16850   QualType CaptureType, DeclRefType;
16851   if (SemaRef.LangOpts.OpenMP)
16852     SemaRef.tryCaptureOpenMPLambdas(Var);
16853   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16854     /*EllipsisLoc*/ SourceLocation(),
16855     /*BuildAndDiagnose*/ true,
16856     CaptureType, DeclRefType,
16857     FunctionScopeIndexToStopAt);
16858 
16859   Var->markUsed(SemaRef.Context);
16860 }
16861 
16862 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16863                                              SourceLocation Loc,
16864                                              unsigned CapturingScopeIndex) {
16865   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16866 }
16867 
16868 static void
16869 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16870                                    ValueDecl *var, DeclContext *DC) {
16871   DeclContext *VarDC = var->getDeclContext();
16872 
16873   //  If the parameter still belongs to the translation unit, then
16874   //  we're actually just using one parameter in the declaration of
16875   //  the next.
16876   if (isa<ParmVarDecl>(var) &&
16877       isa<TranslationUnitDecl>(VarDC))
16878     return;
16879 
16880   // For C code, don't diagnose about capture if we're not actually in code
16881   // right now; it's impossible to write a non-constant expression outside of
16882   // function context, so we'll get other (more useful) diagnostics later.
16883   //
16884   // For C++, things get a bit more nasty... it would be nice to suppress this
16885   // diagnostic for certain cases like using a local variable in an array bound
16886   // for a member of a local class, but the correct predicate is not obvious.
16887   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16888     return;
16889 
16890   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16891   unsigned ContextKind = 3; // unknown
16892   if (isa<CXXMethodDecl>(VarDC) &&
16893       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16894     ContextKind = 2;
16895   } else if (isa<FunctionDecl>(VarDC)) {
16896     ContextKind = 0;
16897   } else if (isa<BlockDecl>(VarDC)) {
16898     ContextKind = 1;
16899   }
16900 
16901   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16902     << var << ValueKind << ContextKind << VarDC;
16903   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16904       << var;
16905 
16906   // FIXME: Add additional diagnostic info about class etc. which prevents
16907   // capture.
16908 }
16909 
16910 
16911 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16912                                       bool &SubCapturesAreNested,
16913                                       QualType &CaptureType,
16914                                       QualType &DeclRefType) {
16915    // Check whether we've already captured it.
16916   if (CSI->CaptureMap.count(Var)) {
16917     // If we found a capture, any subcaptures are nested.
16918     SubCapturesAreNested = true;
16919 
16920     // Retrieve the capture type for this variable.
16921     CaptureType = CSI->getCapture(Var).getCaptureType();
16922 
16923     // Compute the type of an expression that refers to this variable.
16924     DeclRefType = CaptureType.getNonReferenceType();
16925 
16926     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16927     // are mutable in the sense that user can change their value - they are
16928     // private instances of the captured declarations.
16929     const Capture &Cap = CSI->getCapture(Var);
16930     if (Cap.isCopyCapture() &&
16931         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16932         !(isa<CapturedRegionScopeInfo>(CSI) &&
16933           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16934       DeclRefType.addConst();
16935     return true;
16936   }
16937   return false;
16938 }
16939 
16940 // Only block literals, captured statements, and lambda expressions can
16941 // capture; other scopes don't work.
16942 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16943                                  SourceLocation Loc,
16944                                  const bool Diagnose, Sema &S) {
16945   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16946     return getLambdaAwareParentOfDeclContext(DC);
16947   else if (Var->hasLocalStorage()) {
16948     if (Diagnose)
16949        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16950   }
16951   return nullptr;
16952 }
16953 
16954 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16955 // certain types of variables (unnamed, variably modified types etc.)
16956 // so check for eligibility.
16957 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16958                                  SourceLocation Loc,
16959                                  const bool Diagnose, Sema &S) {
16960 
16961   bool IsBlock = isa<BlockScopeInfo>(CSI);
16962   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16963 
16964   // Lambdas are not allowed to capture unnamed variables
16965   // (e.g. anonymous unions).
16966   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16967   // assuming that's the intent.
16968   if (IsLambda && !Var->getDeclName()) {
16969     if (Diagnose) {
16970       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16971       S.Diag(Var->getLocation(), diag::note_declared_at);
16972     }
16973     return false;
16974   }
16975 
16976   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16977   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16978     if (Diagnose) {
16979       S.Diag(Loc, diag::err_ref_vm_type);
16980       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16981     }
16982     return false;
16983   }
16984   // Prohibit structs with flexible array members too.
16985   // We cannot capture what is in the tail end of the struct.
16986   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16987     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16988       if (Diagnose) {
16989         if (IsBlock)
16990           S.Diag(Loc, diag::err_ref_flexarray_type);
16991         else
16992           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16993         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16994       }
16995       return false;
16996     }
16997   }
16998   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16999   // Lambdas and captured statements are not allowed to capture __block
17000   // variables; they don't support the expected semantics.
17001   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17002     if (Diagnose) {
17003       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17004       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17005     }
17006     return false;
17007   }
17008   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17009   if (S.getLangOpts().OpenCL && IsBlock &&
17010       Var->getType()->isBlockPointerType()) {
17011     if (Diagnose)
17012       S.Diag(Loc, diag::err_opencl_block_ref_block);
17013     return false;
17014   }
17015 
17016   return true;
17017 }
17018 
17019 // Returns true if the capture by block was successful.
17020 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17021                                  SourceLocation Loc,
17022                                  const bool BuildAndDiagnose,
17023                                  QualType &CaptureType,
17024                                  QualType &DeclRefType,
17025                                  const bool Nested,
17026                                  Sema &S, bool Invalid) {
17027   bool ByRef = false;
17028 
17029   // Blocks are not allowed to capture arrays, excepting OpenCL.
17030   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17031   // (decayed to pointers).
17032   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17033     if (BuildAndDiagnose) {
17034       S.Diag(Loc, diag::err_ref_array_type);
17035       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17036       Invalid = true;
17037     } else {
17038       return false;
17039     }
17040   }
17041 
17042   // Forbid the block-capture of autoreleasing variables.
17043   if (!Invalid &&
17044       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17045     if (BuildAndDiagnose) {
17046       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17047         << /*block*/ 0;
17048       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17049       Invalid = true;
17050     } else {
17051       return false;
17052     }
17053   }
17054 
17055   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17056   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17057     QualType PointeeTy = PT->getPointeeType();
17058 
17059     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17060         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17061         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17062       if (BuildAndDiagnose) {
17063         SourceLocation VarLoc = Var->getLocation();
17064         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17065         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17066       }
17067     }
17068   }
17069 
17070   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17071   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17072       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17073     // Block capture by reference does not change the capture or
17074     // declaration reference types.
17075     ByRef = true;
17076   } else {
17077     // Block capture by copy introduces 'const'.
17078     CaptureType = CaptureType.getNonReferenceType().withConst();
17079     DeclRefType = CaptureType;
17080   }
17081 
17082   // Actually capture the variable.
17083   if (BuildAndDiagnose)
17084     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17085                     CaptureType, Invalid);
17086 
17087   return !Invalid;
17088 }
17089 
17090 
17091 /// Capture the given variable in the captured region.
17092 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17093                                     VarDecl *Var,
17094                                     SourceLocation Loc,
17095                                     const bool BuildAndDiagnose,
17096                                     QualType &CaptureType,
17097                                     QualType &DeclRefType,
17098                                     const bool RefersToCapturedVariable,
17099                                     Sema &S, bool Invalid) {
17100   // By default, capture variables by reference.
17101   bool ByRef = true;
17102   // Using an LValue reference type is consistent with Lambdas (see below).
17103   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17104     if (S.isOpenMPCapturedDecl(Var)) {
17105       bool HasConst = DeclRefType.isConstQualified();
17106       DeclRefType = DeclRefType.getUnqualifiedType();
17107       // Don't lose diagnostics about assignments to const.
17108       if (HasConst)
17109         DeclRefType.addConst();
17110     }
17111     // Do not capture firstprivates in tasks.
17112     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17113         OMPC_unknown)
17114       return true;
17115     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17116                                     RSI->OpenMPCaptureLevel);
17117   }
17118 
17119   if (ByRef)
17120     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17121   else
17122     CaptureType = DeclRefType;
17123 
17124   // Actually capture the variable.
17125   if (BuildAndDiagnose)
17126     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17127                     Loc, SourceLocation(), CaptureType, Invalid);
17128 
17129   return !Invalid;
17130 }
17131 
17132 /// Capture the given variable in the lambda.
17133 static bool captureInLambda(LambdaScopeInfo *LSI,
17134                             VarDecl *Var,
17135                             SourceLocation Loc,
17136                             const bool BuildAndDiagnose,
17137                             QualType &CaptureType,
17138                             QualType &DeclRefType,
17139                             const bool RefersToCapturedVariable,
17140                             const Sema::TryCaptureKind Kind,
17141                             SourceLocation EllipsisLoc,
17142                             const bool IsTopScope,
17143                             Sema &S, bool Invalid) {
17144   // Determine whether we are capturing by reference or by value.
17145   bool ByRef = false;
17146   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17147     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17148   } else {
17149     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17150   }
17151 
17152   // Compute the type of the field that will capture this variable.
17153   if (ByRef) {
17154     // C++11 [expr.prim.lambda]p15:
17155     //   An entity is captured by reference if it is implicitly or
17156     //   explicitly captured but not captured by copy. It is
17157     //   unspecified whether additional unnamed non-static data
17158     //   members are declared in the closure type for entities
17159     //   captured by reference.
17160     //
17161     // FIXME: It is not clear whether we want to build an lvalue reference
17162     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17163     // to do the former, while EDG does the latter. Core issue 1249 will
17164     // clarify, but for now we follow GCC because it's a more permissive and
17165     // easily defensible position.
17166     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17167   } else {
17168     // C++11 [expr.prim.lambda]p14:
17169     //   For each entity captured by copy, an unnamed non-static
17170     //   data member is declared in the closure type. The
17171     //   declaration order of these members is unspecified. The type
17172     //   of such a data member is the type of the corresponding
17173     //   captured entity if the entity is not a reference to an
17174     //   object, or the referenced type otherwise. [Note: If the
17175     //   captured entity is a reference to a function, the
17176     //   corresponding data member is also a reference to a
17177     //   function. - end note ]
17178     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17179       if (!RefType->getPointeeType()->isFunctionType())
17180         CaptureType = RefType->getPointeeType();
17181     }
17182 
17183     // Forbid the lambda copy-capture of autoreleasing variables.
17184     if (!Invalid &&
17185         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17186       if (BuildAndDiagnose) {
17187         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17188         S.Diag(Var->getLocation(), diag::note_previous_decl)
17189           << Var->getDeclName();
17190         Invalid = true;
17191       } else {
17192         return false;
17193       }
17194     }
17195 
17196     // Make sure that by-copy captures are of a complete and non-abstract type.
17197     if (!Invalid && BuildAndDiagnose) {
17198       if (!CaptureType->isDependentType() &&
17199           S.RequireCompleteSizedType(
17200               Loc, CaptureType,
17201               diag::err_capture_of_incomplete_or_sizeless_type,
17202               Var->getDeclName()))
17203         Invalid = true;
17204       else if (S.RequireNonAbstractType(Loc, CaptureType,
17205                                         diag::err_capture_of_abstract_type))
17206         Invalid = true;
17207     }
17208   }
17209 
17210   // Compute the type of a reference to this captured variable.
17211   if (ByRef)
17212     DeclRefType = CaptureType.getNonReferenceType();
17213   else {
17214     // C++ [expr.prim.lambda]p5:
17215     //   The closure type for a lambda-expression has a public inline
17216     //   function call operator [...]. This function call operator is
17217     //   declared const (9.3.1) if and only if the lambda-expression's
17218     //   parameter-declaration-clause is not followed by mutable.
17219     DeclRefType = CaptureType.getNonReferenceType();
17220     if (!LSI->Mutable && !CaptureType->isReferenceType())
17221       DeclRefType.addConst();
17222   }
17223 
17224   // Add the capture.
17225   if (BuildAndDiagnose)
17226     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17227                     Loc, EllipsisLoc, CaptureType, Invalid);
17228 
17229   return !Invalid;
17230 }
17231 
17232 bool Sema::tryCaptureVariable(
17233     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17234     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17235     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17236   // An init-capture is notionally from the context surrounding its
17237   // declaration, but its parent DC is the lambda class.
17238   DeclContext *VarDC = Var->getDeclContext();
17239   if (Var->isInitCapture())
17240     VarDC = VarDC->getParent();
17241 
17242   DeclContext *DC = CurContext;
17243   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17244       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17245   // We need to sync up the Declaration Context with the
17246   // FunctionScopeIndexToStopAt
17247   if (FunctionScopeIndexToStopAt) {
17248     unsigned FSIndex = FunctionScopes.size() - 1;
17249     while (FSIndex != MaxFunctionScopesIndex) {
17250       DC = getLambdaAwareParentOfDeclContext(DC);
17251       --FSIndex;
17252     }
17253   }
17254 
17255 
17256   // If the variable is declared in the current context, there is no need to
17257   // capture it.
17258   if (VarDC == DC) return true;
17259 
17260   // Capture global variables if it is required to use private copy of this
17261   // variable.
17262   bool IsGlobal = !Var->hasLocalStorage();
17263   if (IsGlobal &&
17264       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17265                                                 MaxFunctionScopesIndex)))
17266     return true;
17267   Var = Var->getCanonicalDecl();
17268 
17269   // Walk up the stack to determine whether we can capture the variable,
17270   // performing the "simple" checks that don't depend on type. We stop when
17271   // we've either hit the declared scope of the variable or find an existing
17272   // capture of that variable.  We start from the innermost capturing-entity
17273   // (the DC) and ensure that all intervening capturing-entities
17274   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17275   // declcontext can either capture the variable or have already captured
17276   // the variable.
17277   CaptureType = Var->getType();
17278   DeclRefType = CaptureType.getNonReferenceType();
17279   bool Nested = false;
17280   bool Explicit = (Kind != TryCapture_Implicit);
17281   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17282   do {
17283     // Only block literals, captured statements, and lambda expressions can
17284     // capture; other scopes don't work.
17285     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17286                                                               ExprLoc,
17287                                                               BuildAndDiagnose,
17288                                                               *this);
17289     // We need to check for the parent *first* because, if we *have*
17290     // private-captured a global variable, we need to recursively capture it in
17291     // intermediate blocks, lambdas, etc.
17292     if (!ParentDC) {
17293       if (IsGlobal) {
17294         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17295         break;
17296       }
17297       return true;
17298     }
17299 
17300     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17301     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17302 
17303 
17304     // Check whether we've already captured it.
17305     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17306                                              DeclRefType)) {
17307       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17308       break;
17309     }
17310     // If we are instantiating a generic lambda call operator body,
17311     // we do not want to capture new variables.  What was captured
17312     // during either a lambdas transformation or initial parsing
17313     // should be used.
17314     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17315       if (BuildAndDiagnose) {
17316         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17317         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17318           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17319           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17320           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17321         } else
17322           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17323       }
17324       return true;
17325     }
17326 
17327     // Try to capture variable-length arrays types.
17328     if (Var->getType()->isVariablyModifiedType()) {
17329       // We're going to walk down into the type and look for VLA
17330       // expressions.
17331       QualType QTy = Var->getType();
17332       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17333         QTy = PVD->getOriginalType();
17334       captureVariablyModifiedType(Context, QTy, CSI);
17335     }
17336 
17337     if (getLangOpts().OpenMP) {
17338       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17339         // OpenMP private variables should not be captured in outer scope, so
17340         // just break here. Similarly, global variables that are captured in a
17341         // target region should not be captured outside the scope of the region.
17342         if (RSI->CapRegionKind == CR_OpenMP) {
17343           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17344               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17345           // If the variable is private (i.e. not captured) and has variably
17346           // modified type, we still need to capture the type for correct
17347           // codegen in all regions, associated with the construct. Currently,
17348           // it is captured in the innermost captured region only.
17349           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17350               Var->getType()->isVariablyModifiedType()) {
17351             QualType QTy = Var->getType();
17352             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17353               QTy = PVD->getOriginalType();
17354             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17355                  I < E; ++I) {
17356               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17357                   FunctionScopes[FunctionScopesIndex - I]);
17358               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17359                      "Wrong number of captured regions associated with the "
17360                      "OpenMP construct.");
17361               captureVariablyModifiedType(Context, QTy, OuterRSI);
17362             }
17363           }
17364           bool IsTargetCap =
17365               IsOpenMPPrivateDecl != OMPC_private &&
17366               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17367                                          RSI->OpenMPCaptureLevel);
17368           // Do not capture global if it is not privatized in outer regions.
17369           bool IsGlobalCap =
17370               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17371                                                      RSI->OpenMPCaptureLevel);
17372 
17373           // When we detect target captures we are looking from inside the
17374           // target region, therefore we need to propagate the capture from the
17375           // enclosing region. Therefore, the capture is not initially nested.
17376           if (IsTargetCap)
17377             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17378 
17379           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17380               (IsGlobal && !IsGlobalCap)) {
17381             Nested = !IsTargetCap;
17382             DeclRefType = DeclRefType.getUnqualifiedType();
17383             CaptureType = Context.getLValueReferenceType(DeclRefType);
17384             break;
17385           }
17386         }
17387       }
17388     }
17389     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17390       // No capture-default, and this is not an explicit capture
17391       // so cannot capture this variable.
17392       if (BuildAndDiagnose) {
17393         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17394         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17395         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17396           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17397                diag::note_lambda_decl);
17398         // FIXME: If we error out because an outer lambda can not implicitly
17399         // capture a variable that an inner lambda explicitly captures, we
17400         // should have the inner lambda do the explicit capture - because
17401         // it makes for cleaner diagnostics later.  This would purely be done
17402         // so that the diagnostic does not misleadingly claim that a variable
17403         // can not be captured by a lambda implicitly even though it is captured
17404         // explicitly.  Suggestion:
17405         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17406         //    at the function head
17407         //  - cache the StartingDeclContext - this must be a lambda
17408         //  - captureInLambda in the innermost lambda the variable.
17409       }
17410       return true;
17411     }
17412 
17413     FunctionScopesIndex--;
17414     DC = ParentDC;
17415     Explicit = false;
17416   } while (!VarDC->Equals(DC));
17417 
17418   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17419   // computing the type of the capture at each step, checking type-specific
17420   // requirements, and adding captures if requested.
17421   // If the variable had already been captured previously, we start capturing
17422   // at the lambda nested within that one.
17423   bool Invalid = false;
17424   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17425        ++I) {
17426     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17427 
17428     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17429     // certain types of variables (unnamed, variably modified types etc.)
17430     // so check for eligibility.
17431     if (!Invalid)
17432       Invalid =
17433           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17434 
17435     // After encountering an error, if we're actually supposed to capture, keep
17436     // capturing in nested contexts to suppress any follow-on diagnostics.
17437     if (Invalid && !BuildAndDiagnose)
17438       return true;
17439 
17440     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17441       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17442                                DeclRefType, Nested, *this, Invalid);
17443       Nested = true;
17444     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17445       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17446                                          CaptureType, DeclRefType, Nested,
17447                                          *this, Invalid);
17448       Nested = true;
17449     } else {
17450       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17451       Invalid =
17452           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17453                            DeclRefType, Nested, Kind, EllipsisLoc,
17454                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17455       Nested = true;
17456     }
17457 
17458     if (Invalid && !BuildAndDiagnose)
17459       return true;
17460   }
17461   return Invalid;
17462 }
17463 
17464 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17465                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17466   QualType CaptureType;
17467   QualType DeclRefType;
17468   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17469                             /*BuildAndDiagnose=*/true, CaptureType,
17470                             DeclRefType, nullptr);
17471 }
17472 
17473 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17474   QualType CaptureType;
17475   QualType DeclRefType;
17476   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17477                              /*BuildAndDiagnose=*/false, CaptureType,
17478                              DeclRefType, nullptr);
17479 }
17480 
17481 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17482   QualType CaptureType;
17483   QualType DeclRefType;
17484 
17485   // Determine whether we can capture this variable.
17486   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17487                          /*BuildAndDiagnose=*/false, CaptureType,
17488                          DeclRefType, nullptr))
17489     return QualType();
17490 
17491   return DeclRefType;
17492 }
17493 
17494 namespace {
17495 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17496 // The produced TemplateArgumentListInfo* points to data stored within this
17497 // object, so should only be used in contexts where the pointer will not be
17498 // used after the CopiedTemplateArgs object is destroyed.
17499 class CopiedTemplateArgs {
17500   bool HasArgs;
17501   TemplateArgumentListInfo TemplateArgStorage;
17502 public:
17503   template<typename RefExpr>
17504   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17505     if (HasArgs)
17506       E->copyTemplateArgumentsInto(TemplateArgStorage);
17507   }
17508   operator TemplateArgumentListInfo*()
17509 #ifdef __has_cpp_attribute
17510 #if __has_cpp_attribute(clang::lifetimebound)
17511   [[clang::lifetimebound]]
17512 #endif
17513 #endif
17514   {
17515     return HasArgs ? &TemplateArgStorage : nullptr;
17516   }
17517 };
17518 }
17519 
17520 /// Walk the set of potential results of an expression and mark them all as
17521 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17522 ///
17523 /// \return A new expression if we found any potential results, ExprEmpty() if
17524 ///         not, and ExprError() if we diagnosed an error.
17525 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17526                                                       NonOdrUseReason NOUR) {
17527   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17528   // an object that satisfies the requirements for appearing in a
17529   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17530   // is immediately applied."  This function handles the lvalue-to-rvalue
17531   // conversion part.
17532   //
17533   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17534   // transform it into the relevant kind of non-odr-use node and rebuild the
17535   // tree of nodes leading to it.
17536   //
17537   // This is a mini-TreeTransform that only transforms a restricted subset of
17538   // nodes (and only certain operands of them).
17539 
17540   // Rebuild a subexpression.
17541   auto Rebuild = [&](Expr *Sub) {
17542     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17543   };
17544 
17545   // Check whether a potential result satisfies the requirements of NOUR.
17546   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17547     // Any entity other than a VarDecl is always odr-used whenever it's named
17548     // in a potentially-evaluated expression.
17549     auto *VD = dyn_cast<VarDecl>(D);
17550     if (!VD)
17551       return true;
17552 
17553     // C++2a [basic.def.odr]p4:
17554     //   A variable x whose name appears as a potentially-evalauted expression
17555     //   e is odr-used by e unless
17556     //   -- x is a reference that is usable in constant expressions, or
17557     //   -- x is a variable of non-reference type that is usable in constant
17558     //      expressions and has no mutable subobjects, and e is an element of
17559     //      the set of potential results of an expression of
17560     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17561     //      conversion is applied, or
17562     //   -- x is a variable of non-reference type, and e is an element of the
17563     //      set of potential results of a discarded-value expression to which
17564     //      the lvalue-to-rvalue conversion is not applied
17565     //
17566     // We check the first bullet and the "potentially-evaluated" condition in
17567     // BuildDeclRefExpr. We check the type requirements in the second bullet
17568     // in CheckLValueToRValueConversionOperand below.
17569     switch (NOUR) {
17570     case NOUR_None:
17571     case NOUR_Unevaluated:
17572       llvm_unreachable("unexpected non-odr-use-reason");
17573 
17574     case NOUR_Constant:
17575       // Constant references were handled when they were built.
17576       if (VD->getType()->isReferenceType())
17577         return true;
17578       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17579         if (RD->hasMutableFields())
17580           return true;
17581       if (!VD->isUsableInConstantExpressions(S.Context))
17582         return true;
17583       break;
17584 
17585     case NOUR_Discarded:
17586       if (VD->getType()->isReferenceType())
17587         return true;
17588       break;
17589     }
17590     return false;
17591   };
17592 
17593   // Mark that this expression does not constitute an odr-use.
17594   auto MarkNotOdrUsed = [&] {
17595     S.MaybeODRUseExprs.remove(E);
17596     if (LambdaScopeInfo *LSI = S.getCurLambda())
17597       LSI->markVariableExprAsNonODRUsed(E);
17598   };
17599 
17600   // C++2a [basic.def.odr]p2:
17601   //   The set of potential results of an expression e is defined as follows:
17602   switch (E->getStmtClass()) {
17603   //   -- If e is an id-expression, ...
17604   case Expr::DeclRefExprClass: {
17605     auto *DRE = cast<DeclRefExpr>(E);
17606     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17607       break;
17608 
17609     // Rebuild as a non-odr-use DeclRefExpr.
17610     MarkNotOdrUsed();
17611     return DeclRefExpr::Create(
17612         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17613         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17614         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17615         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17616   }
17617 
17618   case Expr::FunctionParmPackExprClass: {
17619     auto *FPPE = cast<FunctionParmPackExpr>(E);
17620     // If any of the declarations in the pack is odr-used, then the expression
17621     // as a whole constitutes an odr-use.
17622     for (VarDecl *D : *FPPE)
17623       if (IsPotentialResultOdrUsed(D))
17624         return ExprEmpty();
17625 
17626     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17627     // nothing cares about whether we marked this as an odr-use, but it might
17628     // be useful for non-compiler tools.
17629     MarkNotOdrUsed();
17630     break;
17631   }
17632 
17633   //   -- If e is a subscripting operation with an array operand...
17634   case Expr::ArraySubscriptExprClass: {
17635     auto *ASE = cast<ArraySubscriptExpr>(E);
17636     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17637     if (!OldBase->getType()->isArrayType())
17638       break;
17639     ExprResult Base = Rebuild(OldBase);
17640     if (!Base.isUsable())
17641       return Base;
17642     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17643     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17644     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17645     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17646                                      ASE->getRBracketLoc());
17647   }
17648 
17649   case Expr::MemberExprClass: {
17650     auto *ME = cast<MemberExpr>(E);
17651     // -- If e is a class member access expression [...] naming a non-static
17652     //    data member...
17653     if (isa<FieldDecl>(ME->getMemberDecl())) {
17654       ExprResult Base = Rebuild(ME->getBase());
17655       if (!Base.isUsable())
17656         return Base;
17657       return MemberExpr::Create(
17658           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17659           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17660           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17661           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17662           ME->getObjectKind(), ME->isNonOdrUse());
17663     }
17664 
17665     if (ME->getMemberDecl()->isCXXInstanceMember())
17666       break;
17667 
17668     // -- If e is a class member access expression naming a static data member,
17669     //    ...
17670     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17671       break;
17672 
17673     // Rebuild as a non-odr-use MemberExpr.
17674     MarkNotOdrUsed();
17675     return MemberExpr::Create(
17676         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17677         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17678         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17679         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17680     return ExprEmpty();
17681   }
17682 
17683   case Expr::BinaryOperatorClass: {
17684     auto *BO = cast<BinaryOperator>(E);
17685     Expr *LHS = BO->getLHS();
17686     Expr *RHS = BO->getRHS();
17687     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17688     if (BO->getOpcode() == BO_PtrMemD) {
17689       ExprResult Sub = Rebuild(LHS);
17690       if (!Sub.isUsable())
17691         return Sub;
17692       LHS = Sub.get();
17693     //   -- If e is a comma expression, ...
17694     } else if (BO->getOpcode() == BO_Comma) {
17695       ExprResult Sub = Rebuild(RHS);
17696       if (!Sub.isUsable())
17697         return Sub;
17698       RHS = Sub.get();
17699     } else {
17700       break;
17701     }
17702     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17703                         LHS, RHS);
17704   }
17705 
17706   //   -- If e has the form (e1)...
17707   case Expr::ParenExprClass: {
17708     auto *PE = cast<ParenExpr>(E);
17709     ExprResult Sub = Rebuild(PE->getSubExpr());
17710     if (!Sub.isUsable())
17711       return Sub;
17712     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17713   }
17714 
17715   //   -- If e is a glvalue conditional expression, ...
17716   // We don't apply this to a binary conditional operator. FIXME: Should we?
17717   case Expr::ConditionalOperatorClass: {
17718     auto *CO = cast<ConditionalOperator>(E);
17719     ExprResult LHS = Rebuild(CO->getLHS());
17720     if (LHS.isInvalid())
17721       return ExprError();
17722     ExprResult RHS = Rebuild(CO->getRHS());
17723     if (RHS.isInvalid())
17724       return ExprError();
17725     if (!LHS.isUsable() && !RHS.isUsable())
17726       return ExprEmpty();
17727     if (!LHS.isUsable())
17728       LHS = CO->getLHS();
17729     if (!RHS.isUsable())
17730       RHS = CO->getRHS();
17731     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17732                                 CO->getCond(), LHS.get(), RHS.get());
17733   }
17734 
17735   // [Clang extension]
17736   //   -- If e has the form __extension__ e1...
17737   case Expr::UnaryOperatorClass: {
17738     auto *UO = cast<UnaryOperator>(E);
17739     if (UO->getOpcode() != UO_Extension)
17740       break;
17741     ExprResult Sub = Rebuild(UO->getSubExpr());
17742     if (!Sub.isUsable())
17743       return Sub;
17744     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17745                           Sub.get());
17746   }
17747 
17748   // [Clang extension]
17749   //   -- If e has the form _Generic(...), the set of potential results is the
17750   //      union of the sets of potential results of the associated expressions.
17751   case Expr::GenericSelectionExprClass: {
17752     auto *GSE = cast<GenericSelectionExpr>(E);
17753 
17754     SmallVector<Expr *, 4> AssocExprs;
17755     bool AnyChanged = false;
17756     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17757       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17758       if (AssocExpr.isInvalid())
17759         return ExprError();
17760       if (AssocExpr.isUsable()) {
17761         AssocExprs.push_back(AssocExpr.get());
17762         AnyChanged = true;
17763       } else {
17764         AssocExprs.push_back(OrigAssocExpr);
17765       }
17766     }
17767 
17768     return AnyChanged ? S.CreateGenericSelectionExpr(
17769                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17770                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17771                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17772                       : ExprEmpty();
17773   }
17774 
17775   // [Clang extension]
17776   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17777   //      results is the union of the sets of potential results of the
17778   //      second and third subexpressions.
17779   case Expr::ChooseExprClass: {
17780     auto *CE = cast<ChooseExpr>(E);
17781 
17782     ExprResult LHS = Rebuild(CE->getLHS());
17783     if (LHS.isInvalid())
17784       return ExprError();
17785 
17786     ExprResult RHS = Rebuild(CE->getLHS());
17787     if (RHS.isInvalid())
17788       return ExprError();
17789 
17790     if (!LHS.get() && !RHS.get())
17791       return ExprEmpty();
17792     if (!LHS.isUsable())
17793       LHS = CE->getLHS();
17794     if (!RHS.isUsable())
17795       RHS = CE->getRHS();
17796 
17797     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17798                              RHS.get(), CE->getRParenLoc());
17799   }
17800 
17801   // Step through non-syntactic nodes.
17802   case Expr::ConstantExprClass: {
17803     auto *CE = cast<ConstantExpr>(E);
17804     ExprResult Sub = Rebuild(CE->getSubExpr());
17805     if (!Sub.isUsable())
17806       return Sub;
17807     return ConstantExpr::Create(S.Context, Sub.get());
17808   }
17809 
17810   // We could mostly rely on the recursive rebuilding to rebuild implicit
17811   // casts, but not at the top level, so rebuild them here.
17812   case Expr::ImplicitCastExprClass: {
17813     auto *ICE = cast<ImplicitCastExpr>(E);
17814     // Only step through the narrow set of cast kinds we expect to encounter.
17815     // Anything else suggests we've left the region in which potential results
17816     // can be found.
17817     switch (ICE->getCastKind()) {
17818     case CK_NoOp:
17819     case CK_DerivedToBase:
17820     case CK_UncheckedDerivedToBase: {
17821       ExprResult Sub = Rebuild(ICE->getSubExpr());
17822       if (!Sub.isUsable())
17823         return Sub;
17824       CXXCastPath Path(ICE->path());
17825       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17826                                  ICE->getValueKind(), &Path);
17827     }
17828 
17829     default:
17830       break;
17831     }
17832     break;
17833   }
17834 
17835   default:
17836     break;
17837   }
17838 
17839   // Can't traverse through this node. Nothing to do.
17840   return ExprEmpty();
17841 }
17842 
17843 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17844   // Check whether the operand is or contains an object of non-trivial C union
17845   // type.
17846   if (E->getType().isVolatileQualified() &&
17847       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17848        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17849     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17850                           Sema::NTCUC_LValueToRValueVolatile,
17851                           NTCUK_Destruct|NTCUK_Copy);
17852 
17853   // C++2a [basic.def.odr]p4:
17854   //   [...] an expression of non-volatile-qualified non-class type to which
17855   //   the lvalue-to-rvalue conversion is applied [...]
17856   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17857     return E;
17858 
17859   ExprResult Result =
17860       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17861   if (Result.isInvalid())
17862     return ExprError();
17863   return Result.get() ? Result : E;
17864 }
17865 
17866 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17867   Res = CorrectDelayedTyposInExpr(Res);
17868 
17869   if (!Res.isUsable())
17870     return Res;
17871 
17872   // If a constant-expression is a reference to a variable where we delay
17873   // deciding whether it is an odr-use, just assume we will apply the
17874   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17875   // (a non-type template argument), we have special handling anyway.
17876   return CheckLValueToRValueConversionOperand(Res.get());
17877 }
17878 
17879 void Sema::CleanupVarDeclMarking() {
17880   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17881   // call.
17882   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17883   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17884 
17885   for (Expr *E : LocalMaybeODRUseExprs) {
17886     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17887       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17888                          DRE->getLocation(), *this);
17889     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17890       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17891                          *this);
17892     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17893       for (VarDecl *VD : *FP)
17894         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17895     } else {
17896       llvm_unreachable("Unexpected expression");
17897     }
17898   }
17899 
17900   assert(MaybeODRUseExprs.empty() &&
17901          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17902 }
17903 
17904 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17905                                     VarDecl *Var, Expr *E) {
17906   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17907           isa<FunctionParmPackExpr>(E)) &&
17908          "Invalid Expr argument to DoMarkVarDeclReferenced");
17909   Var->setReferenced();
17910 
17911   if (Var->isInvalidDecl())
17912     return;
17913 
17914   // Record a CUDA/HIP static device/constant variable if it is referenced
17915   // by host code. This is done conservatively, when the variable is referenced
17916   // in any of the following contexts:
17917   //   - a non-function context
17918   //   - a host function
17919   //   - a host device function
17920   // This also requires the reference of the static device/constant variable by
17921   // host code to be visible in the device compilation for the compiler to be
17922   // able to externalize the static device/constant variable.
17923   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17924     auto *CurContext = SemaRef.CurContext;
17925     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17926         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17927         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17928          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17929       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17930   }
17931 
17932   auto *MSI = Var->getMemberSpecializationInfo();
17933   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17934                                        : Var->getTemplateSpecializationKind();
17935 
17936   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17937   bool UsableInConstantExpr =
17938       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17939 
17940   // C++20 [expr.const]p12:
17941   //   A variable [...] is needed for constant evaluation if it is [...] a
17942   //   variable whose name appears as a potentially constant evaluated
17943   //   expression that is either a contexpr variable or is of non-volatile
17944   //   const-qualified integral type or of reference type
17945   bool NeededForConstantEvaluation =
17946       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17947 
17948   bool NeedDefinition =
17949       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17950 
17951   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17952          "Can't instantiate a partial template specialization.");
17953 
17954   // If this might be a member specialization of a static data member, check
17955   // the specialization is visible. We already did the checks for variable
17956   // template specializations when we created them.
17957   if (NeedDefinition && TSK != TSK_Undeclared &&
17958       !isa<VarTemplateSpecializationDecl>(Var))
17959     SemaRef.checkSpecializationVisibility(Loc, Var);
17960 
17961   // Perform implicit instantiation of static data members, static data member
17962   // templates of class templates, and variable template specializations. Delay
17963   // instantiations of variable templates, except for those that could be used
17964   // in a constant expression.
17965   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17966     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17967     // instantiation declaration if a variable is usable in a constant
17968     // expression (among other cases).
17969     bool TryInstantiating =
17970         TSK == TSK_ImplicitInstantiation ||
17971         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17972 
17973     if (TryInstantiating) {
17974       SourceLocation PointOfInstantiation =
17975           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17976       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17977       if (FirstInstantiation) {
17978         PointOfInstantiation = Loc;
17979         if (MSI)
17980           MSI->setPointOfInstantiation(PointOfInstantiation);
17981         else
17982           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17983       }
17984 
17985       if (UsableInConstantExpr) {
17986         // Do not defer instantiations of variables that could be used in a
17987         // constant expression.
17988         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17989           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17990         });
17991       } else if (FirstInstantiation ||
17992                  isa<VarTemplateSpecializationDecl>(Var)) {
17993         // FIXME: For a specialization of a variable template, we don't
17994         // distinguish between "declaration and type implicitly instantiated"
17995         // and "implicit instantiation of definition requested", so we have
17996         // no direct way to avoid enqueueing the pending instantiation
17997         // multiple times.
17998         SemaRef.PendingInstantiations
17999             .push_back(std::make_pair(Var, PointOfInstantiation));
18000       }
18001     }
18002   }
18003 
18004   // C++2a [basic.def.odr]p4:
18005   //   A variable x whose name appears as a potentially-evaluated expression e
18006   //   is odr-used by e unless
18007   //   -- x is a reference that is usable in constant expressions
18008   //   -- x is a variable of non-reference type that is usable in constant
18009   //      expressions and has no mutable subobjects [FIXME], and e is an
18010   //      element of the set of potential results of an expression of
18011   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18012   //      conversion is applied
18013   //   -- x is a variable of non-reference type, and e is an element of the set
18014   //      of potential results of a discarded-value expression to which the
18015   //      lvalue-to-rvalue conversion is not applied [FIXME]
18016   //
18017   // We check the first part of the second bullet here, and
18018   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18019   // FIXME: To get the third bullet right, we need to delay this even for
18020   // variables that are not usable in constant expressions.
18021 
18022   // If we already know this isn't an odr-use, there's nothing more to do.
18023   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18024     if (DRE->isNonOdrUse())
18025       return;
18026   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18027     if (ME->isNonOdrUse())
18028       return;
18029 
18030   switch (OdrUse) {
18031   case OdrUseContext::None:
18032     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18033            "missing non-odr-use marking for unevaluated decl ref");
18034     break;
18035 
18036   case OdrUseContext::FormallyOdrUsed:
18037     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18038     // behavior.
18039     break;
18040 
18041   case OdrUseContext::Used:
18042     // If we might later find that this expression isn't actually an odr-use,
18043     // delay the marking.
18044     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18045       SemaRef.MaybeODRUseExprs.insert(E);
18046     else
18047       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18048     break;
18049 
18050   case OdrUseContext::Dependent:
18051     // If this is a dependent context, we don't need to mark variables as
18052     // odr-used, but we may still need to track them for lambda capture.
18053     // FIXME: Do we also need to do this inside dependent typeid expressions
18054     // (which are modeled as unevaluated at this point)?
18055     const bool RefersToEnclosingScope =
18056         (SemaRef.CurContext != Var->getDeclContext() &&
18057          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18058     if (RefersToEnclosingScope) {
18059       LambdaScopeInfo *const LSI =
18060           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18061       if (LSI && (!LSI->CallOperator ||
18062                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18063         // If a variable could potentially be odr-used, defer marking it so
18064         // until we finish analyzing the full expression for any
18065         // lvalue-to-rvalue
18066         // or discarded value conversions that would obviate odr-use.
18067         // Add it to the list of potential captures that will be analyzed
18068         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18069         // unless the variable is a reference that was initialized by a constant
18070         // expression (this will never need to be captured or odr-used).
18071         //
18072         // FIXME: We can simplify this a lot after implementing P0588R1.
18073         assert(E && "Capture variable should be used in an expression.");
18074         if (!Var->getType()->isReferenceType() ||
18075             !Var->isUsableInConstantExpressions(SemaRef.Context))
18076           LSI->addPotentialCapture(E->IgnoreParens());
18077       }
18078     }
18079     break;
18080   }
18081 }
18082 
18083 /// Mark a variable referenced, and check whether it is odr-used
18084 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18085 /// used directly for normal expressions referring to VarDecl.
18086 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18087   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18088 }
18089 
18090 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18091                                Decl *D, Expr *E, bool MightBeOdrUse) {
18092   if (SemaRef.isInOpenMPDeclareTargetContext())
18093     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18094 
18095   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18096     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18097     return;
18098   }
18099 
18100   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18101 
18102   // If this is a call to a method via a cast, also mark the method in the
18103   // derived class used in case codegen can devirtualize the call.
18104   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18105   if (!ME)
18106     return;
18107   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18108   if (!MD)
18109     return;
18110   // Only attempt to devirtualize if this is truly a virtual call.
18111   bool IsVirtualCall = MD->isVirtual() &&
18112                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18113   if (!IsVirtualCall)
18114     return;
18115 
18116   // If it's possible to devirtualize the call, mark the called function
18117   // referenced.
18118   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18119       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18120   if (DM)
18121     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18122 }
18123 
18124 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18125 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18126   // TODO: update this with DR# once a defect report is filed.
18127   // C++11 defect. The address of a pure member should not be an ODR use, even
18128   // if it's a qualified reference.
18129   bool OdrUse = true;
18130   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18131     if (Method->isVirtual() &&
18132         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18133       OdrUse = false;
18134 
18135   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18136     if (!isConstantEvaluated() && FD->isConsteval() &&
18137         !RebuildingImmediateInvocation)
18138       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18139   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18140 }
18141 
18142 /// Perform reference-marking and odr-use handling for a MemberExpr.
18143 void Sema::MarkMemberReferenced(MemberExpr *E) {
18144   // C++11 [basic.def.odr]p2:
18145   //   A non-overloaded function whose name appears as a potentially-evaluated
18146   //   expression or a member of a set of candidate functions, if selected by
18147   //   overload resolution when referred to from a potentially-evaluated
18148   //   expression, is odr-used, unless it is a pure virtual function and its
18149   //   name is not explicitly qualified.
18150   bool MightBeOdrUse = true;
18151   if (E->performsVirtualDispatch(getLangOpts())) {
18152     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18153       if (Method->isPure())
18154         MightBeOdrUse = false;
18155   }
18156   SourceLocation Loc =
18157       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18158   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18159 }
18160 
18161 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18162 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18163   for (VarDecl *VD : *E)
18164     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18165 }
18166 
18167 /// Perform marking for a reference to an arbitrary declaration.  It
18168 /// marks the declaration referenced, and performs odr-use checking for
18169 /// functions and variables. This method should not be used when building a
18170 /// normal expression which refers to a variable.
18171 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18172                                  bool MightBeOdrUse) {
18173   if (MightBeOdrUse) {
18174     if (auto *VD = dyn_cast<VarDecl>(D)) {
18175       MarkVariableReferenced(Loc, VD);
18176       return;
18177     }
18178   }
18179   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18180     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18181     return;
18182   }
18183   D->setReferenced();
18184 }
18185 
18186 namespace {
18187   // Mark all of the declarations used by a type as referenced.
18188   // FIXME: Not fully implemented yet! We need to have a better understanding
18189   // of when we're entering a context we should not recurse into.
18190   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18191   // TreeTransforms rebuilding the type in a new context. Rather than
18192   // duplicating the TreeTransform logic, we should consider reusing it here.
18193   // Currently that causes problems when rebuilding LambdaExprs.
18194   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18195     Sema &S;
18196     SourceLocation Loc;
18197 
18198   public:
18199     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18200 
18201     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18202 
18203     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18204   };
18205 }
18206 
18207 bool MarkReferencedDecls::TraverseTemplateArgument(
18208     const TemplateArgument &Arg) {
18209   {
18210     // A non-type template argument is a constant-evaluated context.
18211     EnterExpressionEvaluationContext Evaluated(
18212         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18213     if (Arg.getKind() == TemplateArgument::Declaration) {
18214       if (Decl *D = Arg.getAsDecl())
18215         S.MarkAnyDeclReferenced(Loc, D, true);
18216     } else if (Arg.getKind() == TemplateArgument::Expression) {
18217       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18218     }
18219   }
18220 
18221   return Inherited::TraverseTemplateArgument(Arg);
18222 }
18223 
18224 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18225   MarkReferencedDecls Marker(*this, Loc);
18226   Marker.TraverseType(T);
18227 }
18228 
18229 namespace {
18230 /// Helper class that marks all of the declarations referenced by
18231 /// potentially-evaluated subexpressions as "referenced".
18232 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18233 public:
18234   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18235   bool SkipLocalVariables;
18236 
18237   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18238       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18239 
18240   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18241     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18242   }
18243 
18244   void VisitDeclRefExpr(DeclRefExpr *E) {
18245     // If we were asked not to visit local variables, don't.
18246     if (SkipLocalVariables) {
18247       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18248         if (VD->hasLocalStorage())
18249           return;
18250     }
18251     S.MarkDeclRefReferenced(E);
18252   }
18253 
18254   void VisitMemberExpr(MemberExpr *E) {
18255     S.MarkMemberReferenced(E);
18256     Visit(E->getBase());
18257   }
18258 };
18259 } // namespace
18260 
18261 /// Mark any declarations that appear within this expression or any
18262 /// potentially-evaluated subexpressions as "referenced".
18263 ///
18264 /// \param SkipLocalVariables If true, don't mark local variables as
18265 /// 'referenced'.
18266 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18267                                             bool SkipLocalVariables) {
18268   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18269 }
18270 
18271 /// Emit a diagnostic that describes an effect on the run-time behavior
18272 /// of the program being compiled.
18273 ///
18274 /// This routine emits the given diagnostic when the code currently being
18275 /// type-checked is "potentially evaluated", meaning that there is a
18276 /// possibility that the code will actually be executable. Code in sizeof()
18277 /// expressions, code used only during overload resolution, etc., are not
18278 /// potentially evaluated. This routine will suppress such diagnostics or,
18279 /// in the absolutely nutty case of potentially potentially evaluated
18280 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18281 /// later.
18282 ///
18283 /// This routine should be used for all diagnostics that describe the run-time
18284 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18285 /// Failure to do so will likely result in spurious diagnostics or failures
18286 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18287 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18288                                const PartialDiagnostic &PD) {
18289   switch (ExprEvalContexts.back().Context) {
18290   case ExpressionEvaluationContext::Unevaluated:
18291   case ExpressionEvaluationContext::UnevaluatedList:
18292   case ExpressionEvaluationContext::UnevaluatedAbstract:
18293   case ExpressionEvaluationContext::DiscardedStatement:
18294     // The argument will never be evaluated, so don't complain.
18295     break;
18296 
18297   case ExpressionEvaluationContext::ConstantEvaluated:
18298     // Relevant diagnostics should be produced by constant evaluation.
18299     break;
18300 
18301   case ExpressionEvaluationContext::PotentiallyEvaluated:
18302   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18303     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18304       FunctionScopes.back()->PossiblyUnreachableDiags.
18305         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18306       return true;
18307     }
18308 
18309     // The initializer of a constexpr variable or of the first declaration of a
18310     // static data member is not syntactically a constant evaluated constant,
18311     // but nonetheless is always required to be a constant expression, so we
18312     // can skip diagnosing.
18313     // FIXME: Using the mangling context here is a hack.
18314     if (auto *VD = dyn_cast_or_null<VarDecl>(
18315             ExprEvalContexts.back().ManglingContextDecl)) {
18316       if (VD->isConstexpr() ||
18317           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18318         break;
18319       // FIXME: For any other kind of variable, we should build a CFG for its
18320       // initializer and check whether the context in question is reachable.
18321     }
18322 
18323     Diag(Loc, PD);
18324     return true;
18325   }
18326 
18327   return false;
18328 }
18329 
18330 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18331                                const PartialDiagnostic &PD) {
18332   return DiagRuntimeBehavior(
18333       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18334 }
18335 
18336 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18337                                CallExpr *CE, FunctionDecl *FD) {
18338   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18339     return false;
18340 
18341   // If we're inside a decltype's expression, don't check for a valid return
18342   // type or construct temporaries until we know whether this is the last call.
18343   if (ExprEvalContexts.back().ExprContext ==
18344       ExpressionEvaluationContextRecord::EK_Decltype) {
18345     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18346     return false;
18347   }
18348 
18349   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18350     FunctionDecl *FD;
18351     CallExpr *CE;
18352 
18353   public:
18354     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18355       : FD(FD), CE(CE) { }
18356 
18357     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18358       if (!FD) {
18359         S.Diag(Loc, diag::err_call_incomplete_return)
18360           << T << CE->getSourceRange();
18361         return;
18362       }
18363 
18364       S.Diag(Loc, diag::err_call_function_incomplete_return)
18365           << CE->getSourceRange() << FD << T;
18366       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18367           << FD->getDeclName();
18368     }
18369   } Diagnoser(FD, CE);
18370 
18371   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18372     return true;
18373 
18374   return false;
18375 }
18376 
18377 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18378 // will prevent this condition from triggering, which is what we want.
18379 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18380   SourceLocation Loc;
18381 
18382   unsigned diagnostic = diag::warn_condition_is_assignment;
18383   bool IsOrAssign = false;
18384 
18385   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18386     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18387       return;
18388 
18389     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18390 
18391     // Greylist some idioms by putting them into a warning subcategory.
18392     if (ObjCMessageExpr *ME
18393           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18394       Selector Sel = ME->getSelector();
18395 
18396       // self = [<foo> init...]
18397       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18398         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18399 
18400       // <foo> = [<bar> nextObject]
18401       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18402         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18403     }
18404 
18405     Loc = Op->getOperatorLoc();
18406   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18407     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18408       return;
18409 
18410     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18411     Loc = Op->getOperatorLoc();
18412   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18413     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18414   else {
18415     // Not an assignment.
18416     return;
18417   }
18418 
18419   Diag(Loc, diagnostic) << E->getSourceRange();
18420 
18421   SourceLocation Open = E->getBeginLoc();
18422   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18423   Diag(Loc, diag::note_condition_assign_silence)
18424         << FixItHint::CreateInsertion(Open, "(")
18425         << FixItHint::CreateInsertion(Close, ")");
18426 
18427   if (IsOrAssign)
18428     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18429       << FixItHint::CreateReplacement(Loc, "!=");
18430   else
18431     Diag(Loc, diag::note_condition_assign_to_comparison)
18432       << FixItHint::CreateReplacement(Loc, "==");
18433 }
18434 
18435 /// Redundant parentheses over an equality comparison can indicate
18436 /// that the user intended an assignment used as condition.
18437 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18438   // Don't warn if the parens came from a macro.
18439   SourceLocation parenLoc = ParenE->getBeginLoc();
18440   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18441     return;
18442   // Don't warn for dependent expressions.
18443   if (ParenE->isTypeDependent())
18444     return;
18445 
18446   Expr *E = ParenE->IgnoreParens();
18447 
18448   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18449     if (opE->getOpcode() == BO_EQ &&
18450         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18451                                                            == Expr::MLV_Valid) {
18452       SourceLocation Loc = opE->getOperatorLoc();
18453 
18454       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18455       SourceRange ParenERange = ParenE->getSourceRange();
18456       Diag(Loc, diag::note_equality_comparison_silence)
18457         << FixItHint::CreateRemoval(ParenERange.getBegin())
18458         << FixItHint::CreateRemoval(ParenERange.getEnd());
18459       Diag(Loc, diag::note_equality_comparison_to_assign)
18460         << FixItHint::CreateReplacement(Loc, "=");
18461     }
18462 }
18463 
18464 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18465                                        bool IsConstexpr) {
18466   DiagnoseAssignmentAsCondition(E);
18467   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18468     DiagnoseEqualityWithExtraParens(parenE);
18469 
18470   ExprResult result = CheckPlaceholderExpr(E);
18471   if (result.isInvalid()) return ExprError();
18472   E = result.get();
18473 
18474   if (!E->isTypeDependent()) {
18475     if (getLangOpts().CPlusPlus)
18476       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18477 
18478     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18479     if (ERes.isInvalid())
18480       return ExprError();
18481     E = ERes.get();
18482 
18483     QualType T = E->getType();
18484     if (!T->isScalarType()) { // C99 6.8.4.1p1
18485       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18486         << T << E->getSourceRange();
18487       return ExprError();
18488     }
18489     CheckBoolLikeConversion(E, Loc);
18490   }
18491 
18492   return E;
18493 }
18494 
18495 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18496                                            Expr *SubExpr, ConditionKind CK) {
18497   // Empty conditions are valid in for-statements.
18498   if (!SubExpr)
18499     return ConditionResult();
18500 
18501   ExprResult Cond;
18502   switch (CK) {
18503   case ConditionKind::Boolean:
18504     Cond = CheckBooleanCondition(Loc, SubExpr);
18505     break;
18506 
18507   case ConditionKind::ConstexprIf:
18508     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18509     break;
18510 
18511   case ConditionKind::Switch:
18512     Cond = CheckSwitchCondition(Loc, SubExpr);
18513     break;
18514   }
18515   if (Cond.isInvalid()) {
18516     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18517                               {SubExpr});
18518     if (!Cond.get())
18519       return ConditionError();
18520   }
18521   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18522   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18523   if (!FullExpr.get())
18524     return ConditionError();
18525 
18526   return ConditionResult(*this, nullptr, FullExpr,
18527                          CK == ConditionKind::ConstexprIf);
18528 }
18529 
18530 namespace {
18531   /// A visitor for rebuilding a call to an __unknown_any expression
18532   /// to have an appropriate type.
18533   struct RebuildUnknownAnyFunction
18534     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18535 
18536     Sema &S;
18537 
18538     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18539 
18540     ExprResult VisitStmt(Stmt *S) {
18541       llvm_unreachable("unexpected statement!");
18542     }
18543 
18544     ExprResult VisitExpr(Expr *E) {
18545       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18546         << E->getSourceRange();
18547       return ExprError();
18548     }
18549 
18550     /// Rebuild an expression which simply semantically wraps another
18551     /// expression which it shares the type and value kind of.
18552     template <class T> ExprResult rebuildSugarExpr(T *E) {
18553       ExprResult SubResult = Visit(E->getSubExpr());
18554       if (SubResult.isInvalid()) return ExprError();
18555 
18556       Expr *SubExpr = SubResult.get();
18557       E->setSubExpr(SubExpr);
18558       E->setType(SubExpr->getType());
18559       E->setValueKind(SubExpr->getValueKind());
18560       assert(E->getObjectKind() == OK_Ordinary);
18561       return E;
18562     }
18563 
18564     ExprResult VisitParenExpr(ParenExpr *E) {
18565       return rebuildSugarExpr(E);
18566     }
18567 
18568     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18569       return rebuildSugarExpr(E);
18570     }
18571 
18572     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18573       ExprResult SubResult = Visit(E->getSubExpr());
18574       if (SubResult.isInvalid()) return ExprError();
18575 
18576       Expr *SubExpr = SubResult.get();
18577       E->setSubExpr(SubExpr);
18578       E->setType(S.Context.getPointerType(SubExpr->getType()));
18579       assert(E->getValueKind() == VK_RValue);
18580       assert(E->getObjectKind() == OK_Ordinary);
18581       return E;
18582     }
18583 
18584     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18585       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18586 
18587       E->setType(VD->getType());
18588 
18589       assert(E->getValueKind() == VK_RValue);
18590       if (S.getLangOpts().CPlusPlus &&
18591           !(isa<CXXMethodDecl>(VD) &&
18592             cast<CXXMethodDecl>(VD)->isInstance()))
18593         E->setValueKind(VK_LValue);
18594 
18595       return E;
18596     }
18597 
18598     ExprResult VisitMemberExpr(MemberExpr *E) {
18599       return resolveDecl(E, E->getMemberDecl());
18600     }
18601 
18602     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18603       return resolveDecl(E, E->getDecl());
18604     }
18605   };
18606 }
18607 
18608 /// Given a function expression of unknown-any type, try to rebuild it
18609 /// to have a function type.
18610 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18611   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18612   if (Result.isInvalid()) return ExprError();
18613   return S.DefaultFunctionArrayConversion(Result.get());
18614 }
18615 
18616 namespace {
18617   /// A visitor for rebuilding an expression of type __unknown_anytype
18618   /// into one which resolves the type directly on the referring
18619   /// expression.  Strict preservation of the original source
18620   /// structure is not a goal.
18621   struct RebuildUnknownAnyExpr
18622     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18623 
18624     Sema &S;
18625 
18626     /// The current destination type.
18627     QualType DestType;
18628 
18629     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18630       : S(S), DestType(CastType) {}
18631 
18632     ExprResult VisitStmt(Stmt *S) {
18633       llvm_unreachable("unexpected statement!");
18634     }
18635 
18636     ExprResult VisitExpr(Expr *E) {
18637       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18638         << E->getSourceRange();
18639       return ExprError();
18640     }
18641 
18642     ExprResult VisitCallExpr(CallExpr *E);
18643     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18644 
18645     /// Rebuild an expression which simply semantically wraps another
18646     /// expression which it shares the type and value kind of.
18647     template <class T> ExprResult rebuildSugarExpr(T *E) {
18648       ExprResult SubResult = Visit(E->getSubExpr());
18649       if (SubResult.isInvalid()) return ExprError();
18650       Expr *SubExpr = SubResult.get();
18651       E->setSubExpr(SubExpr);
18652       E->setType(SubExpr->getType());
18653       E->setValueKind(SubExpr->getValueKind());
18654       assert(E->getObjectKind() == OK_Ordinary);
18655       return E;
18656     }
18657 
18658     ExprResult VisitParenExpr(ParenExpr *E) {
18659       return rebuildSugarExpr(E);
18660     }
18661 
18662     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18663       return rebuildSugarExpr(E);
18664     }
18665 
18666     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18667       const PointerType *Ptr = DestType->getAs<PointerType>();
18668       if (!Ptr) {
18669         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18670           << E->getSourceRange();
18671         return ExprError();
18672       }
18673 
18674       if (isa<CallExpr>(E->getSubExpr())) {
18675         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18676           << E->getSourceRange();
18677         return ExprError();
18678       }
18679 
18680       assert(E->getValueKind() == VK_RValue);
18681       assert(E->getObjectKind() == OK_Ordinary);
18682       E->setType(DestType);
18683 
18684       // Build the sub-expression as if it were an object of the pointee type.
18685       DestType = Ptr->getPointeeType();
18686       ExprResult SubResult = Visit(E->getSubExpr());
18687       if (SubResult.isInvalid()) return ExprError();
18688       E->setSubExpr(SubResult.get());
18689       return E;
18690     }
18691 
18692     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18693 
18694     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18695 
18696     ExprResult VisitMemberExpr(MemberExpr *E) {
18697       return resolveDecl(E, E->getMemberDecl());
18698     }
18699 
18700     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18701       return resolveDecl(E, E->getDecl());
18702     }
18703   };
18704 }
18705 
18706 /// Rebuilds a call expression which yielded __unknown_anytype.
18707 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18708   Expr *CalleeExpr = E->getCallee();
18709 
18710   enum FnKind {
18711     FK_MemberFunction,
18712     FK_FunctionPointer,
18713     FK_BlockPointer
18714   };
18715 
18716   FnKind Kind;
18717   QualType CalleeType = CalleeExpr->getType();
18718   if (CalleeType == S.Context.BoundMemberTy) {
18719     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18720     Kind = FK_MemberFunction;
18721     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18722   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18723     CalleeType = Ptr->getPointeeType();
18724     Kind = FK_FunctionPointer;
18725   } else {
18726     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18727     Kind = FK_BlockPointer;
18728   }
18729   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18730 
18731   // Verify that this is a legal result type of a function.
18732   if (DestType->isArrayType() || DestType->isFunctionType()) {
18733     unsigned diagID = diag::err_func_returning_array_function;
18734     if (Kind == FK_BlockPointer)
18735       diagID = diag::err_block_returning_array_function;
18736 
18737     S.Diag(E->getExprLoc(), diagID)
18738       << DestType->isFunctionType() << DestType;
18739     return ExprError();
18740   }
18741 
18742   // Otherwise, go ahead and set DestType as the call's result.
18743   E->setType(DestType.getNonLValueExprType(S.Context));
18744   E->setValueKind(Expr::getValueKindForType(DestType));
18745   assert(E->getObjectKind() == OK_Ordinary);
18746 
18747   // Rebuild the function type, replacing the result type with DestType.
18748   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18749   if (Proto) {
18750     // __unknown_anytype(...) is a special case used by the debugger when
18751     // it has no idea what a function's signature is.
18752     //
18753     // We want to build this call essentially under the K&R
18754     // unprototyped rules, but making a FunctionNoProtoType in C++
18755     // would foul up all sorts of assumptions.  However, we cannot
18756     // simply pass all arguments as variadic arguments, nor can we
18757     // portably just call the function under a non-variadic type; see
18758     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18759     // However, it turns out that in practice it is generally safe to
18760     // call a function declared as "A foo(B,C,D);" under the prototype
18761     // "A foo(B,C,D,...);".  The only known exception is with the
18762     // Windows ABI, where any variadic function is implicitly cdecl
18763     // regardless of its normal CC.  Therefore we change the parameter
18764     // types to match the types of the arguments.
18765     //
18766     // This is a hack, but it is far superior to moving the
18767     // corresponding target-specific code from IR-gen to Sema/AST.
18768 
18769     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18770     SmallVector<QualType, 8> ArgTypes;
18771     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18772       ArgTypes.reserve(E->getNumArgs());
18773       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18774         Expr *Arg = E->getArg(i);
18775         QualType ArgType = Arg->getType();
18776         if (E->isLValue()) {
18777           ArgType = S.Context.getLValueReferenceType(ArgType);
18778         } else if (E->isXValue()) {
18779           ArgType = S.Context.getRValueReferenceType(ArgType);
18780         }
18781         ArgTypes.push_back(ArgType);
18782       }
18783       ParamTypes = ArgTypes;
18784     }
18785     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18786                                          Proto->getExtProtoInfo());
18787   } else {
18788     DestType = S.Context.getFunctionNoProtoType(DestType,
18789                                                 FnType->getExtInfo());
18790   }
18791 
18792   // Rebuild the appropriate pointer-to-function type.
18793   switch (Kind) {
18794   case FK_MemberFunction:
18795     // Nothing to do.
18796     break;
18797 
18798   case FK_FunctionPointer:
18799     DestType = S.Context.getPointerType(DestType);
18800     break;
18801 
18802   case FK_BlockPointer:
18803     DestType = S.Context.getBlockPointerType(DestType);
18804     break;
18805   }
18806 
18807   // Finally, we can recurse.
18808   ExprResult CalleeResult = Visit(CalleeExpr);
18809   if (!CalleeResult.isUsable()) return ExprError();
18810   E->setCallee(CalleeResult.get());
18811 
18812   // Bind a temporary if necessary.
18813   return S.MaybeBindToTemporary(E);
18814 }
18815 
18816 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18817   // Verify that this is a legal result type of a call.
18818   if (DestType->isArrayType() || DestType->isFunctionType()) {
18819     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18820       << DestType->isFunctionType() << DestType;
18821     return ExprError();
18822   }
18823 
18824   // Rewrite the method result type if available.
18825   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18826     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18827     Method->setReturnType(DestType);
18828   }
18829 
18830   // Change the type of the message.
18831   E->setType(DestType.getNonReferenceType());
18832   E->setValueKind(Expr::getValueKindForType(DestType));
18833 
18834   return S.MaybeBindToTemporary(E);
18835 }
18836 
18837 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18838   // The only case we should ever see here is a function-to-pointer decay.
18839   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18840     assert(E->getValueKind() == VK_RValue);
18841     assert(E->getObjectKind() == OK_Ordinary);
18842 
18843     E->setType(DestType);
18844 
18845     // Rebuild the sub-expression as the pointee (function) type.
18846     DestType = DestType->castAs<PointerType>()->getPointeeType();
18847 
18848     ExprResult Result = Visit(E->getSubExpr());
18849     if (!Result.isUsable()) return ExprError();
18850 
18851     E->setSubExpr(Result.get());
18852     return E;
18853   } else if (E->getCastKind() == CK_LValueToRValue) {
18854     assert(E->getValueKind() == VK_RValue);
18855     assert(E->getObjectKind() == OK_Ordinary);
18856 
18857     assert(isa<BlockPointerType>(E->getType()));
18858 
18859     E->setType(DestType);
18860 
18861     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18862     DestType = S.Context.getLValueReferenceType(DestType);
18863 
18864     ExprResult Result = Visit(E->getSubExpr());
18865     if (!Result.isUsable()) return ExprError();
18866 
18867     E->setSubExpr(Result.get());
18868     return E;
18869   } else {
18870     llvm_unreachable("Unhandled cast type!");
18871   }
18872 }
18873 
18874 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18875   ExprValueKind ValueKind = VK_LValue;
18876   QualType Type = DestType;
18877 
18878   // We know how to make this work for certain kinds of decls:
18879 
18880   //  - functions
18881   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18882     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18883       DestType = Ptr->getPointeeType();
18884       ExprResult Result = resolveDecl(E, VD);
18885       if (Result.isInvalid()) return ExprError();
18886       return S.ImpCastExprToType(Result.get(), Type,
18887                                  CK_FunctionToPointerDecay, VK_RValue);
18888     }
18889 
18890     if (!Type->isFunctionType()) {
18891       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18892         << VD << E->getSourceRange();
18893       return ExprError();
18894     }
18895     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18896       // We must match the FunctionDecl's type to the hack introduced in
18897       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18898       // type. See the lengthy commentary in that routine.
18899       QualType FDT = FD->getType();
18900       const FunctionType *FnType = FDT->castAs<FunctionType>();
18901       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18902       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18903       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18904         SourceLocation Loc = FD->getLocation();
18905         FunctionDecl *NewFD = FunctionDecl::Create(
18906             S.Context, FD->getDeclContext(), Loc, Loc,
18907             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18908             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18909             /*ConstexprKind*/ CSK_unspecified);
18910 
18911         if (FD->getQualifier())
18912           NewFD->setQualifierInfo(FD->getQualifierLoc());
18913 
18914         SmallVector<ParmVarDecl*, 16> Params;
18915         for (const auto &AI : FT->param_types()) {
18916           ParmVarDecl *Param =
18917             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18918           Param->setScopeInfo(0, Params.size());
18919           Params.push_back(Param);
18920         }
18921         NewFD->setParams(Params);
18922         DRE->setDecl(NewFD);
18923         VD = DRE->getDecl();
18924       }
18925     }
18926 
18927     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18928       if (MD->isInstance()) {
18929         ValueKind = VK_RValue;
18930         Type = S.Context.BoundMemberTy;
18931       }
18932 
18933     // Function references aren't l-values in C.
18934     if (!S.getLangOpts().CPlusPlus)
18935       ValueKind = VK_RValue;
18936 
18937   //  - variables
18938   } else if (isa<VarDecl>(VD)) {
18939     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18940       Type = RefTy->getPointeeType();
18941     } else if (Type->isFunctionType()) {
18942       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18943         << VD << E->getSourceRange();
18944       return ExprError();
18945     }
18946 
18947   //  - nothing else
18948   } else {
18949     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18950       << VD << E->getSourceRange();
18951     return ExprError();
18952   }
18953 
18954   // Modifying the declaration like this is friendly to IR-gen but
18955   // also really dangerous.
18956   VD->setType(DestType);
18957   E->setType(Type);
18958   E->setValueKind(ValueKind);
18959   return E;
18960 }
18961 
18962 /// Check a cast of an unknown-any type.  We intentionally only
18963 /// trigger this for C-style casts.
18964 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18965                                      Expr *CastExpr, CastKind &CastKind,
18966                                      ExprValueKind &VK, CXXCastPath &Path) {
18967   // The type we're casting to must be either void or complete.
18968   if (!CastType->isVoidType() &&
18969       RequireCompleteType(TypeRange.getBegin(), CastType,
18970                           diag::err_typecheck_cast_to_incomplete))
18971     return ExprError();
18972 
18973   // Rewrite the casted expression from scratch.
18974   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18975   if (!result.isUsable()) return ExprError();
18976 
18977   CastExpr = result.get();
18978   VK = CastExpr->getValueKind();
18979   CastKind = CK_NoOp;
18980 
18981   return CastExpr;
18982 }
18983 
18984 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18985   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18986 }
18987 
18988 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18989                                     Expr *arg, QualType &paramType) {
18990   // If the syntactic form of the argument is not an explicit cast of
18991   // any sort, just do default argument promotion.
18992   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18993   if (!castArg) {
18994     ExprResult result = DefaultArgumentPromotion(arg);
18995     if (result.isInvalid()) return ExprError();
18996     paramType = result.get()->getType();
18997     return result;
18998   }
18999 
19000   // Otherwise, use the type that was written in the explicit cast.
19001   assert(!arg->hasPlaceholderType());
19002   paramType = castArg->getTypeAsWritten();
19003 
19004   // Copy-initialize a parameter of that type.
19005   InitializedEntity entity =
19006     InitializedEntity::InitializeParameter(Context, paramType,
19007                                            /*consumed*/ false);
19008   return PerformCopyInitialization(entity, callLoc, arg);
19009 }
19010 
19011 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19012   Expr *orig = E;
19013   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19014   while (true) {
19015     E = E->IgnoreParenImpCasts();
19016     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19017       E = call->getCallee();
19018       diagID = diag::err_uncasted_call_of_unknown_any;
19019     } else {
19020       break;
19021     }
19022   }
19023 
19024   SourceLocation loc;
19025   NamedDecl *d;
19026   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19027     loc = ref->getLocation();
19028     d = ref->getDecl();
19029   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19030     loc = mem->getMemberLoc();
19031     d = mem->getMemberDecl();
19032   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19033     diagID = diag::err_uncasted_call_of_unknown_any;
19034     loc = msg->getSelectorStartLoc();
19035     d = msg->getMethodDecl();
19036     if (!d) {
19037       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19038         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19039         << orig->getSourceRange();
19040       return ExprError();
19041     }
19042   } else {
19043     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19044       << E->getSourceRange();
19045     return ExprError();
19046   }
19047 
19048   S.Diag(loc, diagID) << d << orig->getSourceRange();
19049 
19050   // Never recoverable.
19051   return ExprError();
19052 }
19053 
19054 /// Check for operands with placeholder types and complain if found.
19055 /// Returns ExprError() if there was an error and no recovery was possible.
19056 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19057   if (!getLangOpts().CPlusPlus) {
19058     // C cannot handle TypoExpr nodes on either side of a binop because it
19059     // doesn't handle dependent types properly, so make sure any TypoExprs have
19060     // been dealt with before checking the operands.
19061     ExprResult Result = CorrectDelayedTyposInExpr(E);
19062     if (!Result.isUsable()) return ExprError();
19063     E = Result.get();
19064   }
19065 
19066   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19067   if (!placeholderType) return E;
19068 
19069   switch (placeholderType->getKind()) {
19070 
19071   // Overloaded expressions.
19072   case BuiltinType::Overload: {
19073     // Try to resolve a single function template specialization.
19074     // This is obligatory.
19075     ExprResult Result = E;
19076     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19077       return Result;
19078 
19079     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19080     // leaves Result unchanged on failure.
19081     Result = E;
19082     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19083       return Result;
19084 
19085     // If that failed, try to recover with a call.
19086     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19087                          /*complain*/ true);
19088     return Result;
19089   }
19090 
19091   // Bound member functions.
19092   case BuiltinType::BoundMember: {
19093     ExprResult result = E;
19094     const Expr *BME = E->IgnoreParens();
19095     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19096     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19097     if (isa<CXXPseudoDestructorExpr>(BME)) {
19098       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19099     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19100       if (ME->getMemberNameInfo().getName().getNameKind() ==
19101           DeclarationName::CXXDestructorName)
19102         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19103     }
19104     tryToRecoverWithCall(result, PD,
19105                          /*complain*/ true);
19106     return result;
19107   }
19108 
19109   // ARC unbridged casts.
19110   case BuiltinType::ARCUnbridgedCast: {
19111     Expr *realCast = stripARCUnbridgedCast(E);
19112     diagnoseARCUnbridgedCast(realCast);
19113     return realCast;
19114   }
19115 
19116   // Expressions of unknown type.
19117   case BuiltinType::UnknownAny:
19118     return diagnoseUnknownAnyExpr(*this, E);
19119 
19120   // Pseudo-objects.
19121   case BuiltinType::PseudoObject:
19122     return checkPseudoObjectRValue(E);
19123 
19124   case BuiltinType::BuiltinFn: {
19125     // Accept __noop without parens by implicitly converting it to a call expr.
19126     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19127     if (DRE) {
19128       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19129       if (FD->getBuiltinID() == Builtin::BI__noop) {
19130         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19131                               CK_BuiltinFnToFnPtr)
19132                 .get();
19133         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19134                                 VK_RValue, SourceLocation(),
19135                                 FPOptionsOverride());
19136       }
19137     }
19138 
19139     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19140     return ExprError();
19141   }
19142 
19143   case BuiltinType::IncompleteMatrixIdx:
19144     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19145              ->getRowIdx()
19146              ->getBeginLoc(),
19147          diag::err_matrix_incomplete_index);
19148     return ExprError();
19149 
19150   // Expressions of unknown type.
19151   case BuiltinType::OMPArraySection:
19152     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19153     return ExprError();
19154 
19155   // Expressions of unknown type.
19156   case BuiltinType::OMPArrayShaping:
19157     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19158 
19159   case BuiltinType::OMPIterator:
19160     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19161 
19162   // Everything else should be impossible.
19163 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19164   case BuiltinType::Id:
19165 #include "clang/Basic/OpenCLImageTypes.def"
19166 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19167   case BuiltinType::Id:
19168 #include "clang/Basic/OpenCLExtensionTypes.def"
19169 #define SVE_TYPE(Name, Id, SingletonId) \
19170   case BuiltinType::Id:
19171 #include "clang/Basic/AArch64SVEACLETypes.def"
19172 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19173 #define PLACEHOLDER_TYPE(Id, SingletonId)
19174 #include "clang/AST/BuiltinTypes.def"
19175     break;
19176   }
19177 
19178   llvm_unreachable("invalid placeholder type!");
19179 }
19180 
19181 bool Sema::CheckCaseExpression(Expr *E) {
19182   if (E->isTypeDependent())
19183     return true;
19184   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19185     return E->getType()->isIntegralOrEnumerationType();
19186   return false;
19187 }
19188 
19189 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19190 ExprResult
19191 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19192   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19193          "Unknown Objective-C Boolean value!");
19194   QualType BoolT = Context.ObjCBuiltinBoolTy;
19195   if (!Context.getBOOLDecl()) {
19196     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19197                         Sema::LookupOrdinaryName);
19198     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19199       NamedDecl *ND = Result.getFoundDecl();
19200       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19201         Context.setBOOLDecl(TD);
19202     }
19203   }
19204   if (Context.getBOOLDecl())
19205     BoolT = Context.getBOOLType();
19206   return new (Context)
19207       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19208 }
19209 
19210 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19211     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19212     SourceLocation RParen) {
19213 
19214   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19215 
19216   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19217     return Spec.getPlatform() == Platform;
19218   });
19219 
19220   VersionTuple Version;
19221   if (Spec != AvailSpecs.end())
19222     Version = Spec->getVersion();
19223 
19224   // The use of `@available` in the enclosing function should be analyzed to
19225   // warn when it's used inappropriately (i.e. not if(@available)).
19226   if (getCurFunctionOrMethodDecl())
19227     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19228   else if (getCurBlock() || getCurLambda())
19229     getCurFunction()->HasPotentialAvailabilityViolations = true;
19230 
19231   return new (Context)
19232       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19233 }
19234 
19235 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19236                                     ArrayRef<Expr *> SubExprs, QualType T) {
19237   if (!Context.getLangOpts().RecoveryAST)
19238     return ExprError();
19239 
19240   if (isSFINAEContext())
19241     return ExprError();
19242 
19243   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19244     // We don't know the concrete type, fallback to dependent type.
19245     T = Context.DependentTy;
19246   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19247 }
19248