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     return Incompatible;
9013   }
9014 
9015   // Diagnose attempts to convert between __float128 and long double where
9016   // such conversions currently can't be handled.
9017   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9018     return Incompatible;
9019 
9020   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9021   // discards the imaginary part.
9022   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9023       !LHSType->getAs<ComplexType>())
9024     return Incompatible;
9025 
9026   // Arithmetic conversions.
9027   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9028       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9029     if (ConvertRHS)
9030       Kind = PrepareScalarCast(RHS, LHSType);
9031     return Compatible;
9032   }
9033 
9034   // Conversions to normal pointers.
9035   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9036     // U* -> T*
9037     if (isa<PointerType>(RHSType)) {
9038       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9039       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9040       if (AddrSpaceL != AddrSpaceR)
9041         Kind = CK_AddressSpaceConversion;
9042       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9043         Kind = CK_NoOp;
9044       else
9045         Kind = CK_BitCast;
9046       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9047     }
9048 
9049     // int -> T*
9050     if (RHSType->isIntegerType()) {
9051       Kind = CK_IntegralToPointer; // FIXME: null?
9052       return IntToPointer;
9053     }
9054 
9055     // C pointers are not compatible with ObjC object pointers,
9056     // with two exceptions:
9057     if (isa<ObjCObjectPointerType>(RHSType)) {
9058       //  - conversions to void*
9059       if (LHSPointer->getPointeeType()->isVoidType()) {
9060         Kind = CK_BitCast;
9061         return Compatible;
9062       }
9063 
9064       //  - conversions from 'Class' to the redefinition type
9065       if (RHSType->isObjCClassType() &&
9066           Context.hasSameType(LHSType,
9067                               Context.getObjCClassRedefinitionType())) {
9068         Kind = CK_BitCast;
9069         return Compatible;
9070       }
9071 
9072       Kind = CK_BitCast;
9073       return IncompatiblePointer;
9074     }
9075 
9076     // U^ -> void*
9077     if (RHSType->getAs<BlockPointerType>()) {
9078       if (LHSPointer->getPointeeType()->isVoidType()) {
9079         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9080         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9081                                 ->getPointeeType()
9082                                 .getAddressSpace();
9083         Kind =
9084             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9085         return Compatible;
9086       }
9087     }
9088 
9089     return Incompatible;
9090   }
9091 
9092   // Conversions to block pointers.
9093   if (isa<BlockPointerType>(LHSType)) {
9094     // U^ -> T^
9095     if (RHSType->isBlockPointerType()) {
9096       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9097                               ->getPointeeType()
9098                               .getAddressSpace();
9099       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9100                               ->getPointeeType()
9101                               .getAddressSpace();
9102       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9103       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9104     }
9105 
9106     // int or null -> T^
9107     if (RHSType->isIntegerType()) {
9108       Kind = CK_IntegralToPointer; // FIXME: null
9109       return IntToBlockPointer;
9110     }
9111 
9112     // id -> T^
9113     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9114       Kind = CK_AnyPointerToBlockPointerCast;
9115       return Compatible;
9116     }
9117 
9118     // void* -> T^
9119     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9120       if (RHSPT->getPointeeType()->isVoidType()) {
9121         Kind = CK_AnyPointerToBlockPointerCast;
9122         return Compatible;
9123       }
9124 
9125     return Incompatible;
9126   }
9127 
9128   // Conversions to Objective-C pointers.
9129   if (isa<ObjCObjectPointerType>(LHSType)) {
9130     // A* -> B*
9131     if (RHSType->isObjCObjectPointerType()) {
9132       Kind = CK_BitCast;
9133       Sema::AssignConvertType result =
9134         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9135       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9136           result == Compatible &&
9137           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9138         result = IncompatibleObjCWeakRef;
9139       return result;
9140     }
9141 
9142     // int or null -> A*
9143     if (RHSType->isIntegerType()) {
9144       Kind = CK_IntegralToPointer; // FIXME: null
9145       return IntToPointer;
9146     }
9147 
9148     // In general, C pointers are not compatible with ObjC object pointers,
9149     // with two exceptions:
9150     if (isa<PointerType>(RHSType)) {
9151       Kind = CK_CPointerToObjCPointerCast;
9152 
9153       //  - conversions from 'void*'
9154       if (RHSType->isVoidPointerType()) {
9155         return Compatible;
9156       }
9157 
9158       //  - conversions to 'Class' from its redefinition type
9159       if (LHSType->isObjCClassType() &&
9160           Context.hasSameType(RHSType,
9161                               Context.getObjCClassRedefinitionType())) {
9162         return Compatible;
9163       }
9164 
9165       return IncompatiblePointer;
9166     }
9167 
9168     // Only under strict condition T^ is compatible with an Objective-C pointer.
9169     if (RHSType->isBlockPointerType() &&
9170         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9171       if (ConvertRHS)
9172         maybeExtendBlockObject(RHS);
9173       Kind = CK_BlockPointerToObjCPointerCast;
9174       return Compatible;
9175     }
9176 
9177     return Incompatible;
9178   }
9179 
9180   // Conversions from pointers that are not covered by the above.
9181   if (isa<PointerType>(RHSType)) {
9182     // T* -> _Bool
9183     if (LHSType == Context.BoolTy) {
9184       Kind = CK_PointerToBoolean;
9185       return Compatible;
9186     }
9187 
9188     // T* -> int
9189     if (LHSType->isIntegerType()) {
9190       Kind = CK_PointerToIntegral;
9191       return PointerToInt;
9192     }
9193 
9194     return Incompatible;
9195   }
9196 
9197   // Conversions from Objective-C pointers that are not covered by the above.
9198   if (isa<ObjCObjectPointerType>(RHSType)) {
9199     // T* -> _Bool
9200     if (LHSType == Context.BoolTy) {
9201       Kind = CK_PointerToBoolean;
9202       return Compatible;
9203     }
9204 
9205     // T* -> int
9206     if (LHSType->isIntegerType()) {
9207       Kind = CK_PointerToIntegral;
9208       return PointerToInt;
9209     }
9210 
9211     return Incompatible;
9212   }
9213 
9214   // struct A -> struct B
9215   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9216     if (Context.typesAreCompatible(LHSType, RHSType)) {
9217       Kind = CK_NoOp;
9218       return Compatible;
9219     }
9220   }
9221 
9222   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9223     Kind = CK_IntToOCLSampler;
9224     return Compatible;
9225   }
9226 
9227   return Incompatible;
9228 }
9229 
9230 /// Constructs a transparent union from an expression that is
9231 /// used to initialize the transparent union.
9232 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9233                                       ExprResult &EResult, QualType UnionType,
9234                                       FieldDecl *Field) {
9235   // Build an initializer list that designates the appropriate member
9236   // of the transparent union.
9237   Expr *E = EResult.get();
9238   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9239                                                    E, SourceLocation());
9240   Initializer->setType(UnionType);
9241   Initializer->setInitializedFieldInUnion(Field);
9242 
9243   // Build a compound literal constructing a value of the transparent
9244   // union type from this initializer list.
9245   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9246   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9247                                         VK_RValue, Initializer, false);
9248 }
9249 
9250 Sema::AssignConvertType
9251 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9252                                                ExprResult &RHS) {
9253   QualType RHSType = RHS.get()->getType();
9254 
9255   // If the ArgType is a Union type, we want to handle a potential
9256   // transparent_union GCC extension.
9257   const RecordType *UT = ArgType->getAsUnionType();
9258   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9259     return Incompatible;
9260 
9261   // The field to initialize within the transparent union.
9262   RecordDecl *UD = UT->getDecl();
9263   FieldDecl *InitField = nullptr;
9264   // It's compatible if the expression matches any of the fields.
9265   for (auto *it : UD->fields()) {
9266     if (it->getType()->isPointerType()) {
9267       // If the transparent union contains a pointer type, we allow:
9268       // 1) void pointer
9269       // 2) null pointer constant
9270       if (RHSType->isPointerType())
9271         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9272           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9273           InitField = it;
9274           break;
9275         }
9276 
9277       if (RHS.get()->isNullPointerConstant(Context,
9278                                            Expr::NPC_ValueDependentIsNull)) {
9279         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9280                                 CK_NullToPointer);
9281         InitField = it;
9282         break;
9283       }
9284     }
9285 
9286     CastKind Kind;
9287     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9288           == Compatible) {
9289       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9290       InitField = it;
9291       break;
9292     }
9293   }
9294 
9295   if (!InitField)
9296     return Incompatible;
9297 
9298   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9299   return Compatible;
9300 }
9301 
9302 Sema::AssignConvertType
9303 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9304                                        bool Diagnose,
9305                                        bool DiagnoseCFAudited,
9306                                        bool ConvertRHS) {
9307   // We need to be able to tell the caller whether we diagnosed a problem, if
9308   // they ask us to issue diagnostics.
9309   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9310 
9311   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9312   // we can't avoid *all* modifications at the moment, so we need some somewhere
9313   // to put the updated value.
9314   ExprResult LocalRHS = CallerRHS;
9315   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9316 
9317   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9318     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9319       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9320           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9321         Diag(RHS.get()->getExprLoc(),
9322              diag::warn_noderef_to_dereferenceable_pointer)
9323             << RHS.get()->getSourceRange();
9324       }
9325     }
9326   }
9327 
9328   if (getLangOpts().CPlusPlus) {
9329     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9330       // C++ 5.17p3: If the left operand is not of class type, the
9331       // expression is implicitly converted (C++ 4) to the
9332       // cv-unqualified type of the left operand.
9333       QualType RHSType = RHS.get()->getType();
9334       if (Diagnose) {
9335         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9336                                         AA_Assigning);
9337       } else {
9338         ImplicitConversionSequence ICS =
9339             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9340                                   /*SuppressUserConversions=*/false,
9341                                   AllowedExplicit::None,
9342                                   /*InOverloadResolution=*/false,
9343                                   /*CStyle=*/false,
9344                                   /*AllowObjCWritebackConversion=*/false);
9345         if (ICS.isFailure())
9346           return Incompatible;
9347         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9348                                         ICS, AA_Assigning);
9349       }
9350       if (RHS.isInvalid())
9351         return Incompatible;
9352       Sema::AssignConvertType result = Compatible;
9353       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9354           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9355         result = IncompatibleObjCWeakRef;
9356       return result;
9357     }
9358 
9359     // FIXME: Currently, we fall through and treat C++ classes like C
9360     // structures.
9361     // FIXME: We also fall through for atomics; not sure what should
9362     // happen there, though.
9363   } else if (RHS.get()->getType() == Context.OverloadTy) {
9364     // As a set of extensions to C, we support overloading on functions. These
9365     // functions need to be resolved here.
9366     DeclAccessPair DAP;
9367     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9368             RHS.get(), LHSType, /*Complain=*/false, DAP))
9369       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9370     else
9371       return Incompatible;
9372   }
9373 
9374   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9375   // a null pointer constant.
9376   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9377        LHSType->isBlockPointerType()) &&
9378       RHS.get()->isNullPointerConstant(Context,
9379                                        Expr::NPC_ValueDependentIsNull)) {
9380     if (Diagnose || ConvertRHS) {
9381       CastKind Kind;
9382       CXXCastPath Path;
9383       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9384                              /*IgnoreBaseAccess=*/false, Diagnose);
9385       if (ConvertRHS)
9386         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9387     }
9388     return Compatible;
9389   }
9390 
9391   // OpenCL queue_t type assignment.
9392   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9393                                  Context, Expr::NPC_ValueDependentIsNull)) {
9394     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9395     return Compatible;
9396   }
9397 
9398   // This check seems unnatural, however it is necessary to ensure the proper
9399   // conversion of functions/arrays. If the conversion were done for all
9400   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9401   // expressions that suppress this implicit conversion (&, sizeof).
9402   //
9403   // Suppress this for references: C++ 8.5.3p5.
9404   if (!LHSType->isReferenceType()) {
9405     // FIXME: We potentially allocate here even if ConvertRHS is false.
9406     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9407     if (RHS.isInvalid())
9408       return Incompatible;
9409   }
9410   CastKind Kind;
9411   Sema::AssignConvertType result =
9412     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9413 
9414   // C99 6.5.16.1p2: The value of the right operand is converted to the
9415   // type of the assignment expression.
9416   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9417   // so that we can use references in built-in functions even in C.
9418   // The getNonReferenceType() call makes sure that the resulting expression
9419   // does not have reference type.
9420   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9421     QualType Ty = LHSType.getNonLValueExprType(Context);
9422     Expr *E = RHS.get();
9423 
9424     // Check for various Objective-C errors. If we are not reporting
9425     // diagnostics and just checking for errors, e.g., during overload
9426     // resolution, return Incompatible to indicate the failure.
9427     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9428         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9429                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9430       if (!Diagnose)
9431         return Incompatible;
9432     }
9433     if (getLangOpts().ObjC &&
9434         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9435                                            E->getType(), E, Diagnose) ||
9436          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9437       if (!Diagnose)
9438         return Incompatible;
9439       // Replace the expression with a corrected version and continue so we
9440       // can find further errors.
9441       RHS = E;
9442       return Compatible;
9443     }
9444 
9445     if (ConvertRHS)
9446       RHS = ImpCastExprToType(E, Ty, Kind);
9447   }
9448 
9449   return result;
9450 }
9451 
9452 namespace {
9453 /// The original operand to an operator, prior to the application of the usual
9454 /// arithmetic conversions and converting the arguments of a builtin operator
9455 /// candidate.
9456 struct OriginalOperand {
9457   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9458     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9459       Op = MTE->getSubExpr();
9460     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9461       Op = BTE->getSubExpr();
9462     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9463       Orig = ICE->getSubExprAsWritten();
9464       Conversion = ICE->getConversionFunction();
9465     }
9466   }
9467 
9468   QualType getType() const { return Orig->getType(); }
9469 
9470   Expr *Orig;
9471   NamedDecl *Conversion;
9472 };
9473 }
9474 
9475 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9476                                ExprResult &RHS) {
9477   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9478 
9479   Diag(Loc, diag::err_typecheck_invalid_operands)
9480     << OrigLHS.getType() << OrigRHS.getType()
9481     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9482 
9483   // If a user-defined conversion was applied to either of the operands prior
9484   // to applying the built-in operator rules, tell the user about it.
9485   if (OrigLHS.Conversion) {
9486     Diag(OrigLHS.Conversion->getLocation(),
9487          diag::note_typecheck_invalid_operands_converted)
9488       << 0 << LHS.get()->getType();
9489   }
9490   if (OrigRHS.Conversion) {
9491     Diag(OrigRHS.Conversion->getLocation(),
9492          diag::note_typecheck_invalid_operands_converted)
9493       << 1 << RHS.get()->getType();
9494   }
9495 
9496   return QualType();
9497 }
9498 
9499 // Diagnose cases where a scalar was implicitly converted to a vector and
9500 // diagnose the underlying types. Otherwise, diagnose the error
9501 // as invalid vector logical operands for non-C++ cases.
9502 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9503                                             ExprResult &RHS) {
9504   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9505   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9506 
9507   bool LHSNatVec = LHSType->isVectorType();
9508   bool RHSNatVec = RHSType->isVectorType();
9509 
9510   if (!(LHSNatVec && RHSNatVec)) {
9511     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9512     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9513     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9514         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9515         << Vector->getSourceRange();
9516     return QualType();
9517   }
9518 
9519   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9520       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9521       << RHS.get()->getSourceRange();
9522 
9523   return QualType();
9524 }
9525 
9526 /// Try to convert a value of non-vector type to a vector type by converting
9527 /// the type to the element type of the vector and then performing a splat.
9528 /// If the language is OpenCL, we only use conversions that promote scalar
9529 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9530 /// for float->int.
9531 ///
9532 /// OpenCL V2.0 6.2.6.p2:
9533 /// An error shall occur if any scalar operand type has greater rank
9534 /// than the type of the vector element.
9535 ///
9536 /// \param scalar - if non-null, actually perform the conversions
9537 /// \return true if the operation fails (but without diagnosing the failure)
9538 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9539                                      QualType scalarTy,
9540                                      QualType vectorEltTy,
9541                                      QualType vectorTy,
9542                                      unsigned &DiagID) {
9543   // The conversion to apply to the scalar before splatting it,
9544   // if necessary.
9545   CastKind scalarCast = CK_NoOp;
9546 
9547   if (vectorEltTy->isIntegralType(S.Context)) {
9548     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9549         (scalarTy->isIntegerType() &&
9550          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9551       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9552       return true;
9553     }
9554     if (!scalarTy->isIntegralType(S.Context))
9555       return true;
9556     scalarCast = CK_IntegralCast;
9557   } else if (vectorEltTy->isRealFloatingType()) {
9558     if (scalarTy->isRealFloatingType()) {
9559       if (S.getLangOpts().OpenCL &&
9560           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9561         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9562         return true;
9563       }
9564       scalarCast = CK_FloatingCast;
9565     }
9566     else if (scalarTy->isIntegralType(S.Context))
9567       scalarCast = CK_IntegralToFloating;
9568     else
9569       return true;
9570   } else {
9571     return true;
9572   }
9573 
9574   // Adjust scalar if desired.
9575   if (scalar) {
9576     if (scalarCast != CK_NoOp)
9577       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9578     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9579   }
9580   return false;
9581 }
9582 
9583 /// Convert vector E to a vector with the same number of elements but different
9584 /// element type.
9585 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9586   const auto *VecTy = E->getType()->getAs<VectorType>();
9587   assert(VecTy && "Expression E must be a vector");
9588   QualType NewVecTy = S.Context.getVectorType(ElementType,
9589                                               VecTy->getNumElements(),
9590                                               VecTy->getVectorKind());
9591 
9592   // Look through the implicit cast. Return the subexpression if its type is
9593   // NewVecTy.
9594   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9595     if (ICE->getSubExpr()->getType() == NewVecTy)
9596       return ICE->getSubExpr();
9597 
9598   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9599   return S.ImpCastExprToType(E, NewVecTy, Cast);
9600 }
9601 
9602 /// Test if a (constant) integer Int can be casted to another integer type
9603 /// IntTy without losing precision.
9604 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9605                                       QualType OtherIntTy) {
9606   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9607 
9608   // Reject cases where the value of the Int is unknown as that would
9609   // possibly cause truncation, but accept cases where the scalar can be
9610   // demoted without loss of precision.
9611   Expr::EvalResult EVResult;
9612   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9613   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9614   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9615   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9616 
9617   if (CstInt) {
9618     // If the scalar is constant and is of a higher order and has more active
9619     // bits that the vector element type, reject it.
9620     llvm::APSInt Result = EVResult.Val.getInt();
9621     unsigned NumBits = IntSigned
9622                            ? (Result.isNegative() ? Result.getMinSignedBits()
9623                                                   : Result.getActiveBits())
9624                            : Result.getActiveBits();
9625     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9626       return true;
9627 
9628     // If the signedness of the scalar type and the vector element type
9629     // differs and the number of bits is greater than that of the vector
9630     // element reject it.
9631     return (IntSigned != OtherIntSigned &&
9632             NumBits > S.Context.getIntWidth(OtherIntTy));
9633   }
9634 
9635   // Reject cases where the value of the scalar is not constant and it's
9636   // order is greater than that of the vector element type.
9637   return (Order < 0);
9638 }
9639 
9640 /// Test if a (constant) integer Int can be casted to floating point type
9641 /// FloatTy without losing precision.
9642 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9643                                      QualType FloatTy) {
9644   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9645 
9646   // Determine if the integer constant can be expressed as a floating point
9647   // number of the appropriate type.
9648   Expr::EvalResult EVResult;
9649   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9650 
9651   uint64_t Bits = 0;
9652   if (CstInt) {
9653     // Reject constants that would be truncated if they were converted to
9654     // the floating point type. Test by simple to/from conversion.
9655     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9656     //        could be avoided if there was a convertFromAPInt method
9657     //        which could signal back if implicit truncation occurred.
9658     llvm::APSInt Result = EVResult.Val.getInt();
9659     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9660     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9661                            llvm::APFloat::rmTowardZero);
9662     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9663                              !IntTy->hasSignedIntegerRepresentation());
9664     bool Ignored = false;
9665     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9666                            &Ignored);
9667     if (Result != ConvertBack)
9668       return true;
9669   } else {
9670     // Reject types that cannot be fully encoded into the mantissa of
9671     // the float.
9672     Bits = S.Context.getTypeSize(IntTy);
9673     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9674         S.Context.getFloatTypeSemantics(FloatTy));
9675     if (Bits > FloatPrec)
9676       return true;
9677   }
9678 
9679   return false;
9680 }
9681 
9682 /// Attempt to convert and splat Scalar into a vector whose types matches
9683 /// Vector following GCC conversion rules. The rule is that implicit
9684 /// conversion can occur when Scalar can be casted to match Vector's element
9685 /// type without causing truncation of Scalar.
9686 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9687                                         ExprResult *Vector) {
9688   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9689   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9690   const VectorType *VT = VectorTy->getAs<VectorType>();
9691 
9692   assert(!isa<ExtVectorType>(VT) &&
9693          "ExtVectorTypes should not be handled here!");
9694 
9695   QualType VectorEltTy = VT->getElementType();
9696 
9697   // Reject cases where the vector element type or the scalar element type are
9698   // not integral or floating point types.
9699   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9700     return true;
9701 
9702   // The conversion to apply to the scalar before splatting it,
9703   // if necessary.
9704   CastKind ScalarCast = CK_NoOp;
9705 
9706   // Accept cases where the vector elements are integers and the scalar is
9707   // an integer.
9708   // FIXME: Notionally if the scalar was a floating point value with a precise
9709   //        integral representation, we could cast it to an appropriate integer
9710   //        type and then perform the rest of the checks here. GCC will perform
9711   //        this conversion in some cases as determined by the input language.
9712   //        We should accept it on a language independent basis.
9713   if (VectorEltTy->isIntegralType(S.Context) &&
9714       ScalarTy->isIntegralType(S.Context) &&
9715       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9716 
9717     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9718       return true;
9719 
9720     ScalarCast = CK_IntegralCast;
9721   } else if (VectorEltTy->isIntegralType(S.Context) &&
9722              ScalarTy->isRealFloatingType()) {
9723     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9724       ScalarCast = CK_FloatingToIntegral;
9725     else
9726       return true;
9727   } else if (VectorEltTy->isRealFloatingType()) {
9728     if (ScalarTy->isRealFloatingType()) {
9729 
9730       // Reject cases where the scalar type is not a constant and has a higher
9731       // Order than the vector element type.
9732       llvm::APFloat Result(0.0);
9733 
9734       // Determine whether this is a constant scalar. In the event that the
9735       // value is dependent (and thus cannot be evaluated by the constant
9736       // evaluator), skip the evaluation. This will then diagnose once the
9737       // expression is instantiated.
9738       bool CstScalar = Scalar->get()->isValueDependent() ||
9739                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9740       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9741       if (!CstScalar && Order < 0)
9742         return true;
9743 
9744       // If the scalar cannot be safely casted to the vector element type,
9745       // reject it.
9746       if (CstScalar) {
9747         bool Truncated = false;
9748         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9749                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9750         if (Truncated)
9751           return true;
9752       }
9753 
9754       ScalarCast = CK_FloatingCast;
9755     } else if (ScalarTy->isIntegralType(S.Context)) {
9756       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9757         return true;
9758 
9759       ScalarCast = CK_IntegralToFloating;
9760     } else
9761       return true;
9762   } else if (ScalarTy->isEnumeralType())
9763     return true;
9764 
9765   // Adjust scalar if desired.
9766   if (Scalar) {
9767     if (ScalarCast != CK_NoOp)
9768       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9769     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9770   }
9771   return false;
9772 }
9773 
9774 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9775                                    SourceLocation Loc, bool IsCompAssign,
9776                                    bool AllowBothBool,
9777                                    bool AllowBoolConversions) {
9778   if (!IsCompAssign) {
9779     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9780     if (LHS.isInvalid())
9781       return QualType();
9782   }
9783   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9784   if (RHS.isInvalid())
9785     return QualType();
9786 
9787   // For conversion purposes, we ignore any qualifiers.
9788   // For example, "const float" and "float" are equivalent.
9789   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9790   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9791 
9792   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9793   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9794   assert(LHSVecType || RHSVecType);
9795 
9796   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9797       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9798     return InvalidOperands(Loc, LHS, RHS);
9799 
9800   // AltiVec-style "vector bool op vector bool" combinations are allowed
9801   // for some operators but not others.
9802   if (!AllowBothBool &&
9803       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9804       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9805     return InvalidOperands(Loc, LHS, RHS);
9806 
9807   // If the vector types are identical, return.
9808   if (Context.hasSameType(LHSType, RHSType))
9809     return LHSType;
9810 
9811   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9812   if (LHSVecType && RHSVecType &&
9813       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9814     if (isa<ExtVectorType>(LHSVecType)) {
9815       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9816       return LHSType;
9817     }
9818 
9819     if (!IsCompAssign)
9820       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9821     return RHSType;
9822   }
9823 
9824   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9825   // can be mixed, with the result being the non-bool type.  The non-bool
9826   // operand must have integer element type.
9827   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9828       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9829       (Context.getTypeSize(LHSVecType->getElementType()) ==
9830        Context.getTypeSize(RHSVecType->getElementType()))) {
9831     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9832         LHSVecType->getElementType()->isIntegerType() &&
9833         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9834       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9835       return LHSType;
9836     }
9837     if (!IsCompAssign &&
9838         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9839         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9840         RHSVecType->getElementType()->isIntegerType()) {
9841       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9842       return RHSType;
9843     }
9844   }
9845 
9846   // If there's a vector type and a scalar, try to convert the scalar to
9847   // the vector element type and splat.
9848   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9849   if (!RHSVecType) {
9850     if (isa<ExtVectorType>(LHSVecType)) {
9851       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9852                                     LHSVecType->getElementType(), LHSType,
9853                                     DiagID))
9854         return LHSType;
9855     } else {
9856       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9857         return LHSType;
9858     }
9859   }
9860   if (!LHSVecType) {
9861     if (isa<ExtVectorType>(RHSVecType)) {
9862       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9863                                     LHSType, RHSVecType->getElementType(),
9864                                     RHSType, DiagID))
9865         return RHSType;
9866     } else {
9867       if (LHS.get()->getValueKind() == VK_LValue ||
9868           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9869         return RHSType;
9870     }
9871   }
9872 
9873   // FIXME: The code below also handles conversion between vectors and
9874   // non-scalars, we should break this down into fine grained specific checks
9875   // and emit proper diagnostics.
9876   QualType VecType = LHSVecType ? LHSType : RHSType;
9877   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9878   QualType OtherType = LHSVecType ? RHSType : LHSType;
9879   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9880   if (isLaxVectorConversion(OtherType, VecType)) {
9881     // If we're allowing lax vector conversions, only the total (data) size
9882     // needs to be the same. For non compound assignment, if one of the types is
9883     // scalar, the result is always the vector type.
9884     if (!IsCompAssign) {
9885       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9886       return VecType;
9887     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9888     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9889     // type. Note that this is already done by non-compound assignments in
9890     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9891     // <1 x T> -> T. The result is also a vector type.
9892     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9893                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9894       ExprResult *RHSExpr = &RHS;
9895       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9896       return VecType;
9897     }
9898   }
9899 
9900   // Okay, the expression is invalid.
9901 
9902   // If there's a non-vector, non-real operand, diagnose that.
9903   if ((!RHSVecType && !RHSType->isRealType()) ||
9904       (!LHSVecType && !LHSType->isRealType())) {
9905     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9906       << LHSType << RHSType
9907       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9908     return QualType();
9909   }
9910 
9911   // OpenCL V1.1 6.2.6.p1:
9912   // If the operands are of more than one vector type, then an error shall
9913   // occur. Implicit conversions between vector types are not permitted, per
9914   // section 6.2.1.
9915   if (getLangOpts().OpenCL &&
9916       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9917       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9918     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9919                                                            << RHSType;
9920     return QualType();
9921   }
9922 
9923 
9924   // If there is a vector type that is not a ExtVector and a scalar, we reach
9925   // this point if scalar could not be converted to the vector's element type
9926   // without truncation.
9927   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9928       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9929     QualType Scalar = LHSVecType ? RHSType : LHSType;
9930     QualType Vector = LHSVecType ? LHSType : RHSType;
9931     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9932     Diag(Loc,
9933          diag::err_typecheck_vector_not_convertable_implict_truncation)
9934         << ScalarOrVector << Scalar << Vector;
9935 
9936     return QualType();
9937   }
9938 
9939   // Otherwise, use the generic diagnostic.
9940   Diag(Loc, DiagID)
9941     << LHSType << RHSType
9942     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9943   return QualType();
9944 }
9945 
9946 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9947 // expression.  These are mainly cases where the null pointer is used as an
9948 // integer instead of a pointer.
9949 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9950                                 SourceLocation Loc, bool IsCompare) {
9951   // The canonical way to check for a GNU null is with isNullPointerConstant,
9952   // but we use a bit of a hack here for speed; this is a relatively
9953   // hot path, and isNullPointerConstant is slow.
9954   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9955   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9956 
9957   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9958 
9959   // Avoid analyzing cases where the result will either be invalid (and
9960   // diagnosed as such) or entirely valid and not something to warn about.
9961   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9962       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9963     return;
9964 
9965   // Comparison operations would not make sense with a null pointer no matter
9966   // what the other expression is.
9967   if (!IsCompare) {
9968     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9969         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9970         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9971     return;
9972   }
9973 
9974   // The rest of the operations only make sense with a null pointer
9975   // if the other expression is a pointer.
9976   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9977       NonNullType->canDecayToPointerType())
9978     return;
9979 
9980   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9981       << LHSNull /* LHS is NULL */ << NonNullType
9982       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9983 }
9984 
9985 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9986                                           SourceLocation Loc) {
9987   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9988   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9989   if (!LUE || !RUE)
9990     return;
9991   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9992       RUE->getKind() != UETT_SizeOf)
9993     return;
9994 
9995   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9996   QualType LHSTy = LHSArg->getType();
9997   QualType RHSTy;
9998 
9999   if (RUE->isArgumentType())
10000     RHSTy = RUE->getArgumentType();
10001   else
10002     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10003 
10004   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10005     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10006       return;
10007 
10008     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10009     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10010       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10011         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10012             << LHSArgDecl;
10013     }
10014   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10015     QualType ArrayElemTy = ArrayTy->getElementType();
10016     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10017         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10018         ArrayElemTy->isCharType() ||
10019         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10020       return;
10021     S.Diag(Loc, diag::warn_division_sizeof_array)
10022         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10023     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10024       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10025         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10026             << LHSArgDecl;
10027     }
10028 
10029     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10030   }
10031 }
10032 
10033 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10034                                                ExprResult &RHS,
10035                                                SourceLocation Loc, bool IsDiv) {
10036   // Check for division/remainder by zero.
10037   Expr::EvalResult RHSValue;
10038   if (!RHS.get()->isValueDependent() &&
10039       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10040       RHSValue.Val.getInt() == 0)
10041     S.DiagRuntimeBehavior(Loc, RHS.get(),
10042                           S.PDiag(diag::warn_remainder_division_by_zero)
10043                             << IsDiv << RHS.get()->getSourceRange());
10044 }
10045 
10046 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10047                                            SourceLocation Loc,
10048                                            bool IsCompAssign, bool IsDiv) {
10049   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10050 
10051   if (LHS.get()->getType()->isVectorType() ||
10052       RHS.get()->getType()->isVectorType())
10053     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10054                                /*AllowBothBool*/getLangOpts().AltiVec,
10055                                /*AllowBoolConversions*/false);
10056   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10057                  RHS.get()->getType()->isConstantMatrixType()))
10058     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10059 
10060   QualType compType = UsualArithmeticConversions(
10061       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10062   if (LHS.isInvalid() || RHS.isInvalid())
10063     return QualType();
10064 
10065 
10066   if (compType.isNull() || !compType->isArithmeticType())
10067     return InvalidOperands(Loc, LHS, RHS);
10068   if (IsDiv) {
10069     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10070     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10071   }
10072   return compType;
10073 }
10074 
10075 QualType Sema::CheckRemainderOperands(
10076   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10077   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10078 
10079   if (LHS.get()->getType()->isVectorType() ||
10080       RHS.get()->getType()->isVectorType()) {
10081     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10082         RHS.get()->getType()->hasIntegerRepresentation())
10083       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10084                                  /*AllowBothBool*/getLangOpts().AltiVec,
10085                                  /*AllowBoolConversions*/false);
10086     return InvalidOperands(Loc, LHS, RHS);
10087   }
10088 
10089   QualType compType = UsualArithmeticConversions(
10090       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10091   if (LHS.isInvalid() || RHS.isInvalid())
10092     return QualType();
10093 
10094   if (compType.isNull() || !compType->isIntegerType())
10095     return InvalidOperands(Loc, LHS, RHS);
10096   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10097   return compType;
10098 }
10099 
10100 /// Diagnose invalid arithmetic on two void pointers.
10101 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10102                                                 Expr *LHSExpr, Expr *RHSExpr) {
10103   S.Diag(Loc, S.getLangOpts().CPlusPlus
10104                 ? diag::err_typecheck_pointer_arith_void_type
10105                 : diag::ext_gnu_void_ptr)
10106     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10107                             << RHSExpr->getSourceRange();
10108 }
10109 
10110 /// Diagnose invalid arithmetic on a void pointer.
10111 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10112                                             Expr *Pointer) {
10113   S.Diag(Loc, S.getLangOpts().CPlusPlus
10114                 ? diag::err_typecheck_pointer_arith_void_type
10115                 : diag::ext_gnu_void_ptr)
10116     << 0 /* one pointer */ << Pointer->getSourceRange();
10117 }
10118 
10119 /// Diagnose invalid arithmetic on a null pointer.
10120 ///
10121 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10122 /// idiom, which we recognize as a GNU extension.
10123 ///
10124 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10125                                             Expr *Pointer, bool IsGNUIdiom) {
10126   if (IsGNUIdiom)
10127     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10128       << Pointer->getSourceRange();
10129   else
10130     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10131       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10132 }
10133 
10134 /// Diagnose invalid arithmetic on two function pointers.
10135 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10136                                                     Expr *LHS, Expr *RHS) {
10137   assert(LHS->getType()->isAnyPointerType());
10138   assert(RHS->getType()->isAnyPointerType());
10139   S.Diag(Loc, S.getLangOpts().CPlusPlus
10140                 ? diag::err_typecheck_pointer_arith_function_type
10141                 : diag::ext_gnu_ptr_func_arith)
10142     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10143     // We only show the second type if it differs from the first.
10144     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10145                                                    RHS->getType())
10146     << RHS->getType()->getPointeeType()
10147     << LHS->getSourceRange() << RHS->getSourceRange();
10148 }
10149 
10150 /// Diagnose invalid arithmetic on a function pointer.
10151 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10152                                                 Expr *Pointer) {
10153   assert(Pointer->getType()->isAnyPointerType());
10154   S.Diag(Loc, S.getLangOpts().CPlusPlus
10155                 ? diag::err_typecheck_pointer_arith_function_type
10156                 : diag::ext_gnu_ptr_func_arith)
10157     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10158     << 0 /* one pointer, so only one type */
10159     << Pointer->getSourceRange();
10160 }
10161 
10162 /// Emit error if Operand is incomplete pointer type
10163 ///
10164 /// \returns True if pointer has incomplete type
10165 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10166                                                  Expr *Operand) {
10167   QualType ResType = Operand->getType();
10168   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10169     ResType = ResAtomicType->getValueType();
10170 
10171   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10172   QualType PointeeTy = ResType->getPointeeType();
10173   return S.RequireCompleteSizedType(
10174       Loc, PointeeTy,
10175       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10176       Operand->getSourceRange());
10177 }
10178 
10179 /// Check the validity of an arithmetic pointer operand.
10180 ///
10181 /// If the operand has pointer type, this code will check for pointer types
10182 /// which are invalid in arithmetic operations. These will be diagnosed
10183 /// appropriately, including whether or not the use is supported as an
10184 /// extension.
10185 ///
10186 /// \returns True when the operand is valid to use (even if as an extension).
10187 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10188                                             Expr *Operand) {
10189   QualType ResType = Operand->getType();
10190   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10191     ResType = ResAtomicType->getValueType();
10192 
10193   if (!ResType->isAnyPointerType()) return true;
10194 
10195   QualType PointeeTy = ResType->getPointeeType();
10196   if (PointeeTy->isVoidType()) {
10197     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10198     return !S.getLangOpts().CPlusPlus;
10199   }
10200   if (PointeeTy->isFunctionType()) {
10201     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10202     return !S.getLangOpts().CPlusPlus;
10203   }
10204 
10205   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10206 
10207   return true;
10208 }
10209 
10210 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10211 /// operands.
10212 ///
10213 /// This routine will diagnose any invalid arithmetic on pointer operands much
10214 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10215 /// for emitting a single diagnostic even for operations where both LHS and RHS
10216 /// are (potentially problematic) pointers.
10217 ///
10218 /// \returns True when the operand is valid to use (even if as an extension).
10219 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10220                                                 Expr *LHSExpr, Expr *RHSExpr) {
10221   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10222   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10223   if (!isLHSPointer && !isRHSPointer) return true;
10224 
10225   QualType LHSPointeeTy, RHSPointeeTy;
10226   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10227   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10228 
10229   // if both are pointers check if operation is valid wrt address spaces
10230   if (isLHSPointer && isRHSPointer) {
10231     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10232       S.Diag(Loc,
10233              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10234           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10235           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10236       return false;
10237     }
10238   }
10239 
10240   // Check for arithmetic on pointers to incomplete types.
10241   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10242   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10243   if (isLHSVoidPtr || isRHSVoidPtr) {
10244     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10245     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10246     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10247 
10248     return !S.getLangOpts().CPlusPlus;
10249   }
10250 
10251   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10252   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10253   if (isLHSFuncPtr || isRHSFuncPtr) {
10254     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10255     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10256                                                                 RHSExpr);
10257     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10258 
10259     return !S.getLangOpts().CPlusPlus;
10260   }
10261 
10262   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10263     return false;
10264   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10265     return false;
10266 
10267   return true;
10268 }
10269 
10270 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10271 /// literal.
10272 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10273                                   Expr *LHSExpr, Expr *RHSExpr) {
10274   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10275   Expr* IndexExpr = RHSExpr;
10276   if (!StrExpr) {
10277     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10278     IndexExpr = LHSExpr;
10279   }
10280 
10281   bool IsStringPlusInt = StrExpr &&
10282       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10283   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10284     return;
10285 
10286   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10287   Self.Diag(OpLoc, diag::warn_string_plus_int)
10288       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10289 
10290   // Only print a fixit for "str" + int, not for int + "str".
10291   if (IndexExpr == RHSExpr) {
10292     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10293     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10294         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10295         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10296         << FixItHint::CreateInsertion(EndLoc, "]");
10297   } else
10298     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10299 }
10300 
10301 /// Emit a warning when adding a char literal to a string.
10302 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10303                                    Expr *LHSExpr, Expr *RHSExpr) {
10304   const Expr *StringRefExpr = LHSExpr;
10305   const CharacterLiteral *CharExpr =
10306       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10307 
10308   if (!CharExpr) {
10309     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10310     StringRefExpr = RHSExpr;
10311   }
10312 
10313   if (!CharExpr || !StringRefExpr)
10314     return;
10315 
10316   const QualType StringType = StringRefExpr->getType();
10317 
10318   // Return if not a PointerType.
10319   if (!StringType->isAnyPointerType())
10320     return;
10321 
10322   // Return if not a CharacterType.
10323   if (!StringType->getPointeeType()->isAnyCharacterType())
10324     return;
10325 
10326   ASTContext &Ctx = Self.getASTContext();
10327   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10328 
10329   const QualType CharType = CharExpr->getType();
10330   if (!CharType->isAnyCharacterType() &&
10331       CharType->isIntegerType() &&
10332       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10333     Self.Diag(OpLoc, diag::warn_string_plus_char)
10334         << DiagRange << Ctx.CharTy;
10335   } else {
10336     Self.Diag(OpLoc, diag::warn_string_plus_char)
10337         << DiagRange << CharExpr->getType();
10338   }
10339 
10340   // Only print a fixit for str + char, not for char + str.
10341   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10342     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10343     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10344         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10345         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10346         << FixItHint::CreateInsertion(EndLoc, "]");
10347   } else {
10348     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10349   }
10350 }
10351 
10352 /// Emit error when two pointers are incompatible.
10353 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10354                                            Expr *LHSExpr, Expr *RHSExpr) {
10355   assert(LHSExpr->getType()->isAnyPointerType());
10356   assert(RHSExpr->getType()->isAnyPointerType());
10357   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10358     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10359     << RHSExpr->getSourceRange();
10360 }
10361 
10362 // C99 6.5.6
10363 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10364                                      SourceLocation Loc, BinaryOperatorKind Opc,
10365                                      QualType* CompLHSTy) {
10366   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10367 
10368   if (LHS.get()->getType()->isVectorType() ||
10369       RHS.get()->getType()->isVectorType()) {
10370     QualType compType = CheckVectorOperands(
10371         LHS, RHS, Loc, CompLHSTy,
10372         /*AllowBothBool*/getLangOpts().AltiVec,
10373         /*AllowBoolConversions*/getLangOpts().ZVector);
10374     if (CompLHSTy) *CompLHSTy = compType;
10375     return compType;
10376   }
10377 
10378   if (LHS.get()->getType()->isConstantMatrixType() ||
10379       RHS.get()->getType()->isConstantMatrixType()) {
10380     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10381   }
10382 
10383   QualType compType = UsualArithmeticConversions(
10384       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10385   if (LHS.isInvalid() || RHS.isInvalid())
10386     return QualType();
10387 
10388   // Diagnose "string literal" '+' int and string '+' "char literal".
10389   if (Opc == BO_Add) {
10390     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10391     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10392   }
10393 
10394   // handle the common case first (both operands are arithmetic).
10395   if (!compType.isNull() && compType->isArithmeticType()) {
10396     if (CompLHSTy) *CompLHSTy = compType;
10397     return compType;
10398   }
10399 
10400   // Type-checking.  Ultimately the pointer's going to be in PExp;
10401   // note that we bias towards the LHS being the pointer.
10402   Expr *PExp = LHS.get(), *IExp = RHS.get();
10403 
10404   bool isObjCPointer;
10405   if (PExp->getType()->isPointerType()) {
10406     isObjCPointer = false;
10407   } else if (PExp->getType()->isObjCObjectPointerType()) {
10408     isObjCPointer = true;
10409   } else {
10410     std::swap(PExp, IExp);
10411     if (PExp->getType()->isPointerType()) {
10412       isObjCPointer = false;
10413     } else if (PExp->getType()->isObjCObjectPointerType()) {
10414       isObjCPointer = true;
10415     } else {
10416       return InvalidOperands(Loc, LHS, RHS);
10417     }
10418   }
10419   assert(PExp->getType()->isAnyPointerType());
10420 
10421   if (!IExp->getType()->isIntegerType())
10422     return InvalidOperands(Loc, LHS, RHS);
10423 
10424   // Adding to a null pointer results in undefined behavior.
10425   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10426           Context, Expr::NPC_ValueDependentIsNotNull)) {
10427     // In C++ adding zero to a null pointer is defined.
10428     Expr::EvalResult KnownVal;
10429     if (!getLangOpts().CPlusPlus ||
10430         (!IExp->isValueDependent() &&
10431          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10432           KnownVal.Val.getInt() != 0))) {
10433       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10434       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10435           Context, BO_Add, PExp, IExp);
10436       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10437     }
10438   }
10439 
10440   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10441     return QualType();
10442 
10443   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10444     return QualType();
10445 
10446   // Check array bounds for pointer arithemtic
10447   CheckArrayAccess(PExp, IExp);
10448 
10449   if (CompLHSTy) {
10450     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10451     if (LHSTy.isNull()) {
10452       LHSTy = LHS.get()->getType();
10453       if (LHSTy->isPromotableIntegerType())
10454         LHSTy = Context.getPromotedIntegerType(LHSTy);
10455     }
10456     *CompLHSTy = LHSTy;
10457   }
10458 
10459   return PExp->getType();
10460 }
10461 
10462 // C99 6.5.6
10463 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10464                                         SourceLocation Loc,
10465                                         QualType* CompLHSTy) {
10466   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10467 
10468   if (LHS.get()->getType()->isVectorType() ||
10469       RHS.get()->getType()->isVectorType()) {
10470     QualType compType = CheckVectorOperands(
10471         LHS, RHS, Loc, CompLHSTy,
10472         /*AllowBothBool*/getLangOpts().AltiVec,
10473         /*AllowBoolConversions*/getLangOpts().ZVector);
10474     if (CompLHSTy) *CompLHSTy = compType;
10475     return compType;
10476   }
10477 
10478   if (LHS.get()->getType()->isConstantMatrixType() ||
10479       RHS.get()->getType()->isConstantMatrixType()) {
10480     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10481   }
10482 
10483   QualType compType = UsualArithmeticConversions(
10484       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10485   if (LHS.isInvalid() || RHS.isInvalid())
10486     return QualType();
10487 
10488   // Enforce type constraints: C99 6.5.6p3.
10489 
10490   // Handle the common case first (both operands are arithmetic).
10491   if (!compType.isNull() && compType->isArithmeticType()) {
10492     if (CompLHSTy) *CompLHSTy = compType;
10493     return compType;
10494   }
10495 
10496   // Either ptr - int   or   ptr - ptr.
10497   if (LHS.get()->getType()->isAnyPointerType()) {
10498     QualType lpointee = LHS.get()->getType()->getPointeeType();
10499 
10500     // Diagnose bad cases where we step over interface counts.
10501     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10502         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10503       return QualType();
10504 
10505     // The result type of a pointer-int computation is the pointer type.
10506     if (RHS.get()->getType()->isIntegerType()) {
10507       // Subtracting from a null pointer should produce a warning.
10508       // The last argument to the diagnose call says this doesn't match the
10509       // GNU int-to-pointer idiom.
10510       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10511                                            Expr::NPC_ValueDependentIsNotNull)) {
10512         // In C++ adding zero to a null pointer is defined.
10513         Expr::EvalResult KnownVal;
10514         if (!getLangOpts().CPlusPlus ||
10515             (!RHS.get()->isValueDependent() &&
10516              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10517               KnownVal.Val.getInt() != 0))) {
10518           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10519         }
10520       }
10521 
10522       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10523         return QualType();
10524 
10525       // Check array bounds for pointer arithemtic
10526       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10527                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10528 
10529       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10530       return LHS.get()->getType();
10531     }
10532 
10533     // Handle pointer-pointer subtractions.
10534     if (const PointerType *RHSPTy
10535           = RHS.get()->getType()->getAs<PointerType>()) {
10536       QualType rpointee = RHSPTy->getPointeeType();
10537 
10538       if (getLangOpts().CPlusPlus) {
10539         // Pointee types must be the same: C++ [expr.add]
10540         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10541           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10542         }
10543       } else {
10544         // Pointee types must be compatible C99 6.5.6p3
10545         if (!Context.typesAreCompatible(
10546                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10547                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10548           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10549           return QualType();
10550         }
10551       }
10552 
10553       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10554                                                LHS.get(), RHS.get()))
10555         return QualType();
10556 
10557       // FIXME: Add warnings for nullptr - ptr.
10558 
10559       // The pointee type may have zero size.  As an extension, a structure or
10560       // union may have zero size or an array may have zero length.  In this
10561       // case subtraction does not make sense.
10562       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10563         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10564         if (ElementSize.isZero()) {
10565           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10566             << rpointee.getUnqualifiedType()
10567             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10568         }
10569       }
10570 
10571       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10572       return Context.getPointerDiffType();
10573     }
10574   }
10575 
10576   return InvalidOperands(Loc, LHS, RHS);
10577 }
10578 
10579 static bool isScopedEnumerationType(QualType T) {
10580   if (const EnumType *ET = T->getAs<EnumType>())
10581     return ET->getDecl()->isScoped();
10582   return false;
10583 }
10584 
10585 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10586                                    SourceLocation Loc, BinaryOperatorKind Opc,
10587                                    QualType LHSType) {
10588   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10589   // so skip remaining warnings as we don't want to modify values within Sema.
10590   if (S.getLangOpts().OpenCL)
10591     return;
10592 
10593   // Check right/shifter operand
10594   Expr::EvalResult RHSResult;
10595   if (RHS.get()->isValueDependent() ||
10596       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10597     return;
10598   llvm::APSInt Right = RHSResult.Val.getInt();
10599 
10600   if (Right.isNegative()) {
10601     S.DiagRuntimeBehavior(Loc, RHS.get(),
10602                           S.PDiag(diag::warn_shift_negative)
10603                             << RHS.get()->getSourceRange());
10604     return;
10605   }
10606 
10607   QualType LHSExprType = LHS.get()->getType();
10608   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10609   if (LHSExprType->isExtIntType())
10610     LeftSize = S.Context.getIntWidth(LHSExprType);
10611   else if (LHSExprType->isFixedPointType()) {
10612     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10613     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10614   }
10615   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10616   if (Right.uge(LeftBits)) {
10617     S.DiagRuntimeBehavior(Loc, RHS.get(),
10618                           S.PDiag(diag::warn_shift_gt_typewidth)
10619                             << RHS.get()->getSourceRange());
10620     return;
10621   }
10622 
10623   // FIXME: We probably need to handle fixed point types specially here.
10624   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10625     return;
10626 
10627   // When left shifting an ICE which is signed, we can check for overflow which
10628   // according to C++ standards prior to C++2a has undefined behavior
10629   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10630   // more than the maximum value representable in the result type, so never
10631   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10632   // expression is still probably a bug.)
10633   Expr::EvalResult LHSResult;
10634   if (LHS.get()->isValueDependent() ||
10635       LHSType->hasUnsignedIntegerRepresentation() ||
10636       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10637     return;
10638   llvm::APSInt Left = LHSResult.Val.getInt();
10639 
10640   // If LHS does not have a signed type and non-negative value
10641   // then, the behavior is undefined before C++2a. Warn about it.
10642   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10643       !S.getLangOpts().CPlusPlus20) {
10644     S.DiagRuntimeBehavior(Loc, LHS.get(),
10645                           S.PDiag(diag::warn_shift_lhs_negative)
10646                             << LHS.get()->getSourceRange());
10647     return;
10648   }
10649 
10650   llvm::APInt ResultBits =
10651       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10652   if (LeftBits.uge(ResultBits))
10653     return;
10654   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10655   Result = Result.shl(Right);
10656 
10657   // Print the bit representation of the signed integer as an unsigned
10658   // hexadecimal number.
10659   SmallString<40> HexResult;
10660   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10661 
10662   // If we are only missing a sign bit, this is less likely to result in actual
10663   // bugs -- if the result is cast back to an unsigned type, it will have the
10664   // expected value. Thus we place this behind a different warning that can be
10665   // turned off separately if needed.
10666   if (LeftBits == ResultBits - 1) {
10667     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10668         << HexResult << LHSType
10669         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10670     return;
10671   }
10672 
10673   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10674     << HexResult.str() << Result.getMinSignedBits() << LHSType
10675     << Left.getBitWidth() << LHS.get()->getSourceRange()
10676     << RHS.get()->getSourceRange();
10677 }
10678 
10679 /// Return the resulting type when a vector is shifted
10680 ///        by a scalar or vector shift amount.
10681 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10682                                  SourceLocation Loc, bool IsCompAssign) {
10683   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10684   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10685       !LHS.get()->getType()->isVectorType()) {
10686     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10687       << RHS.get()->getType() << LHS.get()->getType()
10688       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10689     return QualType();
10690   }
10691 
10692   if (!IsCompAssign) {
10693     LHS = S.UsualUnaryConversions(LHS.get());
10694     if (LHS.isInvalid()) return QualType();
10695   }
10696 
10697   RHS = S.UsualUnaryConversions(RHS.get());
10698   if (RHS.isInvalid()) return QualType();
10699 
10700   QualType LHSType = LHS.get()->getType();
10701   // Note that LHS might be a scalar because the routine calls not only in
10702   // OpenCL case.
10703   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10704   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10705 
10706   // Note that RHS might not be a vector.
10707   QualType RHSType = RHS.get()->getType();
10708   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10709   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10710 
10711   // The operands need to be integers.
10712   if (!LHSEleType->isIntegerType()) {
10713     S.Diag(Loc, diag::err_typecheck_expect_int)
10714       << LHS.get()->getType() << LHS.get()->getSourceRange();
10715     return QualType();
10716   }
10717 
10718   if (!RHSEleType->isIntegerType()) {
10719     S.Diag(Loc, diag::err_typecheck_expect_int)
10720       << RHS.get()->getType() << RHS.get()->getSourceRange();
10721     return QualType();
10722   }
10723 
10724   if (!LHSVecTy) {
10725     assert(RHSVecTy);
10726     if (IsCompAssign)
10727       return RHSType;
10728     if (LHSEleType != RHSEleType) {
10729       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10730       LHSEleType = RHSEleType;
10731     }
10732     QualType VecTy =
10733         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10734     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10735     LHSType = VecTy;
10736   } else if (RHSVecTy) {
10737     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10738     // are applied component-wise. So if RHS is a vector, then ensure
10739     // that the number of elements is the same as LHS...
10740     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10741       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10742         << LHS.get()->getType() << RHS.get()->getType()
10743         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10744       return QualType();
10745     }
10746     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10747       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10748       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10749       if (LHSBT != RHSBT &&
10750           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10751         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10752             << LHS.get()->getType() << RHS.get()->getType()
10753             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10754       }
10755     }
10756   } else {
10757     // ...else expand RHS to match the number of elements in LHS.
10758     QualType VecTy =
10759       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10760     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10761   }
10762 
10763   return LHSType;
10764 }
10765 
10766 // C99 6.5.7
10767 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10768                                   SourceLocation Loc, BinaryOperatorKind Opc,
10769                                   bool IsCompAssign) {
10770   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10771 
10772   // Vector shifts promote their scalar inputs to vector type.
10773   if (LHS.get()->getType()->isVectorType() ||
10774       RHS.get()->getType()->isVectorType()) {
10775     if (LangOpts.ZVector) {
10776       // The shift operators for the z vector extensions work basically
10777       // like general shifts, except that neither the LHS nor the RHS is
10778       // allowed to be a "vector bool".
10779       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10780         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10781           return InvalidOperands(Loc, LHS, RHS);
10782       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10783         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10784           return InvalidOperands(Loc, LHS, RHS);
10785     }
10786     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10787   }
10788 
10789   // Shifts don't perform usual arithmetic conversions, they just do integer
10790   // promotions on each operand. C99 6.5.7p3
10791 
10792   // For the LHS, do usual unary conversions, but then reset them away
10793   // if this is a compound assignment.
10794   ExprResult OldLHS = LHS;
10795   LHS = UsualUnaryConversions(LHS.get());
10796   if (LHS.isInvalid())
10797     return QualType();
10798   QualType LHSType = LHS.get()->getType();
10799   if (IsCompAssign) LHS = OldLHS;
10800 
10801   // The RHS is simpler.
10802   RHS = UsualUnaryConversions(RHS.get());
10803   if (RHS.isInvalid())
10804     return QualType();
10805   QualType RHSType = RHS.get()->getType();
10806 
10807   // C99 6.5.7p2: Each of the operands shall have integer type.
10808   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10809   if ((!LHSType->isFixedPointOrIntegerType() &&
10810        !LHSType->hasIntegerRepresentation()) ||
10811       !RHSType->hasIntegerRepresentation())
10812     return InvalidOperands(Loc, LHS, RHS);
10813 
10814   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10815   // hasIntegerRepresentation() above instead of this.
10816   if (isScopedEnumerationType(LHSType) ||
10817       isScopedEnumerationType(RHSType)) {
10818     return InvalidOperands(Loc, LHS, RHS);
10819   }
10820   // Sanity-check shift operands
10821   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10822 
10823   // "The type of the result is that of the promoted left operand."
10824   return LHSType;
10825 }
10826 
10827 /// Diagnose bad pointer comparisons.
10828 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10829                                               ExprResult &LHS, ExprResult &RHS,
10830                                               bool IsError) {
10831   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10832                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10833     << LHS.get()->getType() << RHS.get()->getType()
10834     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10835 }
10836 
10837 /// Returns false if the pointers are converted to a composite type,
10838 /// true otherwise.
10839 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10840                                            ExprResult &LHS, ExprResult &RHS) {
10841   // C++ [expr.rel]p2:
10842   //   [...] Pointer conversions (4.10) and qualification
10843   //   conversions (4.4) are performed on pointer operands (or on
10844   //   a pointer operand and a null pointer constant) to bring
10845   //   them to their composite pointer type. [...]
10846   //
10847   // C++ [expr.eq]p1 uses the same notion for (in)equality
10848   // comparisons of pointers.
10849 
10850   QualType LHSType = LHS.get()->getType();
10851   QualType RHSType = RHS.get()->getType();
10852   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10853          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10854 
10855   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10856   if (T.isNull()) {
10857     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10858         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10859       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10860     else
10861       S.InvalidOperands(Loc, LHS, RHS);
10862     return true;
10863   }
10864 
10865   return false;
10866 }
10867 
10868 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10869                                                     ExprResult &LHS,
10870                                                     ExprResult &RHS,
10871                                                     bool IsError) {
10872   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10873                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10874     << LHS.get()->getType() << RHS.get()->getType()
10875     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10876 }
10877 
10878 static bool isObjCObjectLiteral(ExprResult &E) {
10879   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10880   case Stmt::ObjCArrayLiteralClass:
10881   case Stmt::ObjCDictionaryLiteralClass:
10882   case Stmt::ObjCStringLiteralClass:
10883   case Stmt::ObjCBoxedExprClass:
10884     return true;
10885   default:
10886     // Note that ObjCBoolLiteral is NOT an object literal!
10887     return false;
10888   }
10889 }
10890 
10891 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10892   const ObjCObjectPointerType *Type =
10893     LHS->getType()->getAs<ObjCObjectPointerType>();
10894 
10895   // If this is not actually an Objective-C object, bail out.
10896   if (!Type)
10897     return false;
10898 
10899   // Get the LHS object's interface type.
10900   QualType InterfaceType = Type->getPointeeType();
10901 
10902   // If the RHS isn't an Objective-C object, bail out.
10903   if (!RHS->getType()->isObjCObjectPointerType())
10904     return false;
10905 
10906   // Try to find the -isEqual: method.
10907   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10908   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10909                                                       InterfaceType,
10910                                                       /*IsInstance=*/true);
10911   if (!Method) {
10912     if (Type->isObjCIdType()) {
10913       // For 'id', just check the global pool.
10914       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10915                                                   /*receiverId=*/true);
10916     } else {
10917       // Check protocols.
10918       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10919                                              /*IsInstance=*/true);
10920     }
10921   }
10922 
10923   if (!Method)
10924     return false;
10925 
10926   QualType T = Method->parameters()[0]->getType();
10927   if (!T->isObjCObjectPointerType())
10928     return false;
10929 
10930   QualType R = Method->getReturnType();
10931   if (!R->isScalarType())
10932     return false;
10933 
10934   return true;
10935 }
10936 
10937 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10938   FromE = FromE->IgnoreParenImpCasts();
10939   switch (FromE->getStmtClass()) {
10940     default:
10941       break;
10942     case Stmt::ObjCStringLiteralClass:
10943       // "string literal"
10944       return LK_String;
10945     case Stmt::ObjCArrayLiteralClass:
10946       // "array literal"
10947       return LK_Array;
10948     case Stmt::ObjCDictionaryLiteralClass:
10949       // "dictionary literal"
10950       return LK_Dictionary;
10951     case Stmt::BlockExprClass:
10952       return LK_Block;
10953     case Stmt::ObjCBoxedExprClass: {
10954       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10955       switch (Inner->getStmtClass()) {
10956         case Stmt::IntegerLiteralClass:
10957         case Stmt::FloatingLiteralClass:
10958         case Stmt::CharacterLiteralClass:
10959         case Stmt::ObjCBoolLiteralExprClass:
10960         case Stmt::CXXBoolLiteralExprClass:
10961           // "numeric literal"
10962           return LK_Numeric;
10963         case Stmt::ImplicitCastExprClass: {
10964           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10965           // Boolean literals can be represented by implicit casts.
10966           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10967             return LK_Numeric;
10968           break;
10969         }
10970         default:
10971           break;
10972       }
10973       return LK_Boxed;
10974     }
10975   }
10976   return LK_None;
10977 }
10978 
10979 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10980                                           ExprResult &LHS, ExprResult &RHS,
10981                                           BinaryOperator::Opcode Opc){
10982   Expr *Literal;
10983   Expr *Other;
10984   if (isObjCObjectLiteral(LHS)) {
10985     Literal = LHS.get();
10986     Other = RHS.get();
10987   } else {
10988     Literal = RHS.get();
10989     Other = LHS.get();
10990   }
10991 
10992   // Don't warn on comparisons against nil.
10993   Other = Other->IgnoreParenCasts();
10994   if (Other->isNullPointerConstant(S.getASTContext(),
10995                                    Expr::NPC_ValueDependentIsNotNull))
10996     return;
10997 
10998   // This should be kept in sync with warn_objc_literal_comparison.
10999   // LK_String should always be after the other literals, since it has its own
11000   // warning flag.
11001   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11002   assert(LiteralKind != Sema::LK_Block);
11003   if (LiteralKind == Sema::LK_None) {
11004     llvm_unreachable("Unknown Objective-C object literal kind");
11005   }
11006 
11007   if (LiteralKind == Sema::LK_String)
11008     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11009       << Literal->getSourceRange();
11010   else
11011     S.Diag(Loc, diag::warn_objc_literal_comparison)
11012       << LiteralKind << Literal->getSourceRange();
11013 
11014   if (BinaryOperator::isEqualityOp(Opc) &&
11015       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11016     SourceLocation Start = LHS.get()->getBeginLoc();
11017     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11018     CharSourceRange OpRange =
11019       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11020 
11021     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11022       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11023       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11024       << FixItHint::CreateInsertion(End, "]");
11025   }
11026 }
11027 
11028 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11029 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11030                                            ExprResult &RHS, SourceLocation Loc,
11031                                            BinaryOperatorKind Opc) {
11032   // Check that left hand side is !something.
11033   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11034   if (!UO || UO->getOpcode() != UO_LNot) return;
11035 
11036   // Only check if the right hand side is non-bool arithmetic type.
11037   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11038 
11039   // Make sure that the something in !something is not bool.
11040   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11041   if (SubExpr->isKnownToHaveBooleanValue()) return;
11042 
11043   // Emit warning.
11044   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11045   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11046       << Loc << IsBitwiseOp;
11047 
11048   // First note suggest !(x < y)
11049   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11050   SourceLocation FirstClose = RHS.get()->getEndLoc();
11051   FirstClose = S.getLocForEndOfToken(FirstClose);
11052   if (FirstClose.isInvalid())
11053     FirstOpen = SourceLocation();
11054   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11055       << IsBitwiseOp
11056       << FixItHint::CreateInsertion(FirstOpen, "(")
11057       << FixItHint::CreateInsertion(FirstClose, ")");
11058 
11059   // Second note suggests (!x) < y
11060   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11061   SourceLocation SecondClose = LHS.get()->getEndLoc();
11062   SecondClose = S.getLocForEndOfToken(SecondClose);
11063   if (SecondClose.isInvalid())
11064     SecondOpen = SourceLocation();
11065   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11066       << FixItHint::CreateInsertion(SecondOpen, "(")
11067       << FixItHint::CreateInsertion(SecondClose, ")");
11068 }
11069 
11070 // Returns true if E refers to a non-weak array.
11071 static bool checkForArray(const Expr *E) {
11072   const ValueDecl *D = nullptr;
11073   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11074     D = DR->getDecl();
11075   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11076     if (Mem->isImplicitAccess())
11077       D = Mem->getMemberDecl();
11078   }
11079   if (!D)
11080     return false;
11081   return D->getType()->isArrayType() && !D->isWeak();
11082 }
11083 
11084 /// Diagnose some forms of syntactically-obvious tautological comparison.
11085 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11086                                            Expr *LHS, Expr *RHS,
11087                                            BinaryOperatorKind Opc) {
11088   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11089   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11090 
11091   QualType LHSType = LHS->getType();
11092   QualType RHSType = RHS->getType();
11093   if (LHSType->hasFloatingRepresentation() ||
11094       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11095       S.inTemplateInstantiation())
11096     return;
11097 
11098   // Comparisons between two array types are ill-formed for operator<=>, so
11099   // we shouldn't emit any additional warnings about it.
11100   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11101     return;
11102 
11103   // For non-floating point types, check for self-comparisons of the form
11104   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11105   // often indicate logic errors in the program.
11106   //
11107   // NOTE: Don't warn about comparison expressions resulting from macro
11108   // expansion. Also don't warn about comparisons which are only self
11109   // comparisons within a template instantiation. The warnings should catch
11110   // obvious cases in the definition of the template anyways. The idea is to
11111   // warn when the typed comparison operator will always evaluate to the same
11112   // result.
11113 
11114   // Used for indexing into %select in warn_comparison_always
11115   enum {
11116     AlwaysConstant,
11117     AlwaysTrue,
11118     AlwaysFalse,
11119     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11120   };
11121 
11122   // C++2a [depr.array.comp]:
11123   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11124   //   operands of array type are deprecated.
11125   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11126       RHSStripped->getType()->isArrayType()) {
11127     S.Diag(Loc, diag::warn_depr_array_comparison)
11128         << LHS->getSourceRange() << RHS->getSourceRange()
11129         << LHSStripped->getType() << RHSStripped->getType();
11130     // Carry on to produce the tautological comparison warning, if this
11131     // expression is potentially-evaluated, we can resolve the array to a
11132     // non-weak declaration, and so on.
11133   }
11134 
11135   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11136     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11137       unsigned Result;
11138       switch (Opc) {
11139       case BO_EQ:
11140       case BO_LE:
11141       case BO_GE:
11142         Result = AlwaysTrue;
11143         break;
11144       case BO_NE:
11145       case BO_LT:
11146       case BO_GT:
11147         Result = AlwaysFalse;
11148         break;
11149       case BO_Cmp:
11150         Result = AlwaysEqual;
11151         break;
11152       default:
11153         Result = AlwaysConstant;
11154         break;
11155       }
11156       S.DiagRuntimeBehavior(Loc, nullptr,
11157                             S.PDiag(diag::warn_comparison_always)
11158                                 << 0 /*self-comparison*/
11159                                 << Result);
11160     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11161       // What is it always going to evaluate to?
11162       unsigned Result;
11163       switch (Opc) {
11164       case BO_EQ: // e.g. array1 == array2
11165         Result = AlwaysFalse;
11166         break;
11167       case BO_NE: // e.g. array1 != array2
11168         Result = AlwaysTrue;
11169         break;
11170       default: // e.g. array1 <= array2
11171         // The best we can say is 'a constant'
11172         Result = AlwaysConstant;
11173         break;
11174       }
11175       S.DiagRuntimeBehavior(Loc, nullptr,
11176                             S.PDiag(diag::warn_comparison_always)
11177                                 << 1 /*array comparison*/
11178                                 << Result);
11179     }
11180   }
11181 
11182   if (isa<CastExpr>(LHSStripped))
11183     LHSStripped = LHSStripped->IgnoreParenCasts();
11184   if (isa<CastExpr>(RHSStripped))
11185     RHSStripped = RHSStripped->IgnoreParenCasts();
11186 
11187   // Warn about comparisons against a string constant (unless the other
11188   // operand is null); the user probably wants string comparison function.
11189   Expr *LiteralString = nullptr;
11190   Expr *LiteralStringStripped = nullptr;
11191   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11192       !RHSStripped->isNullPointerConstant(S.Context,
11193                                           Expr::NPC_ValueDependentIsNull)) {
11194     LiteralString = LHS;
11195     LiteralStringStripped = LHSStripped;
11196   } else if ((isa<StringLiteral>(RHSStripped) ||
11197               isa<ObjCEncodeExpr>(RHSStripped)) &&
11198              !LHSStripped->isNullPointerConstant(S.Context,
11199                                           Expr::NPC_ValueDependentIsNull)) {
11200     LiteralString = RHS;
11201     LiteralStringStripped = RHSStripped;
11202   }
11203 
11204   if (LiteralString) {
11205     S.DiagRuntimeBehavior(Loc, nullptr,
11206                           S.PDiag(diag::warn_stringcompare)
11207                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11208                               << LiteralString->getSourceRange());
11209   }
11210 }
11211 
11212 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11213   switch (CK) {
11214   default: {
11215 #ifndef NDEBUG
11216     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11217                  << "\n";
11218 #endif
11219     llvm_unreachable("unhandled cast kind");
11220   }
11221   case CK_UserDefinedConversion:
11222     return ICK_Identity;
11223   case CK_LValueToRValue:
11224     return ICK_Lvalue_To_Rvalue;
11225   case CK_ArrayToPointerDecay:
11226     return ICK_Array_To_Pointer;
11227   case CK_FunctionToPointerDecay:
11228     return ICK_Function_To_Pointer;
11229   case CK_IntegralCast:
11230     return ICK_Integral_Conversion;
11231   case CK_FloatingCast:
11232     return ICK_Floating_Conversion;
11233   case CK_IntegralToFloating:
11234   case CK_FloatingToIntegral:
11235     return ICK_Floating_Integral;
11236   case CK_IntegralComplexCast:
11237   case CK_FloatingComplexCast:
11238   case CK_FloatingComplexToIntegralComplex:
11239   case CK_IntegralComplexToFloatingComplex:
11240     return ICK_Complex_Conversion;
11241   case CK_FloatingComplexToReal:
11242   case CK_FloatingRealToComplex:
11243   case CK_IntegralComplexToReal:
11244   case CK_IntegralRealToComplex:
11245     return ICK_Complex_Real;
11246   }
11247 }
11248 
11249 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11250                                              QualType FromType,
11251                                              SourceLocation Loc) {
11252   // Check for a narrowing implicit conversion.
11253   StandardConversionSequence SCS;
11254   SCS.setAsIdentityConversion();
11255   SCS.setToType(0, FromType);
11256   SCS.setToType(1, ToType);
11257   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11258     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11259 
11260   APValue PreNarrowingValue;
11261   QualType PreNarrowingType;
11262   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11263                                PreNarrowingType,
11264                                /*IgnoreFloatToIntegralConversion*/ true)) {
11265   case NK_Dependent_Narrowing:
11266     // Implicit conversion to a narrower type, but the expression is
11267     // value-dependent so we can't tell whether it's actually narrowing.
11268   case NK_Not_Narrowing:
11269     return false;
11270 
11271   case NK_Constant_Narrowing:
11272     // Implicit conversion to a narrower type, and the value is not a constant
11273     // expression.
11274     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11275         << /*Constant*/ 1
11276         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11277     return true;
11278 
11279   case NK_Variable_Narrowing:
11280     // Implicit conversion to a narrower type, and the value is not a constant
11281     // expression.
11282   case NK_Type_Narrowing:
11283     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11284         << /*Constant*/ 0 << FromType << ToType;
11285     // TODO: It's not a constant expression, but what if the user intended it
11286     // to be? Can we produce notes to help them figure out why it isn't?
11287     return true;
11288   }
11289   llvm_unreachable("unhandled case in switch");
11290 }
11291 
11292 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11293                                                          ExprResult &LHS,
11294                                                          ExprResult &RHS,
11295                                                          SourceLocation Loc) {
11296   QualType LHSType = LHS.get()->getType();
11297   QualType RHSType = RHS.get()->getType();
11298   // Dig out the original argument type and expression before implicit casts
11299   // were applied. These are the types/expressions we need to check the
11300   // [expr.spaceship] requirements against.
11301   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11302   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11303   QualType LHSStrippedType = LHSStripped.get()->getType();
11304   QualType RHSStrippedType = RHSStripped.get()->getType();
11305 
11306   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11307   // other is not, the program is ill-formed.
11308   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11309     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11310     return QualType();
11311   }
11312 
11313   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11314   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11315                     RHSStrippedType->isEnumeralType();
11316   if (NumEnumArgs == 1) {
11317     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11318     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11319     if (OtherTy->hasFloatingRepresentation()) {
11320       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11321       return QualType();
11322     }
11323   }
11324   if (NumEnumArgs == 2) {
11325     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11326     // type E, the operator yields the result of converting the operands
11327     // to the underlying type of E and applying <=> to the converted operands.
11328     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11329       S.InvalidOperands(Loc, LHS, RHS);
11330       return QualType();
11331     }
11332     QualType IntType =
11333         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11334     assert(IntType->isArithmeticType());
11335 
11336     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11337     // promote the boolean type, and all other promotable integer types, to
11338     // avoid this.
11339     if (IntType->isPromotableIntegerType())
11340       IntType = S.Context.getPromotedIntegerType(IntType);
11341 
11342     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11343     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11344     LHSType = RHSType = IntType;
11345   }
11346 
11347   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11348   // usual arithmetic conversions are applied to the operands.
11349   QualType Type =
11350       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11351   if (LHS.isInvalid() || RHS.isInvalid())
11352     return QualType();
11353   if (Type.isNull())
11354     return S.InvalidOperands(Loc, LHS, RHS);
11355 
11356   Optional<ComparisonCategoryType> CCT =
11357       getComparisonCategoryForBuiltinCmp(Type);
11358   if (!CCT)
11359     return S.InvalidOperands(Loc, LHS, RHS);
11360 
11361   bool HasNarrowing = checkThreeWayNarrowingConversion(
11362       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11363   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11364                                                    RHS.get()->getBeginLoc());
11365   if (HasNarrowing)
11366     return QualType();
11367 
11368   assert(!Type.isNull() && "composite type for <=> has not been set");
11369 
11370   return S.CheckComparisonCategoryType(
11371       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11372 }
11373 
11374 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11375                                                  ExprResult &RHS,
11376                                                  SourceLocation Loc,
11377                                                  BinaryOperatorKind Opc) {
11378   if (Opc == BO_Cmp)
11379     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11380 
11381   // C99 6.5.8p3 / C99 6.5.9p4
11382   QualType Type =
11383       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11384   if (LHS.isInvalid() || RHS.isInvalid())
11385     return QualType();
11386   if (Type.isNull())
11387     return S.InvalidOperands(Loc, LHS, RHS);
11388   assert(Type->isArithmeticType() || Type->isEnumeralType());
11389 
11390   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11391     return S.InvalidOperands(Loc, LHS, RHS);
11392 
11393   // Check for comparisons of floating point operands using != and ==.
11394   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11395     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11396 
11397   // The result of comparisons is 'bool' in C++, 'int' in C.
11398   return S.Context.getLogicalOperationType();
11399 }
11400 
11401 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11402   if (!NullE.get()->getType()->isAnyPointerType())
11403     return;
11404   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11405   if (!E.get()->getType()->isAnyPointerType() &&
11406       E.get()->isNullPointerConstant(Context,
11407                                      Expr::NPC_ValueDependentIsNotNull) ==
11408         Expr::NPCK_ZeroExpression) {
11409     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11410       if (CL->getValue() == 0)
11411         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11412             << NullValue
11413             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11414                                             NullValue ? "NULL" : "(void *)0");
11415     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11416         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11417         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11418         if (T == Context.CharTy)
11419           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11420               << NullValue
11421               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11422                                               NullValue ? "NULL" : "(void *)0");
11423       }
11424   }
11425 }
11426 
11427 // C99 6.5.8, C++ [expr.rel]
11428 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11429                                     SourceLocation Loc,
11430                                     BinaryOperatorKind Opc) {
11431   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11432   bool IsThreeWay = Opc == BO_Cmp;
11433   bool IsOrdered = IsRelational || IsThreeWay;
11434   auto IsAnyPointerType = [](ExprResult E) {
11435     QualType Ty = E.get()->getType();
11436     return Ty->isPointerType() || Ty->isMemberPointerType();
11437   };
11438 
11439   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11440   // type, array-to-pointer, ..., conversions are performed on both operands to
11441   // bring them to their composite type.
11442   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11443   // any type-related checks.
11444   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11445     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11446     if (LHS.isInvalid())
11447       return QualType();
11448     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11449     if (RHS.isInvalid())
11450       return QualType();
11451   } else {
11452     LHS = DefaultLvalueConversion(LHS.get());
11453     if (LHS.isInvalid())
11454       return QualType();
11455     RHS = DefaultLvalueConversion(RHS.get());
11456     if (RHS.isInvalid())
11457       return QualType();
11458   }
11459 
11460   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11461   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11462     CheckPtrComparisonWithNullChar(LHS, RHS);
11463     CheckPtrComparisonWithNullChar(RHS, LHS);
11464   }
11465 
11466   // Handle vector comparisons separately.
11467   if (LHS.get()->getType()->isVectorType() ||
11468       RHS.get()->getType()->isVectorType())
11469     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11470 
11471   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11472   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11473 
11474   QualType LHSType = LHS.get()->getType();
11475   QualType RHSType = RHS.get()->getType();
11476   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11477       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11478     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11479 
11480   const Expr::NullPointerConstantKind LHSNullKind =
11481       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11482   const Expr::NullPointerConstantKind RHSNullKind =
11483       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11484   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11485   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11486 
11487   auto computeResultTy = [&]() {
11488     if (Opc != BO_Cmp)
11489       return Context.getLogicalOperationType();
11490     assert(getLangOpts().CPlusPlus);
11491     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11492 
11493     QualType CompositeTy = LHS.get()->getType();
11494     assert(!CompositeTy->isReferenceType());
11495 
11496     Optional<ComparisonCategoryType> CCT =
11497         getComparisonCategoryForBuiltinCmp(CompositeTy);
11498     if (!CCT)
11499       return InvalidOperands(Loc, LHS, RHS);
11500 
11501     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11502       // P0946R0: Comparisons between a null pointer constant and an object
11503       // pointer result in std::strong_equality, which is ill-formed under
11504       // P1959R0.
11505       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11506           << (LHSIsNull ? LHS.get()->getSourceRange()
11507                         : RHS.get()->getSourceRange());
11508       return QualType();
11509     }
11510 
11511     return CheckComparisonCategoryType(
11512         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11513   };
11514 
11515   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11516     bool IsEquality = Opc == BO_EQ;
11517     if (RHSIsNull)
11518       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11519                                    RHS.get()->getSourceRange());
11520     else
11521       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11522                                    LHS.get()->getSourceRange());
11523   }
11524 
11525   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11526       (RHSType->isIntegerType() && !RHSIsNull)) {
11527     // Skip normal pointer conversion checks in this case; we have better
11528     // diagnostics for this below.
11529   } else if (getLangOpts().CPlusPlus) {
11530     // Equality comparison of a function pointer to a void pointer is invalid,
11531     // but we allow it as an extension.
11532     // FIXME: If we really want to allow this, should it be part of composite
11533     // pointer type computation so it works in conditionals too?
11534     if (!IsOrdered &&
11535         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11536          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11537       // This is a gcc extension compatibility comparison.
11538       // In a SFINAE context, we treat this as a hard error to maintain
11539       // conformance with the C++ standard.
11540       diagnoseFunctionPointerToVoidComparison(
11541           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11542 
11543       if (isSFINAEContext())
11544         return QualType();
11545 
11546       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11547       return computeResultTy();
11548     }
11549 
11550     // C++ [expr.eq]p2:
11551     //   If at least one operand is a pointer [...] bring them to their
11552     //   composite pointer type.
11553     // C++ [expr.spaceship]p6
11554     //  If at least one of the operands is of pointer type, [...] bring them
11555     //  to their composite pointer type.
11556     // C++ [expr.rel]p2:
11557     //   If both operands are pointers, [...] bring them to their composite
11558     //   pointer type.
11559     // For <=>, the only valid non-pointer types are arrays and functions, and
11560     // we already decayed those, so this is really the same as the relational
11561     // comparison rule.
11562     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11563             (IsOrdered ? 2 : 1) &&
11564         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11565                                          RHSType->isObjCObjectPointerType()))) {
11566       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11567         return QualType();
11568       return computeResultTy();
11569     }
11570   } else if (LHSType->isPointerType() &&
11571              RHSType->isPointerType()) { // C99 6.5.8p2
11572     // All of the following pointer-related warnings are GCC extensions, except
11573     // when handling null pointer constants.
11574     QualType LCanPointeeTy =
11575       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11576     QualType RCanPointeeTy =
11577       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11578 
11579     // C99 6.5.9p2 and C99 6.5.8p2
11580     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11581                                    RCanPointeeTy.getUnqualifiedType())) {
11582       if (IsRelational) {
11583         // Pointers both need to point to complete or incomplete types
11584         if ((LCanPointeeTy->isIncompleteType() !=
11585              RCanPointeeTy->isIncompleteType()) &&
11586             !getLangOpts().C11) {
11587           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11588               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11589               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11590               << RCanPointeeTy->isIncompleteType();
11591         }
11592         if (LCanPointeeTy->isFunctionType()) {
11593           // Valid unless a relational comparison of function pointers
11594           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11595               << LHSType << RHSType << LHS.get()->getSourceRange()
11596               << RHS.get()->getSourceRange();
11597         }
11598       }
11599     } else if (!IsRelational &&
11600                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11601       // Valid unless comparison between non-null pointer and function pointer
11602       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11603           && !LHSIsNull && !RHSIsNull)
11604         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11605                                                 /*isError*/false);
11606     } else {
11607       // Invalid
11608       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11609     }
11610     if (LCanPointeeTy != RCanPointeeTy) {
11611       // Treat NULL constant as a special case in OpenCL.
11612       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11613         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11614           Diag(Loc,
11615                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11616               << LHSType << RHSType << 0 /* comparison */
11617               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11618         }
11619       }
11620       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11621       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11622       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11623                                                : CK_BitCast;
11624       if (LHSIsNull && !RHSIsNull)
11625         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11626       else
11627         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11628     }
11629     return computeResultTy();
11630   }
11631 
11632   if (getLangOpts().CPlusPlus) {
11633     // C++ [expr.eq]p4:
11634     //   Two operands of type std::nullptr_t or one operand of type
11635     //   std::nullptr_t and the other a null pointer constant compare equal.
11636     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11637       if (LHSType->isNullPtrType()) {
11638         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11639         return computeResultTy();
11640       }
11641       if (RHSType->isNullPtrType()) {
11642         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11643         return computeResultTy();
11644       }
11645     }
11646 
11647     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11648     // These aren't covered by the composite pointer type rules.
11649     if (!IsOrdered && RHSType->isNullPtrType() &&
11650         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11651       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11652       return computeResultTy();
11653     }
11654     if (!IsOrdered && LHSType->isNullPtrType() &&
11655         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11656       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11657       return computeResultTy();
11658     }
11659 
11660     if (IsRelational &&
11661         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11662          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11663       // HACK: Relational comparison of nullptr_t against a pointer type is
11664       // invalid per DR583, but we allow it within std::less<> and friends,
11665       // since otherwise common uses of it break.
11666       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11667       // friends to have std::nullptr_t overload candidates.
11668       DeclContext *DC = CurContext;
11669       if (isa<FunctionDecl>(DC))
11670         DC = DC->getParent();
11671       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11672         if (CTSD->isInStdNamespace() &&
11673             llvm::StringSwitch<bool>(CTSD->getName())
11674                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11675                 .Default(false)) {
11676           if (RHSType->isNullPtrType())
11677             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11678           else
11679             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11680           return computeResultTy();
11681         }
11682       }
11683     }
11684 
11685     // C++ [expr.eq]p2:
11686     //   If at least one operand is a pointer to member, [...] bring them to
11687     //   their composite pointer type.
11688     if (!IsOrdered &&
11689         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11690       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11691         return QualType();
11692       else
11693         return computeResultTy();
11694     }
11695   }
11696 
11697   // Handle block pointer types.
11698   if (!IsOrdered && LHSType->isBlockPointerType() &&
11699       RHSType->isBlockPointerType()) {
11700     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11701     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11702 
11703     if (!LHSIsNull && !RHSIsNull &&
11704         !Context.typesAreCompatible(lpointee, rpointee)) {
11705       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11706         << LHSType << RHSType << LHS.get()->getSourceRange()
11707         << RHS.get()->getSourceRange();
11708     }
11709     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11710     return computeResultTy();
11711   }
11712 
11713   // Allow block pointers to be compared with null pointer constants.
11714   if (!IsOrdered
11715       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11716           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11717     if (!LHSIsNull && !RHSIsNull) {
11718       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11719              ->getPointeeType()->isVoidType())
11720             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11721                 ->getPointeeType()->isVoidType())))
11722         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11723           << LHSType << RHSType << LHS.get()->getSourceRange()
11724           << RHS.get()->getSourceRange();
11725     }
11726     if (LHSIsNull && !RHSIsNull)
11727       LHS = ImpCastExprToType(LHS.get(), RHSType,
11728                               RHSType->isPointerType() ? CK_BitCast
11729                                 : CK_AnyPointerToBlockPointerCast);
11730     else
11731       RHS = ImpCastExprToType(RHS.get(), LHSType,
11732                               LHSType->isPointerType() ? CK_BitCast
11733                                 : CK_AnyPointerToBlockPointerCast);
11734     return computeResultTy();
11735   }
11736 
11737   if (LHSType->isObjCObjectPointerType() ||
11738       RHSType->isObjCObjectPointerType()) {
11739     const PointerType *LPT = LHSType->getAs<PointerType>();
11740     const PointerType *RPT = RHSType->getAs<PointerType>();
11741     if (LPT || RPT) {
11742       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11743       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11744 
11745       if (!LPtrToVoid && !RPtrToVoid &&
11746           !Context.typesAreCompatible(LHSType, RHSType)) {
11747         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11748                                           /*isError*/false);
11749       }
11750       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11751       // the RHS, but we have test coverage for this behavior.
11752       // FIXME: Consider using convertPointersToCompositeType in C++.
11753       if (LHSIsNull && !RHSIsNull) {
11754         Expr *E = LHS.get();
11755         if (getLangOpts().ObjCAutoRefCount)
11756           CheckObjCConversion(SourceRange(), RHSType, E,
11757                               CCK_ImplicitConversion);
11758         LHS = ImpCastExprToType(E, RHSType,
11759                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11760       }
11761       else {
11762         Expr *E = RHS.get();
11763         if (getLangOpts().ObjCAutoRefCount)
11764           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11765                               /*Diagnose=*/true,
11766                               /*DiagnoseCFAudited=*/false, Opc);
11767         RHS = ImpCastExprToType(E, LHSType,
11768                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11769       }
11770       return computeResultTy();
11771     }
11772     if (LHSType->isObjCObjectPointerType() &&
11773         RHSType->isObjCObjectPointerType()) {
11774       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11775         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11776                                           /*isError*/false);
11777       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11778         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11779 
11780       if (LHSIsNull && !RHSIsNull)
11781         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11782       else
11783         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11784       return computeResultTy();
11785     }
11786 
11787     if (!IsOrdered && LHSType->isBlockPointerType() &&
11788         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11789       LHS = ImpCastExprToType(LHS.get(), RHSType,
11790                               CK_BlockPointerToObjCPointerCast);
11791       return computeResultTy();
11792     } else if (!IsOrdered &&
11793                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11794                RHSType->isBlockPointerType()) {
11795       RHS = ImpCastExprToType(RHS.get(), LHSType,
11796                               CK_BlockPointerToObjCPointerCast);
11797       return computeResultTy();
11798     }
11799   }
11800   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11801       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11802     unsigned DiagID = 0;
11803     bool isError = false;
11804     if (LangOpts.DebuggerSupport) {
11805       // Under a debugger, allow the comparison of pointers to integers,
11806       // since users tend to want to compare addresses.
11807     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11808                (RHSIsNull && RHSType->isIntegerType())) {
11809       if (IsOrdered) {
11810         isError = getLangOpts().CPlusPlus;
11811         DiagID =
11812           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11813                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11814       }
11815     } else if (getLangOpts().CPlusPlus) {
11816       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11817       isError = true;
11818     } else if (IsOrdered)
11819       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11820     else
11821       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11822 
11823     if (DiagID) {
11824       Diag(Loc, DiagID)
11825         << LHSType << RHSType << LHS.get()->getSourceRange()
11826         << RHS.get()->getSourceRange();
11827       if (isError)
11828         return QualType();
11829     }
11830 
11831     if (LHSType->isIntegerType())
11832       LHS = ImpCastExprToType(LHS.get(), RHSType,
11833                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11834     else
11835       RHS = ImpCastExprToType(RHS.get(), LHSType,
11836                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11837     return computeResultTy();
11838   }
11839 
11840   // Handle block pointers.
11841   if (!IsOrdered && RHSIsNull
11842       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11843     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11844     return computeResultTy();
11845   }
11846   if (!IsOrdered && LHSIsNull
11847       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11848     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11849     return computeResultTy();
11850   }
11851 
11852   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11853     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11854       return computeResultTy();
11855     }
11856 
11857     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11858       return computeResultTy();
11859     }
11860 
11861     if (LHSIsNull && RHSType->isQueueT()) {
11862       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11863       return computeResultTy();
11864     }
11865 
11866     if (LHSType->isQueueT() && RHSIsNull) {
11867       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11868       return computeResultTy();
11869     }
11870   }
11871 
11872   return InvalidOperands(Loc, LHS, RHS);
11873 }
11874 
11875 // Return a signed ext_vector_type that is of identical size and number of
11876 // elements. For floating point vectors, return an integer type of identical
11877 // size and number of elements. In the non ext_vector_type case, search from
11878 // the largest type to the smallest type to avoid cases where long long == long,
11879 // where long gets picked over long long.
11880 QualType Sema::GetSignedVectorType(QualType V) {
11881   const VectorType *VTy = V->castAs<VectorType>();
11882   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11883 
11884   if (isa<ExtVectorType>(VTy)) {
11885     if (TypeSize == Context.getTypeSize(Context.CharTy))
11886       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11887     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11888       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11889     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11890       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11891     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11892       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11893     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11894            "Unhandled vector element size in vector compare");
11895     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11896   }
11897 
11898   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11899     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11900                                  VectorType::GenericVector);
11901   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11902     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11903                                  VectorType::GenericVector);
11904   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11905     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11906                                  VectorType::GenericVector);
11907   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11908     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11909                                  VectorType::GenericVector);
11910   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11911          "Unhandled vector element size in vector compare");
11912   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11913                                VectorType::GenericVector);
11914 }
11915 
11916 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11917 /// operates on extended vector types.  Instead of producing an IntTy result,
11918 /// like a scalar comparison, a vector comparison produces a vector of integer
11919 /// types.
11920 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11921                                           SourceLocation Loc,
11922                                           BinaryOperatorKind Opc) {
11923   if (Opc == BO_Cmp) {
11924     Diag(Loc, diag::err_three_way_vector_comparison);
11925     return QualType();
11926   }
11927 
11928   // Check to make sure we're operating on vectors of the same type and width,
11929   // Allowing one side to be a scalar of element type.
11930   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11931                               /*AllowBothBool*/true,
11932                               /*AllowBoolConversions*/getLangOpts().ZVector);
11933   if (vType.isNull())
11934     return vType;
11935 
11936   QualType LHSType = LHS.get()->getType();
11937 
11938   // If AltiVec, the comparison results in a numeric type, i.e.
11939   // bool for C++, int for C
11940   if (getLangOpts().AltiVec &&
11941       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11942     return Context.getLogicalOperationType();
11943 
11944   // For non-floating point types, check for self-comparisons of the form
11945   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11946   // often indicate logic errors in the program.
11947   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11948 
11949   // Check for comparisons of floating point operands using != and ==.
11950   if (BinaryOperator::isEqualityOp(Opc) &&
11951       LHSType->hasFloatingRepresentation()) {
11952     assert(RHS.get()->getType()->hasFloatingRepresentation());
11953     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11954   }
11955 
11956   // Return a signed type for the vector.
11957   return GetSignedVectorType(vType);
11958 }
11959 
11960 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11961                                     const ExprResult &XorRHS,
11962                                     const SourceLocation Loc) {
11963   // Do not diagnose macros.
11964   if (Loc.isMacroID())
11965     return;
11966 
11967   bool Negative = false;
11968   bool ExplicitPlus = false;
11969   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11970   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11971 
11972   if (!LHSInt)
11973     return;
11974   if (!RHSInt) {
11975     // Check negative literals.
11976     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11977       UnaryOperatorKind Opc = UO->getOpcode();
11978       if (Opc != UO_Minus && Opc != UO_Plus)
11979         return;
11980       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11981       if (!RHSInt)
11982         return;
11983       Negative = (Opc == UO_Minus);
11984       ExplicitPlus = !Negative;
11985     } else {
11986       return;
11987     }
11988   }
11989 
11990   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11991   llvm::APInt RightSideValue = RHSInt->getValue();
11992   if (LeftSideValue != 2 && LeftSideValue != 10)
11993     return;
11994 
11995   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11996     return;
11997 
11998   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11999       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12000   llvm::StringRef ExprStr =
12001       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12002 
12003   CharSourceRange XorRange =
12004       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12005   llvm::StringRef XorStr =
12006       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12007   // Do not diagnose if xor keyword/macro is used.
12008   if (XorStr == "xor")
12009     return;
12010 
12011   std::string LHSStr = std::string(Lexer::getSourceText(
12012       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12013       S.getSourceManager(), S.getLangOpts()));
12014   std::string RHSStr = std::string(Lexer::getSourceText(
12015       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12016       S.getSourceManager(), S.getLangOpts()));
12017 
12018   if (Negative) {
12019     RightSideValue = -RightSideValue;
12020     RHSStr = "-" + RHSStr;
12021   } else if (ExplicitPlus) {
12022     RHSStr = "+" + RHSStr;
12023   }
12024 
12025   StringRef LHSStrRef = LHSStr;
12026   StringRef RHSStrRef = RHSStr;
12027   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12028   // literals.
12029   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12030       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12031       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12032       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12033       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12034       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12035       LHSStrRef.find('\'') != StringRef::npos ||
12036       RHSStrRef.find('\'') != StringRef::npos)
12037     return;
12038 
12039   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12040   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12041   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12042   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12043     std::string SuggestedExpr = "1 << " + RHSStr;
12044     bool Overflow = false;
12045     llvm::APInt One = (LeftSideValue - 1);
12046     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12047     if (Overflow) {
12048       if (RightSideIntValue < 64)
12049         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12050             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12051             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12052       else if (RightSideIntValue == 64)
12053         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12054       else
12055         return;
12056     } else {
12057       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12058           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12059           << PowValue.toString(10, true)
12060           << FixItHint::CreateReplacement(
12061                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12062     }
12063 
12064     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12065   } else if (LeftSideValue == 10) {
12066     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12067     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12068         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12069         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12070     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12071   }
12072 }
12073 
12074 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12075                                           SourceLocation Loc) {
12076   // Ensure that either both operands are of the same vector type, or
12077   // one operand is of a vector type and the other is of its element type.
12078   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12079                                        /*AllowBothBool*/true,
12080                                        /*AllowBoolConversions*/false);
12081   if (vType.isNull())
12082     return InvalidOperands(Loc, LHS, RHS);
12083   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12084       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12085     return InvalidOperands(Loc, LHS, RHS);
12086   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12087   //        usage of the logical operators && and || with vectors in C. This
12088   //        check could be notionally dropped.
12089   if (!getLangOpts().CPlusPlus &&
12090       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12091     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12092 
12093   return GetSignedVectorType(LHS.get()->getType());
12094 }
12095 
12096 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12097                                               SourceLocation Loc,
12098                                               bool IsCompAssign) {
12099   if (!IsCompAssign) {
12100     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12101     if (LHS.isInvalid())
12102       return QualType();
12103   }
12104   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12105   if (RHS.isInvalid())
12106     return QualType();
12107 
12108   // For conversion purposes, we ignore any qualifiers.
12109   // For example, "const float" and "float" are equivalent.
12110   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12111   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12112 
12113   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12114   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12115   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12116 
12117   if (Context.hasSameType(LHSType, RHSType))
12118     return LHSType;
12119 
12120   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12121   // case we have to return InvalidOperands.
12122   ExprResult OriginalLHS = LHS;
12123   ExprResult OriginalRHS = RHS;
12124   if (LHSMatType && !RHSMatType) {
12125     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12126     if (!RHS.isInvalid())
12127       return LHSType;
12128 
12129     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12130   }
12131 
12132   if (!LHSMatType && RHSMatType) {
12133     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12134     if (!LHS.isInvalid())
12135       return RHSType;
12136     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12137   }
12138 
12139   return InvalidOperands(Loc, LHS, RHS);
12140 }
12141 
12142 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12143                                            SourceLocation Loc,
12144                                            bool IsCompAssign) {
12145   if (!IsCompAssign) {
12146     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12147     if (LHS.isInvalid())
12148       return QualType();
12149   }
12150   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12151   if (RHS.isInvalid())
12152     return QualType();
12153 
12154   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12155   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12156   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12157 
12158   if (LHSMatType && RHSMatType) {
12159     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12160       return InvalidOperands(Loc, LHS, RHS);
12161 
12162     if (!Context.hasSameType(LHSMatType->getElementType(),
12163                              RHSMatType->getElementType()))
12164       return InvalidOperands(Loc, LHS, RHS);
12165 
12166     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12167                                          LHSMatType->getNumRows(),
12168                                          RHSMatType->getNumColumns());
12169   }
12170   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12171 }
12172 
12173 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12174                                            SourceLocation Loc,
12175                                            BinaryOperatorKind Opc) {
12176   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12177 
12178   bool IsCompAssign =
12179       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12180 
12181   if (LHS.get()->getType()->isVectorType() ||
12182       RHS.get()->getType()->isVectorType()) {
12183     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12184         RHS.get()->getType()->hasIntegerRepresentation())
12185       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12186                         /*AllowBothBool*/true,
12187                         /*AllowBoolConversions*/getLangOpts().ZVector);
12188     return InvalidOperands(Loc, LHS, RHS);
12189   }
12190 
12191   if (Opc == BO_And)
12192     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12193 
12194   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12195       RHS.get()->getType()->hasFloatingRepresentation())
12196     return InvalidOperands(Loc, LHS, RHS);
12197 
12198   ExprResult LHSResult = LHS, RHSResult = RHS;
12199   QualType compType = UsualArithmeticConversions(
12200       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12201   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12202     return QualType();
12203   LHS = LHSResult.get();
12204   RHS = RHSResult.get();
12205 
12206   if (Opc == BO_Xor)
12207     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12208 
12209   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12210     return compType;
12211   return InvalidOperands(Loc, LHS, RHS);
12212 }
12213 
12214 // C99 6.5.[13,14]
12215 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12216                                            SourceLocation Loc,
12217                                            BinaryOperatorKind Opc) {
12218   // Check vector operands differently.
12219   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12220     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12221 
12222   bool EnumConstantInBoolContext = false;
12223   for (const ExprResult &HS : {LHS, RHS}) {
12224     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12225       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12226       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12227         EnumConstantInBoolContext = true;
12228     }
12229   }
12230 
12231   if (EnumConstantInBoolContext)
12232     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12233 
12234   // Diagnose cases where the user write a logical and/or but probably meant a
12235   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12236   // is a constant.
12237   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12238       !LHS.get()->getType()->isBooleanType() &&
12239       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12240       // Don't warn in macros or template instantiations.
12241       !Loc.isMacroID() && !inTemplateInstantiation()) {
12242     // If the RHS can be constant folded, and if it constant folds to something
12243     // that isn't 0 or 1 (which indicate a potential logical operation that
12244     // happened to fold to true/false) then warn.
12245     // Parens on the RHS are ignored.
12246     Expr::EvalResult EVResult;
12247     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12248       llvm::APSInt Result = EVResult.Val.getInt();
12249       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12250            !RHS.get()->getExprLoc().isMacroID()) ||
12251           (Result != 0 && Result != 1)) {
12252         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12253           << RHS.get()->getSourceRange()
12254           << (Opc == BO_LAnd ? "&&" : "||");
12255         // Suggest replacing the logical operator with the bitwise version
12256         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12257             << (Opc == BO_LAnd ? "&" : "|")
12258             << FixItHint::CreateReplacement(SourceRange(
12259                                                  Loc, getLocForEndOfToken(Loc)),
12260                                             Opc == BO_LAnd ? "&" : "|");
12261         if (Opc == BO_LAnd)
12262           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12263           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12264               << FixItHint::CreateRemoval(
12265                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12266                                  RHS.get()->getEndLoc()));
12267       }
12268     }
12269   }
12270 
12271   if (!Context.getLangOpts().CPlusPlus) {
12272     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12273     // not operate on the built-in scalar and vector float types.
12274     if (Context.getLangOpts().OpenCL &&
12275         Context.getLangOpts().OpenCLVersion < 120) {
12276       if (LHS.get()->getType()->isFloatingType() ||
12277           RHS.get()->getType()->isFloatingType())
12278         return InvalidOperands(Loc, LHS, RHS);
12279     }
12280 
12281     LHS = UsualUnaryConversions(LHS.get());
12282     if (LHS.isInvalid())
12283       return QualType();
12284 
12285     RHS = UsualUnaryConversions(RHS.get());
12286     if (RHS.isInvalid())
12287       return QualType();
12288 
12289     if (!LHS.get()->getType()->isScalarType() ||
12290         !RHS.get()->getType()->isScalarType())
12291       return InvalidOperands(Loc, LHS, RHS);
12292 
12293     return Context.IntTy;
12294   }
12295 
12296   // The following is safe because we only use this method for
12297   // non-overloadable operands.
12298 
12299   // C++ [expr.log.and]p1
12300   // C++ [expr.log.or]p1
12301   // The operands are both contextually converted to type bool.
12302   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12303   if (LHSRes.isInvalid())
12304     return InvalidOperands(Loc, LHS, RHS);
12305   LHS = LHSRes;
12306 
12307   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12308   if (RHSRes.isInvalid())
12309     return InvalidOperands(Loc, LHS, RHS);
12310   RHS = RHSRes;
12311 
12312   // C++ [expr.log.and]p2
12313   // C++ [expr.log.or]p2
12314   // The result is a bool.
12315   return Context.BoolTy;
12316 }
12317 
12318 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12319   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12320   if (!ME) return false;
12321   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12322   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12323       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12324   if (!Base) return false;
12325   return Base->getMethodDecl() != nullptr;
12326 }
12327 
12328 /// Is the given expression (which must be 'const') a reference to a
12329 /// variable which was originally non-const, but which has become
12330 /// 'const' due to being captured within a block?
12331 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12332 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12333   assert(E->isLValue() && E->getType().isConstQualified());
12334   E = E->IgnoreParens();
12335 
12336   // Must be a reference to a declaration from an enclosing scope.
12337   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12338   if (!DRE) return NCCK_None;
12339   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12340 
12341   // The declaration must be a variable which is not declared 'const'.
12342   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12343   if (!var) return NCCK_None;
12344   if (var->getType().isConstQualified()) return NCCK_None;
12345   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12346 
12347   // Decide whether the first capture was for a block or a lambda.
12348   DeclContext *DC = S.CurContext, *Prev = nullptr;
12349   // Decide whether the first capture was for a block or a lambda.
12350   while (DC) {
12351     // For init-capture, it is possible that the variable belongs to the
12352     // template pattern of the current context.
12353     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12354       if (var->isInitCapture() &&
12355           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12356         break;
12357     if (DC == var->getDeclContext())
12358       break;
12359     Prev = DC;
12360     DC = DC->getParent();
12361   }
12362   // Unless we have an init-capture, we've gone one step too far.
12363   if (!var->isInitCapture())
12364     DC = Prev;
12365   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12366 }
12367 
12368 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12369   Ty = Ty.getNonReferenceType();
12370   if (IsDereference && Ty->isPointerType())
12371     Ty = Ty->getPointeeType();
12372   return !Ty.isConstQualified();
12373 }
12374 
12375 // Update err_typecheck_assign_const and note_typecheck_assign_const
12376 // when this enum is changed.
12377 enum {
12378   ConstFunction,
12379   ConstVariable,
12380   ConstMember,
12381   ConstMethod,
12382   NestedConstMember,
12383   ConstUnknown,  // Keep as last element
12384 };
12385 
12386 /// Emit the "read-only variable not assignable" error and print notes to give
12387 /// more information about why the variable is not assignable, such as pointing
12388 /// to the declaration of a const variable, showing that a method is const, or
12389 /// that the function is returning a const reference.
12390 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12391                                     SourceLocation Loc) {
12392   SourceRange ExprRange = E->getSourceRange();
12393 
12394   // Only emit one error on the first const found.  All other consts will emit
12395   // a note to the error.
12396   bool DiagnosticEmitted = false;
12397 
12398   // Track if the current expression is the result of a dereference, and if the
12399   // next checked expression is the result of a dereference.
12400   bool IsDereference = false;
12401   bool NextIsDereference = false;
12402 
12403   // Loop to process MemberExpr chains.
12404   while (true) {
12405     IsDereference = NextIsDereference;
12406 
12407     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12408     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12409       NextIsDereference = ME->isArrow();
12410       const ValueDecl *VD = ME->getMemberDecl();
12411       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12412         // Mutable fields can be modified even if the class is const.
12413         if (Field->isMutable()) {
12414           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12415           break;
12416         }
12417 
12418         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12419           if (!DiagnosticEmitted) {
12420             S.Diag(Loc, diag::err_typecheck_assign_const)
12421                 << ExprRange << ConstMember << false /*static*/ << Field
12422                 << Field->getType();
12423             DiagnosticEmitted = true;
12424           }
12425           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12426               << ConstMember << false /*static*/ << Field << Field->getType()
12427               << Field->getSourceRange();
12428         }
12429         E = ME->getBase();
12430         continue;
12431       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12432         if (VDecl->getType().isConstQualified()) {
12433           if (!DiagnosticEmitted) {
12434             S.Diag(Loc, diag::err_typecheck_assign_const)
12435                 << ExprRange << ConstMember << true /*static*/ << VDecl
12436                 << VDecl->getType();
12437             DiagnosticEmitted = true;
12438           }
12439           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12440               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12441               << VDecl->getSourceRange();
12442         }
12443         // Static fields do not inherit constness from parents.
12444         break;
12445       }
12446       break; // End MemberExpr
12447     } else if (const ArraySubscriptExpr *ASE =
12448                    dyn_cast<ArraySubscriptExpr>(E)) {
12449       E = ASE->getBase()->IgnoreParenImpCasts();
12450       continue;
12451     } else if (const ExtVectorElementExpr *EVE =
12452                    dyn_cast<ExtVectorElementExpr>(E)) {
12453       E = EVE->getBase()->IgnoreParenImpCasts();
12454       continue;
12455     }
12456     break;
12457   }
12458 
12459   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12460     // Function calls
12461     const FunctionDecl *FD = CE->getDirectCallee();
12462     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12463       if (!DiagnosticEmitted) {
12464         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12465                                                       << ConstFunction << FD;
12466         DiagnosticEmitted = true;
12467       }
12468       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12469              diag::note_typecheck_assign_const)
12470           << ConstFunction << FD << FD->getReturnType()
12471           << FD->getReturnTypeSourceRange();
12472     }
12473   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12474     // Point to variable declaration.
12475     if (const ValueDecl *VD = DRE->getDecl()) {
12476       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12477         if (!DiagnosticEmitted) {
12478           S.Diag(Loc, diag::err_typecheck_assign_const)
12479               << ExprRange << ConstVariable << VD << VD->getType();
12480           DiagnosticEmitted = true;
12481         }
12482         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12483             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12484       }
12485     }
12486   } else if (isa<CXXThisExpr>(E)) {
12487     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12488       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12489         if (MD->isConst()) {
12490           if (!DiagnosticEmitted) {
12491             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12492                                                           << ConstMethod << MD;
12493             DiagnosticEmitted = true;
12494           }
12495           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12496               << ConstMethod << MD << MD->getSourceRange();
12497         }
12498       }
12499     }
12500   }
12501 
12502   if (DiagnosticEmitted)
12503     return;
12504 
12505   // Can't determine a more specific message, so display the generic error.
12506   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12507 }
12508 
12509 enum OriginalExprKind {
12510   OEK_Variable,
12511   OEK_Member,
12512   OEK_LValue
12513 };
12514 
12515 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12516                                          const RecordType *Ty,
12517                                          SourceLocation Loc, SourceRange Range,
12518                                          OriginalExprKind OEK,
12519                                          bool &DiagnosticEmitted) {
12520   std::vector<const RecordType *> RecordTypeList;
12521   RecordTypeList.push_back(Ty);
12522   unsigned NextToCheckIndex = 0;
12523   // We walk the record hierarchy breadth-first to ensure that we print
12524   // diagnostics in field nesting order.
12525   while (RecordTypeList.size() > NextToCheckIndex) {
12526     bool IsNested = NextToCheckIndex > 0;
12527     for (const FieldDecl *Field :
12528          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12529       // First, check every field for constness.
12530       QualType FieldTy = Field->getType();
12531       if (FieldTy.isConstQualified()) {
12532         if (!DiagnosticEmitted) {
12533           S.Diag(Loc, diag::err_typecheck_assign_const)
12534               << Range << NestedConstMember << OEK << VD
12535               << IsNested << Field;
12536           DiagnosticEmitted = true;
12537         }
12538         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12539             << NestedConstMember << IsNested << Field
12540             << FieldTy << Field->getSourceRange();
12541       }
12542 
12543       // Then we append it to the list to check next in order.
12544       FieldTy = FieldTy.getCanonicalType();
12545       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12546         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12547           RecordTypeList.push_back(FieldRecTy);
12548       }
12549     }
12550     ++NextToCheckIndex;
12551   }
12552 }
12553 
12554 /// Emit an error for the case where a record we are trying to assign to has a
12555 /// const-qualified field somewhere in its hierarchy.
12556 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12557                                          SourceLocation Loc) {
12558   QualType Ty = E->getType();
12559   assert(Ty->isRecordType() && "lvalue was not record?");
12560   SourceRange Range = E->getSourceRange();
12561   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12562   bool DiagEmitted = false;
12563 
12564   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12565     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12566             Range, OEK_Member, DiagEmitted);
12567   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12568     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12569             Range, OEK_Variable, DiagEmitted);
12570   else
12571     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12572             Range, OEK_LValue, DiagEmitted);
12573   if (!DiagEmitted)
12574     DiagnoseConstAssignment(S, E, Loc);
12575 }
12576 
12577 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12578 /// emit an error and return true.  If so, return false.
12579 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12580   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12581 
12582   S.CheckShadowingDeclModification(E, Loc);
12583 
12584   SourceLocation OrigLoc = Loc;
12585   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12586                                                               &Loc);
12587   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12588     IsLV = Expr::MLV_InvalidMessageExpression;
12589   if (IsLV == Expr::MLV_Valid)
12590     return false;
12591 
12592   unsigned DiagID = 0;
12593   bool NeedType = false;
12594   switch (IsLV) { // C99 6.5.16p2
12595   case Expr::MLV_ConstQualified:
12596     // Use a specialized diagnostic when we're assigning to an object
12597     // from an enclosing function or block.
12598     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12599       if (NCCK == NCCK_Block)
12600         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12601       else
12602         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12603       break;
12604     }
12605 
12606     // In ARC, use some specialized diagnostics for occasions where we
12607     // infer 'const'.  These are always pseudo-strong variables.
12608     if (S.getLangOpts().ObjCAutoRefCount) {
12609       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12610       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12611         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12612 
12613         // Use the normal diagnostic if it's pseudo-__strong but the
12614         // user actually wrote 'const'.
12615         if (var->isARCPseudoStrong() &&
12616             (!var->getTypeSourceInfo() ||
12617              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12618           // There are three pseudo-strong cases:
12619           //  - self
12620           ObjCMethodDecl *method = S.getCurMethodDecl();
12621           if (method && var == method->getSelfDecl()) {
12622             DiagID = method->isClassMethod()
12623               ? diag::err_typecheck_arc_assign_self_class_method
12624               : diag::err_typecheck_arc_assign_self;
12625 
12626           //  - Objective-C externally_retained attribute.
12627           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12628                      isa<ParmVarDecl>(var)) {
12629             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12630 
12631           //  - fast enumeration variables
12632           } else {
12633             DiagID = diag::err_typecheck_arr_assign_enumeration;
12634           }
12635 
12636           SourceRange Assign;
12637           if (Loc != OrigLoc)
12638             Assign = SourceRange(OrigLoc, OrigLoc);
12639           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12640           // We need to preserve the AST regardless, so migration tool
12641           // can do its job.
12642           return false;
12643         }
12644       }
12645     }
12646 
12647     // If none of the special cases above are triggered, then this is a
12648     // simple const assignment.
12649     if (DiagID == 0) {
12650       DiagnoseConstAssignment(S, E, Loc);
12651       return true;
12652     }
12653 
12654     break;
12655   case Expr::MLV_ConstAddrSpace:
12656     DiagnoseConstAssignment(S, E, Loc);
12657     return true;
12658   case Expr::MLV_ConstQualifiedField:
12659     DiagnoseRecursiveConstFields(S, E, Loc);
12660     return true;
12661   case Expr::MLV_ArrayType:
12662   case Expr::MLV_ArrayTemporary:
12663     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12664     NeedType = true;
12665     break;
12666   case Expr::MLV_NotObjectType:
12667     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12668     NeedType = true;
12669     break;
12670   case Expr::MLV_LValueCast:
12671     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12672     break;
12673   case Expr::MLV_Valid:
12674     llvm_unreachable("did not take early return for MLV_Valid");
12675   case Expr::MLV_InvalidExpression:
12676   case Expr::MLV_MemberFunction:
12677   case Expr::MLV_ClassTemporary:
12678     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12679     break;
12680   case Expr::MLV_IncompleteType:
12681   case Expr::MLV_IncompleteVoidType:
12682     return S.RequireCompleteType(Loc, E->getType(),
12683              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12684   case Expr::MLV_DuplicateVectorComponents:
12685     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12686     break;
12687   case Expr::MLV_NoSetterProperty:
12688     llvm_unreachable("readonly properties should be processed differently");
12689   case Expr::MLV_InvalidMessageExpression:
12690     DiagID = diag::err_readonly_message_assignment;
12691     break;
12692   case Expr::MLV_SubObjCPropertySetting:
12693     DiagID = diag::err_no_subobject_property_setting;
12694     break;
12695   }
12696 
12697   SourceRange Assign;
12698   if (Loc != OrigLoc)
12699     Assign = SourceRange(OrigLoc, OrigLoc);
12700   if (NeedType)
12701     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12702   else
12703     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12704   return true;
12705 }
12706 
12707 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12708                                          SourceLocation Loc,
12709                                          Sema &Sema) {
12710   if (Sema.inTemplateInstantiation())
12711     return;
12712   if (Sema.isUnevaluatedContext())
12713     return;
12714   if (Loc.isInvalid() || Loc.isMacroID())
12715     return;
12716   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12717     return;
12718 
12719   // C / C++ fields
12720   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12721   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12722   if (ML && MR) {
12723     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12724       return;
12725     const ValueDecl *LHSDecl =
12726         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12727     const ValueDecl *RHSDecl =
12728         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12729     if (LHSDecl != RHSDecl)
12730       return;
12731     if (LHSDecl->getType().isVolatileQualified())
12732       return;
12733     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12734       if (RefTy->getPointeeType().isVolatileQualified())
12735         return;
12736 
12737     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12738   }
12739 
12740   // Objective-C instance variables
12741   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12742   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12743   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12744     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12745     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12746     if (RL && RR && RL->getDecl() == RR->getDecl())
12747       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12748   }
12749 }
12750 
12751 // C99 6.5.16.1
12752 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12753                                        SourceLocation Loc,
12754                                        QualType CompoundType) {
12755   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12756 
12757   // Verify that LHS is a modifiable lvalue, and emit error if not.
12758   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12759     return QualType();
12760 
12761   QualType LHSType = LHSExpr->getType();
12762   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12763                                              CompoundType;
12764   // OpenCL v1.2 s6.1.1.1 p2:
12765   // The half data type can only be used to declare a pointer to a buffer that
12766   // contains half values
12767   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12768     LHSType->isHalfType()) {
12769     Diag(Loc, diag::err_opencl_half_load_store) << 1
12770         << LHSType.getUnqualifiedType();
12771     return QualType();
12772   }
12773 
12774   AssignConvertType ConvTy;
12775   if (CompoundType.isNull()) {
12776     Expr *RHSCheck = RHS.get();
12777 
12778     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12779 
12780     QualType LHSTy(LHSType);
12781     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12782     if (RHS.isInvalid())
12783       return QualType();
12784     // Special case of NSObject attributes on c-style pointer types.
12785     if (ConvTy == IncompatiblePointer &&
12786         ((Context.isObjCNSObjectType(LHSType) &&
12787           RHSType->isObjCObjectPointerType()) ||
12788          (Context.isObjCNSObjectType(RHSType) &&
12789           LHSType->isObjCObjectPointerType())))
12790       ConvTy = Compatible;
12791 
12792     if (ConvTy == Compatible &&
12793         LHSType->isObjCObjectType())
12794         Diag(Loc, diag::err_objc_object_assignment)
12795           << LHSType;
12796 
12797     // If the RHS is a unary plus or minus, check to see if they = and + are
12798     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12799     // instead of "x += 4".
12800     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12801       RHSCheck = ICE->getSubExpr();
12802     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12803       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12804           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12805           // Only if the two operators are exactly adjacent.
12806           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12807           // And there is a space or other character before the subexpr of the
12808           // unary +/-.  We don't want to warn on "x=-1".
12809           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12810           UO->getSubExpr()->getBeginLoc().isFileID()) {
12811         Diag(Loc, diag::warn_not_compound_assign)
12812           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12813           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12814       }
12815     }
12816 
12817     if (ConvTy == Compatible) {
12818       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12819         // Warn about retain cycles where a block captures the LHS, but
12820         // not if the LHS is a simple variable into which the block is
12821         // being stored...unless that variable can be captured by reference!
12822         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12823         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12824         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12825           checkRetainCycles(LHSExpr, RHS.get());
12826       }
12827 
12828       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12829           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12830         // It is safe to assign a weak reference into a strong variable.
12831         // Although this code can still have problems:
12832         //   id x = self.weakProp;
12833         //   id y = self.weakProp;
12834         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12835         // paths through the function. This should be revisited if
12836         // -Wrepeated-use-of-weak is made flow-sensitive.
12837         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12838         // variable, which will be valid for the current autorelease scope.
12839         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12840                              RHS.get()->getBeginLoc()))
12841           getCurFunction()->markSafeWeakUse(RHS.get());
12842 
12843       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12844         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12845       }
12846     }
12847   } else {
12848     // Compound assignment "x += y"
12849     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12850   }
12851 
12852   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12853                                RHS.get(), AA_Assigning))
12854     return QualType();
12855 
12856   CheckForNullPointerDereference(*this, LHSExpr);
12857 
12858   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12859     if (CompoundType.isNull()) {
12860       // C++2a [expr.ass]p5:
12861       //   A simple-assignment whose left operand is of a volatile-qualified
12862       //   type is deprecated unless the assignment is either a discarded-value
12863       //   expression or an unevaluated operand
12864       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12865     } else {
12866       // C++2a [expr.ass]p6:
12867       //   [Compound-assignment] expressions are deprecated if E1 has
12868       //   volatile-qualified type
12869       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12870     }
12871   }
12872 
12873   // C99 6.5.16p3: The type of an assignment expression is the type of the
12874   // left operand unless the left operand has qualified type, in which case
12875   // it is the unqualified version of the type of the left operand.
12876   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12877   // is converted to the type of the assignment expression (above).
12878   // C++ 5.17p1: the type of the assignment expression is that of its left
12879   // operand.
12880   return (getLangOpts().CPlusPlus
12881           ? LHSType : LHSType.getUnqualifiedType());
12882 }
12883 
12884 // Only ignore explicit casts to void.
12885 static bool IgnoreCommaOperand(const Expr *E) {
12886   E = E->IgnoreParens();
12887 
12888   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12889     if (CE->getCastKind() == CK_ToVoid) {
12890       return true;
12891     }
12892 
12893     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12894     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12895         CE->getSubExpr()->getType()->isDependentType()) {
12896       return true;
12897     }
12898   }
12899 
12900   return false;
12901 }
12902 
12903 // Look for instances where it is likely the comma operator is confused with
12904 // another operator.  There is an explicit list of acceptable expressions for
12905 // the left hand side of the comma operator, otherwise emit a warning.
12906 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12907   // No warnings in macros
12908   if (Loc.isMacroID())
12909     return;
12910 
12911   // Don't warn in template instantiations.
12912   if (inTemplateInstantiation())
12913     return;
12914 
12915   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12916   // instead, skip more than needed, then call back into here with the
12917   // CommaVisitor in SemaStmt.cpp.
12918   // The listed locations are the initialization and increment portions
12919   // of a for loop.  The additional checks are on the condition of
12920   // if statements, do/while loops, and for loops.
12921   // Differences in scope flags for C89 mode requires the extra logic.
12922   const unsigned ForIncrementFlags =
12923       getLangOpts().C99 || getLangOpts().CPlusPlus
12924           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12925           : Scope::ContinueScope | Scope::BreakScope;
12926   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12927   const unsigned ScopeFlags = getCurScope()->getFlags();
12928   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12929       (ScopeFlags & ForInitFlags) == ForInitFlags)
12930     return;
12931 
12932   // If there are multiple comma operators used together, get the RHS of the
12933   // of the comma operator as the LHS.
12934   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12935     if (BO->getOpcode() != BO_Comma)
12936       break;
12937     LHS = BO->getRHS();
12938   }
12939 
12940   // Only allow some expressions on LHS to not warn.
12941   if (IgnoreCommaOperand(LHS))
12942     return;
12943 
12944   Diag(Loc, diag::warn_comma_operator);
12945   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12946       << LHS->getSourceRange()
12947       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12948                                     LangOpts.CPlusPlus ? "static_cast<void>("
12949                                                        : "(void)(")
12950       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12951                                     ")");
12952 }
12953 
12954 // C99 6.5.17
12955 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12956                                    SourceLocation Loc) {
12957   LHS = S.CheckPlaceholderExpr(LHS.get());
12958   RHS = S.CheckPlaceholderExpr(RHS.get());
12959   if (LHS.isInvalid() || RHS.isInvalid())
12960     return QualType();
12961 
12962   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12963   // operands, but not unary promotions.
12964   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12965 
12966   // So we treat the LHS as a ignored value, and in C++ we allow the
12967   // containing site to determine what should be done with the RHS.
12968   LHS = S.IgnoredValueConversions(LHS.get());
12969   if (LHS.isInvalid())
12970     return QualType();
12971 
12972   S.DiagnoseUnusedExprResult(LHS.get());
12973 
12974   if (!S.getLangOpts().CPlusPlus) {
12975     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12976     if (RHS.isInvalid())
12977       return QualType();
12978     if (!RHS.get()->getType()->isVoidType())
12979       S.RequireCompleteType(Loc, RHS.get()->getType(),
12980                             diag::err_incomplete_type);
12981   }
12982 
12983   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12984     S.DiagnoseCommaOperator(LHS.get(), Loc);
12985 
12986   return RHS.get()->getType();
12987 }
12988 
12989 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12990 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12991 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12992                                                ExprValueKind &VK,
12993                                                ExprObjectKind &OK,
12994                                                SourceLocation OpLoc,
12995                                                bool IsInc, bool IsPrefix) {
12996   if (Op->isTypeDependent())
12997     return S.Context.DependentTy;
12998 
12999   QualType ResType = Op->getType();
13000   // Atomic types can be used for increment / decrement where the non-atomic
13001   // versions can, so ignore the _Atomic() specifier for the purpose of
13002   // checking.
13003   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13004     ResType = ResAtomicType->getValueType();
13005 
13006   assert(!ResType.isNull() && "no type for increment/decrement expression");
13007 
13008   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13009     // Decrement of bool is not allowed.
13010     if (!IsInc) {
13011       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13012       return QualType();
13013     }
13014     // Increment of bool sets it to true, but is deprecated.
13015     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13016                                               : diag::warn_increment_bool)
13017       << Op->getSourceRange();
13018   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13019     // Error on enum increments and decrements in C++ mode
13020     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13021     return QualType();
13022   } else if (ResType->isRealType()) {
13023     // OK!
13024   } else if (ResType->isPointerType()) {
13025     // C99 6.5.2.4p2, 6.5.6p2
13026     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13027       return QualType();
13028   } else if (ResType->isObjCObjectPointerType()) {
13029     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13030     // Otherwise, we just need a complete type.
13031     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13032         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13033       return QualType();
13034   } else if (ResType->isAnyComplexType()) {
13035     // C99 does not support ++/-- on complex types, we allow as an extension.
13036     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13037       << ResType << Op->getSourceRange();
13038   } else if (ResType->isPlaceholderType()) {
13039     ExprResult PR = S.CheckPlaceholderExpr(Op);
13040     if (PR.isInvalid()) return QualType();
13041     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13042                                           IsInc, IsPrefix);
13043   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13044     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13045   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13046              (ResType->castAs<VectorType>()->getVectorKind() !=
13047               VectorType::AltiVecBool)) {
13048     // The z vector extensions allow ++ and -- for non-bool vectors.
13049   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13050             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13051     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13052   } else {
13053     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13054       << ResType << int(IsInc) << Op->getSourceRange();
13055     return QualType();
13056   }
13057   // At this point, we know we have a real, complex or pointer type.
13058   // Now make sure the operand is a modifiable lvalue.
13059   if (CheckForModifiableLvalue(Op, OpLoc, S))
13060     return QualType();
13061   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13062     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13063     //   An operand with volatile-qualified type is deprecated
13064     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13065         << IsInc << ResType;
13066   }
13067   // In C++, a prefix increment is the same type as the operand. Otherwise
13068   // (in C or with postfix), the increment is the unqualified type of the
13069   // operand.
13070   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13071     VK = VK_LValue;
13072     OK = Op->getObjectKind();
13073     return ResType;
13074   } else {
13075     VK = VK_RValue;
13076     return ResType.getUnqualifiedType();
13077   }
13078 }
13079 
13080 
13081 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13082 /// This routine allows us to typecheck complex/recursive expressions
13083 /// where the declaration is needed for type checking. We only need to
13084 /// handle cases when the expression references a function designator
13085 /// or is an lvalue. Here are some examples:
13086 ///  - &(x) => x
13087 ///  - &*****f => f for f a function designator.
13088 ///  - &s.xx => s
13089 ///  - &s.zz[1].yy -> s, if zz is an array
13090 ///  - *(x + 1) -> x, if x is an array
13091 ///  - &"123"[2] -> 0
13092 ///  - & __real__ x -> x
13093 ///
13094 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13095 /// members.
13096 static ValueDecl *getPrimaryDecl(Expr *E) {
13097   switch (E->getStmtClass()) {
13098   case Stmt::DeclRefExprClass:
13099     return cast<DeclRefExpr>(E)->getDecl();
13100   case Stmt::MemberExprClass:
13101     // If this is an arrow operator, the address is an offset from
13102     // the base's value, so the object the base refers to is
13103     // irrelevant.
13104     if (cast<MemberExpr>(E)->isArrow())
13105       return nullptr;
13106     // Otherwise, the expression refers to a part of the base
13107     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13108   case Stmt::ArraySubscriptExprClass: {
13109     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13110     // promotion of register arrays earlier.
13111     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13112     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13113       if (ICE->getSubExpr()->getType()->isArrayType())
13114         return getPrimaryDecl(ICE->getSubExpr());
13115     }
13116     return nullptr;
13117   }
13118   case Stmt::UnaryOperatorClass: {
13119     UnaryOperator *UO = cast<UnaryOperator>(E);
13120 
13121     switch(UO->getOpcode()) {
13122     case UO_Real:
13123     case UO_Imag:
13124     case UO_Extension:
13125       return getPrimaryDecl(UO->getSubExpr());
13126     default:
13127       return nullptr;
13128     }
13129   }
13130   case Stmt::ParenExprClass:
13131     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13132   case Stmt::ImplicitCastExprClass:
13133     // If the result of an implicit cast is an l-value, we care about
13134     // the sub-expression; otherwise, the result here doesn't matter.
13135     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13136   case Stmt::CXXUuidofExprClass:
13137     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13138   default:
13139     return nullptr;
13140   }
13141 }
13142 
13143 namespace {
13144 enum {
13145   AO_Bit_Field = 0,
13146   AO_Vector_Element = 1,
13147   AO_Property_Expansion = 2,
13148   AO_Register_Variable = 3,
13149   AO_Matrix_Element = 4,
13150   AO_No_Error = 5
13151 };
13152 }
13153 /// Diagnose invalid operand for address of operations.
13154 ///
13155 /// \param Type The type of operand which cannot have its address taken.
13156 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13157                                          Expr *E, unsigned Type) {
13158   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13159 }
13160 
13161 /// CheckAddressOfOperand - The operand of & must be either a function
13162 /// designator or an lvalue designating an object. If it is an lvalue, the
13163 /// object cannot be declared with storage class register or be a bit field.
13164 /// Note: The usual conversions are *not* applied to the operand of the &
13165 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13166 /// In C++, the operand might be an overloaded function name, in which case
13167 /// we allow the '&' but retain the overloaded-function type.
13168 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13169   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13170     if (PTy->getKind() == BuiltinType::Overload) {
13171       Expr *E = OrigOp.get()->IgnoreParens();
13172       if (!isa<OverloadExpr>(E)) {
13173         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13174         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13175           << OrigOp.get()->getSourceRange();
13176         return QualType();
13177       }
13178 
13179       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13180       if (isa<UnresolvedMemberExpr>(Ovl))
13181         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13182           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13183             << OrigOp.get()->getSourceRange();
13184           return QualType();
13185         }
13186 
13187       return Context.OverloadTy;
13188     }
13189 
13190     if (PTy->getKind() == BuiltinType::UnknownAny)
13191       return Context.UnknownAnyTy;
13192 
13193     if (PTy->getKind() == BuiltinType::BoundMember) {
13194       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13195         << OrigOp.get()->getSourceRange();
13196       return QualType();
13197     }
13198 
13199     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13200     if (OrigOp.isInvalid()) return QualType();
13201   }
13202 
13203   if (OrigOp.get()->isTypeDependent())
13204     return Context.DependentTy;
13205 
13206   assert(!OrigOp.get()->getType()->isPlaceholderType());
13207 
13208   // Make sure to ignore parentheses in subsequent checks
13209   Expr *op = OrigOp.get()->IgnoreParens();
13210 
13211   // In OpenCL captures for blocks called as lambda functions
13212   // are located in the private address space. Blocks used in
13213   // enqueue_kernel can be located in a different address space
13214   // depending on a vendor implementation. Thus preventing
13215   // taking an address of the capture to avoid invalid AS casts.
13216   if (LangOpts.OpenCL) {
13217     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13218     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13219       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13220       return QualType();
13221     }
13222   }
13223 
13224   if (getLangOpts().C99) {
13225     // Implement C99-only parts of addressof rules.
13226     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13227       if (uOp->getOpcode() == UO_Deref)
13228         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13229         // (assuming the deref expression is valid).
13230         return uOp->getSubExpr()->getType();
13231     }
13232     // Technically, there should be a check for array subscript
13233     // expressions here, but the result of one is always an lvalue anyway.
13234   }
13235   ValueDecl *dcl = getPrimaryDecl(op);
13236 
13237   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13238     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13239                                            op->getBeginLoc()))
13240       return QualType();
13241 
13242   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13243   unsigned AddressOfError = AO_No_Error;
13244 
13245   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13246     bool sfinae = (bool)isSFINAEContext();
13247     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13248                                   : diag::ext_typecheck_addrof_temporary)
13249       << op->getType() << op->getSourceRange();
13250     if (sfinae)
13251       return QualType();
13252     // Materialize the temporary as an lvalue so that we can take its address.
13253     OrigOp = op =
13254         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13255   } else if (isa<ObjCSelectorExpr>(op)) {
13256     return Context.getPointerType(op->getType());
13257   } else if (lval == Expr::LV_MemberFunction) {
13258     // If it's an instance method, make a member pointer.
13259     // The expression must have exactly the form &A::foo.
13260 
13261     // If the underlying expression isn't a decl ref, give up.
13262     if (!isa<DeclRefExpr>(op)) {
13263       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13264         << OrigOp.get()->getSourceRange();
13265       return QualType();
13266     }
13267     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13268     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13269 
13270     // The id-expression was parenthesized.
13271     if (OrigOp.get() != DRE) {
13272       Diag(OpLoc, diag::err_parens_pointer_member_function)
13273         << OrigOp.get()->getSourceRange();
13274 
13275     // The method was named without a qualifier.
13276     } else if (!DRE->getQualifier()) {
13277       if (MD->getParent()->getName().empty())
13278         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13279           << op->getSourceRange();
13280       else {
13281         SmallString<32> Str;
13282         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13283         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13284           << op->getSourceRange()
13285           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13286       }
13287     }
13288 
13289     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13290     if (isa<CXXDestructorDecl>(MD))
13291       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13292 
13293     QualType MPTy = Context.getMemberPointerType(
13294         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13295     // Under the MS ABI, lock down the inheritance model now.
13296     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13297       (void)isCompleteType(OpLoc, MPTy);
13298     return MPTy;
13299   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13300     // C99 6.5.3.2p1
13301     // The operand must be either an l-value or a function designator
13302     if (!op->getType()->isFunctionType()) {
13303       // Use a special diagnostic for loads from property references.
13304       if (isa<PseudoObjectExpr>(op)) {
13305         AddressOfError = AO_Property_Expansion;
13306       } else {
13307         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13308           << op->getType() << op->getSourceRange();
13309         return QualType();
13310       }
13311     }
13312   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13313     // The operand cannot be a bit-field
13314     AddressOfError = AO_Bit_Field;
13315   } else if (op->getObjectKind() == OK_VectorComponent) {
13316     // The operand cannot be an element of a vector
13317     AddressOfError = AO_Vector_Element;
13318   } else if (op->getObjectKind() == OK_MatrixComponent) {
13319     // The operand cannot be an element of a matrix.
13320     AddressOfError = AO_Matrix_Element;
13321   } else if (dcl) { // C99 6.5.3.2p1
13322     // We have an lvalue with a decl. Make sure the decl is not declared
13323     // with the register storage-class specifier.
13324     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13325       // in C++ it is not error to take address of a register
13326       // variable (c++03 7.1.1P3)
13327       if (vd->getStorageClass() == SC_Register &&
13328           !getLangOpts().CPlusPlus) {
13329         AddressOfError = AO_Register_Variable;
13330       }
13331     } else if (isa<MSPropertyDecl>(dcl)) {
13332       AddressOfError = AO_Property_Expansion;
13333     } else if (isa<FunctionTemplateDecl>(dcl)) {
13334       return Context.OverloadTy;
13335     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13336       // Okay: we can take the address of a field.
13337       // Could be a pointer to member, though, if there is an explicit
13338       // scope qualifier for the class.
13339       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13340         DeclContext *Ctx = dcl->getDeclContext();
13341         if (Ctx && Ctx->isRecord()) {
13342           if (dcl->getType()->isReferenceType()) {
13343             Diag(OpLoc,
13344                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13345               << dcl->getDeclName() << dcl->getType();
13346             return QualType();
13347           }
13348 
13349           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13350             Ctx = Ctx->getParent();
13351 
13352           QualType MPTy = Context.getMemberPointerType(
13353               op->getType(),
13354               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13355           // Under the MS ABI, lock down the inheritance model now.
13356           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13357             (void)isCompleteType(OpLoc, MPTy);
13358           return MPTy;
13359         }
13360       }
13361     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13362                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13363       llvm_unreachable("Unknown/unexpected decl type");
13364   }
13365 
13366   if (AddressOfError != AO_No_Error) {
13367     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13368     return QualType();
13369   }
13370 
13371   if (lval == Expr::LV_IncompleteVoidType) {
13372     // Taking the address of a void variable is technically illegal, but we
13373     // allow it in cases which are otherwise valid.
13374     // Example: "extern void x; void* y = &x;".
13375     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13376   }
13377 
13378   // If the operand has type "type", the result has type "pointer to type".
13379   if (op->getType()->isObjCObjectType())
13380     return Context.getObjCObjectPointerType(op->getType());
13381 
13382   CheckAddressOfPackedMember(op);
13383 
13384   return Context.getPointerType(op->getType());
13385 }
13386 
13387 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13388   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13389   if (!DRE)
13390     return;
13391   const Decl *D = DRE->getDecl();
13392   if (!D)
13393     return;
13394   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13395   if (!Param)
13396     return;
13397   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13398     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13399       return;
13400   if (FunctionScopeInfo *FD = S.getCurFunction())
13401     if (!FD->ModifiedNonNullParams.count(Param))
13402       FD->ModifiedNonNullParams.insert(Param);
13403 }
13404 
13405 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13406 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13407                                         SourceLocation OpLoc) {
13408   if (Op->isTypeDependent())
13409     return S.Context.DependentTy;
13410 
13411   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13412   if (ConvResult.isInvalid())
13413     return QualType();
13414   Op = ConvResult.get();
13415   QualType OpTy = Op->getType();
13416   QualType Result;
13417 
13418   if (isa<CXXReinterpretCastExpr>(Op)) {
13419     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13420     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13421                                      Op->getSourceRange());
13422   }
13423 
13424   if (const PointerType *PT = OpTy->getAs<PointerType>())
13425   {
13426     Result = PT->getPointeeType();
13427   }
13428   else if (const ObjCObjectPointerType *OPT =
13429              OpTy->getAs<ObjCObjectPointerType>())
13430     Result = OPT->getPointeeType();
13431   else {
13432     ExprResult PR = S.CheckPlaceholderExpr(Op);
13433     if (PR.isInvalid()) return QualType();
13434     if (PR.get() != Op)
13435       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13436   }
13437 
13438   if (Result.isNull()) {
13439     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13440       << OpTy << Op->getSourceRange();
13441     return QualType();
13442   }
13443 
13444   // Note that per both C89 and C99, indirection is always legal, even if Result
13445   // is an incomplete type or void.  It would be possible to warn about
13446   // dereferencing a void pointer, but it's completely well-defined, and such a
13447   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13448   // for pointers to 'void' but is fine for any other pointer type:
13449   //
13450   // C++ [expr.unary.op]p1:
13451   //   [...] the expression to which [the unary * operator] is applied shall
13452   //   be a pointer to an object type, or a pointer to a function type
13453   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13454     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13455       << OpTy << Op->getSourceRange();
13456 
13457   // Dereferences are usually l-values...
13458   VK = VK_LValue;
13459 
13460   // ...except that certain expressions are never l-values in C.
13461   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13462     VK = VK_RValue;
13463 
13464   return Result;
13465 }
13466 
13467 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13468   BinaryOperatorKind Opc;
13469   switch (Kind) {
13470   default: llvm_unreachable("Unknown binop!");
13471   case tok::periodstar:           Opc = BO_PtrMemD; break;
13472   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13473   case tok::star:                 Opc = BO_Mul; break;
13474   case tok::slash:                Opc = BO_Div; break;
13475   case tok::percent:              Opc = BO_Rem; break;
13476   case tok::plus:                 Opc = BO_Add; break;
13477   case tok::minus:                Opc = BO_Sub; break;
13478   case tok::lessless:             Opc = BO_Shl; break;
13479   case tok::greatergreater:       Opc = BO_Shr; break;
13480   case tok::lessequal:            Opc = BO_LE; break;
13481   case tok::less:                 Opc = BO_LT; break;
13482   case tok::greaterequal:         Opc = BO_GE; break;
13483   case tok::greater:              Opc = BO_GT; break;
13484   case tok::exclaimequal:         Opc = BO_NE; break;
13485   case tok::equalequal:           Opc = BO_EQ; break;
13486   case tok::spaceship:            Opc = BO_Cmp; break;
13487   case tok::amp:                  Opc = BO_And; break;
13488   case tok::caret:                Opc = BO_Xor; break;
13489   case tok::pipe:                 Opc = BO_Or; break;
13490   case tok::ampamp:               Opc = BO_LAnd; break;
13491   case tok::pipepipe:             Opc = BO_LOr; break;
13492   case tok::equal:                Opc = BO_Assign; break;
13493   case tok::starequal:            Opc = BO_MulAssign; break;
13494   case tok::slashequal:           Opc = BO_DivAssign; break;
13495   case tok::percentequal:         Opc = BO_RemAssign; break;
13496   case tok::plusequal:            Opc = BO_AddAssign; break;
13497   case tok::minusequal:           Opc = BO_SubAssign; break;
13498   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13499   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13500   case tok::ampequal:             Opc = BO_AndAssign; break;
13501   case tok::caretequal:           Opc = BO_XorAssign; break;
13502   case tok::pipeequal:            Opc = BO_OrAssign; break;
13503   case tok::comma:                Opc = BO_Comma; break;
13504   }
13505   return Opc;
13506 }
13507 
13508 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13509   tok::TokenKind Kind) {
13510   UnaryOperatorKind Opc;
13511   switch (Kind) {
13512   default: llvm_unreachable("Unknown unary op!");
13513   case tok::plusplus:     Opc = UO_PreInc; break;
13514   case tok::minusminus:   Opc = UO_PreDec; break;
13515   case tok::amp:          Opc = UO_AddrOf; break;
13516   case tok::star:         Opc = UO_Deref; break;
13517   case tok::plus:         Opc = UO_Plus; break;
13518   case tok::minus:        Opc = UO_Minus; break;
13519   case tok::tilde:        Opc = UO_Not; break;
13520   case tok::exclaim:      Opc = UO_LNot; break;
13521   case tok::kw___real:    Opc = UO_Real; break;
13522   case tok::kw___imag:    Opc = UO_Imag; break;
13523   case tok::kw___extension__: Opc = UO_Extension; break;
13524   }
13525   return Opc;
13526 }
13527 
13528 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13529 /// This warning suppressed in the event of macro expansions.
13530 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13531                                    SourceLocation OpLoc, bool IsBuiltin) {
13532   if (S.inTemplateInstantiation())
13533     return;
13534   if (S.isUnevaluatedContext())
13535     return;
13536   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13537     return;
13538   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13539   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13540   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13541   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13542   if (!LHSDeclRef || !RHSDeclRef ||
13543       LHSDeclRef->getLocation().isMacroID() ||
13544       RHSDeclRef->getLocation().isMacroID())
13545     return;
13546   const ValueDecl *LHSDecl =
13547     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13548   const ValueDecl *RHSDecl =
13549     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13550   if (LHSDecl != RHSDecl)
13551     return;
13552   if (LHSDecl->getType().isVolatileQualified())
13553     return;
13554   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13555     if (RefTy->getPointeeType().isVolatileQualified())
13556       return;
13557 
13558   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13559                           : diag::warn_self_assignment_overloaded)
13560       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13561       << RHSExpr->getSourceRange();
13562 }
13563 
13564 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13565 /// is usually indicative of introspection within the Objective-C pointer.
13566 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13567                                           SourceLocation OpLoc) {
13568   if (!S.getLangOpts().ObjC)
13569     return;
13570 
13571   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13572   const Expr *LHS = L.get();
13573   const Expr *RHS = R.get();
13574 
13575   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13576     ObjCPointerExpr = LHS;
13577     OtherExpr = RHS;
13578   }
13579   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13580     ObjCPointerExpr = RHS;
13581     OtherExpr = LHS;
13582   }
13583 
13584   // This warning is deliberately made very specific to reduce false
13585   // positives with logic that uses '&' for hashing.  This logic mainly
13586   // looks for code trying to introspect into tagged pointers, which
13587   // code should generally never do.
13588   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13589     unsigned Diag = diag::warn_objc_pointer_masking;
13590     // Determine if we are introspecting the result of performSelectorXXX.
13591     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13592     // Special case messages to -performSelector and friends, which
13593     // can return non-pointer values boxed in a pointer value.
13594     // Some clients may wish to silence warnings in this subcase.
13595     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13596       Selector S = ME->getSelector();
13597       StringRef SelArg0 = S.getNameForSlot(0);
13598       if (SelArg0.startswith("performSelector"))
13599         Diag = diag::warn_objc_pointer_masking_performSelector;
13600     }
13601 
13602     S.Diag(OpLoc, Diag)
13603       << ObjCPointerExpr->getSourceRange();
13604   }
13605 }
13606 
13607 static NamedDecl *getDeclFromExpr(Expr *E) {
13608   if (!E)
13609     return nullptr;
13610   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13611     return DRE->getDecl();
13612   if (auto *ME = dyn_cast<MemberExpr>(E))
13613     return ME->getMemberDecl();
13614   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13615     return IRE->getDecl();
13616   return nullptr;
13617 }
13618 
13619 // This helper function promotes a binary operator's operands (which are of a
13620 // half vector type) to a vector of floats and then truncates the result to
13621 // a vector of either half or short.
13622 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13623                                       BinaryOperatorKind Opc, QualType ResultTy,
13624                                       ExprValueKind VK, ExprObjectKind OK,
13625                                       bool IsCompAssign, SourceLocation OpLoc,
13626                                       FPOptionsOverride FPFeatures) {
13627   auto &Context = S.getASTContext();
13628   assert((isVector(ResultTy, Context.HalfTy) ||
13629           isVector(ResultTy, Context.ShortTy)) &&
13630          "Result must be a vector of half or short");
13631   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13632          isVector(RHS.get()->getType(), Context.HalfTy) &&
13633          "both operands expected to be a half vector");
13634 
13635   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13636   QualType BinOpResTy = RHS.get()->getType();
13637 
13638   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13639   // change BinOpResTy to a vector of ints.
13640   if (isVector(ResultTy, Context.ShortTy))
13641     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13642 
13643   if (IsCompAssign)
13644     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13645                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13646                                           BinOpResTy, BinOpResTy);
13647 
13648   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13649   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13650                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13651   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13652 }
13653 
13654 static std::pair<ExprResult, ExprResult>
13655 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13656                            Expr *RHSExpr) {
13657   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13658   if (!S.getLangOpts().CPlusPlus) {
13659     // C cannot handle TypoExpr nodes on either side of a binop because it
13660     // doesn't handle dependent types properly, so make sure any TypoExprs have
13661     // been dealt with before checking the operands.
13662     LHS = S.CorrectDelayedTyposInExpr(LHS);
13663     RHS = S.CorrectDelayedTyposInExpr(
13664         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13665         [Opc, LHS](Expr *E) {
13666           if (Opc != BO_Assign)
13667             return ExprResult(E);
13668           // Avoid correcting the RHS to the same Expr as the LHS.
13669           Decl *D = getDeclFromExpr(E);
13670           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13671         });
13672   }
13673   return std::make_pair(LHS, RHS);
13674 }
13675 
13676 /// Returns true if conversion between vectors of halfs and vectors of floats
13677 /// is needed.
13678 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13679                                      Expr *E0, Expr *E1 = nullptr) {
13680   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13681       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13682     return false;
13683 
13684   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13685     QualType Ty = E->IgnoreImplicit()->getType();
13686 
13687     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13688     // to vectors of floats. Although the element type of the vectors is __fp16,
13689     // the vectors shouldn't be treated as storage-only types. See the
13690     // discussion here: https://reviews.llvm.org/rG825235c140e7
13691     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13692       if (VT->getVectorKind() == VectorType::NeonVector)
13693         return false;
13694       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13695     }
13696     return false;
13697   };
13698 
13699   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13700 }
13701 
13702 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13703 /// operator @p Opc at location @c TokLoc. This routine only supports
13704 /// built-in operations; ActOnBinOp handles overloaded operators.
13705 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13706                                     BinaryOperatorKind Opc,
13707                                     Expr *LHSExpr, Expr *RHSExpr) {
13708   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13709     // The syntax only allows initializer lists on the RHS of assignment,
13710     // so we don't need to worry about accepting invalid code for
13711     // non-assignment operators.
13712     // C++11 5.17p9:
13713     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13714     //   of x = {} is x = T().
13715     InitializationKind Kind = InitializationKind::CreateDirectList(
13716         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13717     InitializedEntity Entity =
13718         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13719     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13720     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13721     if (Init.isInvalid())
13722       return Init;
13723     RHSExpr = Init.get();
13724   }
13725 
13726   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13727   QualType ResultTy;     // Result type of the binary operator.
13728   // The following two variables are used for compound assignment operators
13729   QualType CompLHSTy;    // Type of LHS after promotions for computation
13730   QualType CompResultTy; // Type of computation result
13731   ExprValueKind VK = VK_RValue;
13732   ExprObjectKind OK = OK_Ordinary;
13733   bool ConvertHalfVec = false;
13734 
13735   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13736   if (!LHS.isUsable() || !RHS.isUsable())
13737     return ExprError();
13738 
13739   if (getLangOpts().OpenCL) {
13740     QualType LHSTy = LHSExpr->getType();
13741     QualType RHSTy = RHSExpr->getType();
13742     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13743     // the ATOMIC_VAR_INIT macro.
13744     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13745       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13746       if (BO_Assign == Opc)
13747         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13748       else
13749         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13750       return ExprError();
13751     }
13752 
13753     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13754     // only with a builtin functions and therefore should be disallowed here.
13755     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13756         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13757         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13758         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13759       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13760       return ExprError();
13761     }
13762   }
13763 
13764   switch (Opc) {
13765   case BO_Assign:
13766     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13767     if (getLangOpts().CPlusPlus &&
13768         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13769       VK = LHS.get()->getValueKind();
13770       OK = LHS.get()->getObjectKind();
13771     }
13772     if (!ResultTy.isNull()) {
13773       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13774       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13775 
13776       // Avoid copying a block to the heap if the block is assigned to a local
13777       // auto variable that is declared in the same scope as the block. This
13778       // optimization is unsafe if the local variable is declared in an outer
13779       // scope. For example:
13780       //
13781       // BlockTy b;
13782       // {
13783       //   b = ^{...};
13784       // }
13785       // // It is unsafe to invoke the block here if it wasn't copied to the
13786       // // heap.
13787       // b();
13788 
13789       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13790         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13791           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13792             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13793               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13794 
13795       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13796         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13797                               NTCUC_Assignment, NTCUK_Copy);
13798     }
13799     RecordModifiableNonNullParam(*this, LHS.get());
13800     break;
13801   case BO_PtrMemD:
13802   case BO_PtrMemI:
13803     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13804                                             Opc == BO_PtrMemI);
13805     break;
13806   case BO_Mul:
13807   case BO_Div:
13808     ConvertHalfVec = true;
13809     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13810                                            Opc == BO_Div);
13811     break;
13812   case BO_Rem:
13813     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13814     break;
13815   case BO_Add:
13816     ConvertHalfVec = true;
13817     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13818     break;
13819   case BO_Sub:
13820     ConvertHalfVec = true;
13821     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13822     break;
13823   case BO_Shl:
13824   case BO_Shr:
13825     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13826     break;
13827   case BO_LE:
13828   case BO_LT:
13829   case BO_GE:
13830   case BO_GT:
13831     ConvertHalfVec = true;
13832     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13833     break;
13834   case BO_EQ:
13835   case BO_NE:
13836     ConvertHalfVec = true;
13837     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13838     break;
13839   case BO_Cmp:
13840     ConvertHalfVec = true;
13841     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13842     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13843     break;
13844   case BO_And:
13845     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13846     LLVM_FALLTHROUGH;
13847   case BO_Xor:
13848   case BO_Or:
13849     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13850     break;
13851   case BO_LAnd:
13852   case BO_LOr:
13853     ConvertHalfVec = true;
13854     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13855     break;
13856   case BO_MulAssign:
13857   case BO_DivAssign:
13858     ConvertHalfVec = true;
13859     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13860                                                Opc == BO_DivAssign);
13861     CompLHSTy = CompResultTy;
13862     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13863       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13864     break;
13865   case BO_RemAssign:
13866     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13867     CompLHSTy = CompResultTy;
13868     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13869       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13870     break;
13871   case BO_AddAssign:
13872     ConvertHalfVec = true;
13873     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13874     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13875       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13876     break;
13877   case BO_SubAssign:
13878     ConvertHalfVec = true;
13879     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13880     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13881       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13882     break;
13883   case BO_ShlAssign:
13884   case BO_ShrAssign:
13885     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13886     CompLHSTy = CompResultTy;
13887     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13888       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13889     break;
13890   case BO_AndAssign:
13891   case BO_OrAssign: // fallthrough
13892     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13893     LLVM_FALLTHROUGH;
13894   case BO_XorAssign:
13895     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13896     CompLHSTy = CompResultTy;
13897     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13898       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13899     break;
13900   case BO_Comma:
13901     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13902     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13903       VK = RHS.get()->getValueKind();
13904       OK = RHS.get()->getObjectKind();
13905     }
13906     break;
13907   }
13908   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13909     return ExprError();
13910 
13911   // Some of the binary operations require promoting operands of half vector to
13912   // float vectors and truncating the result back to half vector. For now, we do
13913   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13914   // arm64).
13915   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13916          isVector(LHS.get()->getType(), Context.HalfTy) &&
13917          "both sides are half vectors or neither sides are");
13918   ConvertHalfVec =
13919       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13920 
13921   // Check for array bounds violations for both sides of the BinaryOperator
13922   CheckArrayAccess(LHS.get());
13923   CheckArrayAccess(RHS.get());
13924 
13925   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13926     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13927                                                  &Context.Idents.get("object_setClass"),
13928                                                  SourceLocation(), LookupOrdinaryName);
13929     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13930       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13931       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13932           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13933                                         "object_setClass(")
13934           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13935                                           ",")
13936           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13937     }
13938     else
13939       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13940   }
13941   else if (const ObjCIvarRefExpr *OIRE =
13942            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13943     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13944 
13945   // Opc is not a compound assignment if CompResultTy is null.
13946   if (CompResultTy.isNull()) {
13947     if (ConvertHalfVec)
13948       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13949                                  OpLoc, CurFPFeatureOverrides());
13950     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13951                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13952   }
13953 
13954   // Handle compound assignments.
13955   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13956       OK_ObjCProperty) {
13957     VK = VK_LValue;
13958     OK = LHS.get()->getObjectKind();
13959   }
13960 
13961   // The LHS is not converted to the result type for fixed-point compound
13962   // assignment as the common type is computed on demand. Reset the CompLHSTy
13963   // to the LHS type we would have gotten after unary conversions.
13964   if (CompResultTy->isFixedPointType())
13965     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13966 
13967   if (ConvertHalfVec)
13968     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13969                                OpLoc, CurFPFeatureOverrides());
13970 
13971   return CompoundAssignOperator::Create(
13972       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13973       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13974 }
13975 
13976 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13977 /// operators are mixed in a way that suggests that the programmer forgot that
13978 /// comparison operators have higher precedence. The most typical example of
13979 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13980 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13981                                       SourceLocation OpLoc, Expr *LHSExpr,
13982                                       Expr *RHSExpr) {
13983   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13984   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13985 
13986   // Check that one of the sides is a comparison operator and the other isn't.
13987   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13988   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13989   if (isLeftComp == isRightComp)
13990     return;
13991 
13992   // Bitwise operations are sometimes used as eager logical ops.
13993   // Don't diagnose this.
13994   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13995   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13996   if (isLeftBitwise || isRightBitwise)
13997     return;
13998 
13999   SourceRange DiagRange = isLeftComp
14000                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14001                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14002   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14003   SourceRange ParensRange =
14004       isLeftComp
14005           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14006           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14007 
14008   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14009     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14010   SuggestParentheses(Self, OpLoc,
14011     Self.PDiag(diag::note_precedence_silence) << OpStr,
14012     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14013   SuggestParentheses(Self, OpLoc,
14014     Self.PDiag(diag::note_precedence_bitwise_first)
14015       << BinaryOperator::getOpcodeStr(Opc),
14016     ParensRange);
14017 }
14018 
14019 /// It accepts a '&&' expr that is inside a '||' one.
14020 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14021 /// in parentheses.
14022 static void
14023 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14024                                        BinaryOperator *Bop) {
14025   assert(Bop->getOpcode() == BO_LAnd);
14026   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14027       << Bop->getSourceRange() << OpLoc;
14028   SuggestParentheses(Self, Bop->getOperatorLoc(),
14029     Self.PDiag(diag::note_precedence_silence)
14030       << Bop->getOpcodeStr(),
14031     Bop->getSourceRange());
14032 }
14033 
14034 /// Returns true if the given expression can be evaluated as a constant
14035 /// 'true'.
14036 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14037   bool Res;
14038   return !E->isValueDependent() &&
14039          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14040 }
14041 
14042 /// Returns true if the given expression can be evaluated as a constant
14043 /// 'false'.
14044 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14045   bool Res;
14046   return !E->isValueDependent() &&
14047          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14048 }
14049 
14050 /// Look for '&&' in the left hand of a '||' expr.
14051 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14052                                              Expr *LHSExpr, Expr *RHSExpr) {
14053   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14054     if (Bop->getOpcode() == BO_LAnd) {
14055       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14056       if (EvaluatesAsFalse(S, RHSExpr))
14057         return;
14058       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14059       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14060         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14061     } else if (Bop->getOpcode() == BO_LOr) {
14062       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14063         // If it's "a || b && 1 || c" we didn't warn earlier for
14064         // "a || b && 1", but warn now.
14065         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14066           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14067       }
14068     }
14069   }
14070 }
14071 
14072 /// Look for '&&' in the right hand of a '||' expr.
14073 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14074                                              Expr *LHSExpr, Expr *RHSExpr) {
14075   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14076     if (Bop->getOpcode() == BO_LAnd) {
14077       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14078       if (EvaluatesAsFalse(S, LHSExpr))
14079         return;
14080       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14081       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14082         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14083     }
14084   }
14085 }
14086 
14087 /// Look for bitwise op in the left or right hand of a bitwise op with
14088 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14089 /// the '&' expression in parentheses.
14090 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14091                                          SourceLocation OpLoc, Expr *SubExpr) {
14092   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14093     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14094       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14095         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14096         << Bop->getSourceRange() << OpLoc;
14097       SuggestParentheses(S, Bop->getOperatorLoc(),
14098         S.PDiag(diag::note_precedence_silence)
14099           << Bop->getOpcodeStr(),
14100         Bop->getSourceRange());
14101     }
14102   }
14103 }
14104 
14105 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14106                                     Expr *SubExpr, StringRef Shift) {
14107   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14108     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14109       StringRef Op = Bop->getOpcodeStr();
14110       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14111           << Bop->getSourceRange() << OpLoc << Shift << Op;
14112       SuggestParentheses(S, Bop->getOperatorLoc(),
14113           S.PDiag(diag::note_precedence_silence) << Op,
14114           Bop->getSourceRange());
14115     }
14116   }
14117 }
14118 
14119 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14120                                  Expr *LHSExpr, Expr *RHSExpr) {
14121   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14122   if (!OCE)
14123     return;
14124 
14125   FunctionDecl *FD = OCE->getDirectCallee();
14126   if (!FD || !FD->isOverloadedOperator())
14127     return;
14128 
14129   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14130   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14131     return;
14132 
14133   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14134       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14135       << (Kind == OO_LessLess);
14136   SuggestParentheses(S, OCE->getOperatorLoc(),
14137                      S.PDiag(diag::note_precedence_silence)
14138                          << (Kind == OO_LessLess ? "<<" : ">>"),
14139                      OCE->getSourceRange());
14140   SuggestParentheses(
14141       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14142       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14143 }
14144 
14145 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14146 /// precedence.
14147 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14148                                     SourceLocation OpLoc, Expr *LHSExpr,
14149                                     Expr *RHSExpr){
14150   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14151   if (BinaryOperator::isBitwiseOp(Opc))
14152     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14153 
14154   // Diagnose "arg1 & arg2 | arg3"
14155   if ((Opc == BO_Or || Opc == BO_Xor) &&
14156       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14157     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14158     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14159   }
14160 
14161   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14162   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14163   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14164     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14165     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14166   }
14167 
14168   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14169       || Opc == BO_Shr) {
14170     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14171     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14172     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14173   }
14174 
14175   // Warn on overloaded shift operators and comparisons, such as:
14176   // cout << 5 == 4;
14177   if (BinaryOperator::isComparisonOp(Opc))
14178     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14179 }
14180 
14181 // Binary Operators.  'Tok' is the token for the operator.
14182 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14183                             tok::TokenKind Kind,
14184                             Expr *LHSExpr, Expr *RHSExpr) {
14185   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14186   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14187   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14188 
14189   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14190   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14191 
14192   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14193 }
14194 
14195 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14196                        UnresolvedSetImpl &Functions) {
14197   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14198   if (OverOp != OO_None && OverOp != OO_Equal)
14199     LookupOverloadedOperatorName(OverOp, S, Functions);
14200 
14201   // In C++20 onwards, we may have a second operator to look up.
14202   if (getLangOpts().CPlusPlus20) {
14203     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14204       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14205   }
14206 }
14207 
14208 /// Build an overloaded binary operator expression in the given scope.
14209 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14210                                        BinaryOperatorKind Opc,
14211                                        Expr *LHS, Expr *RHS) {
14212   switch (Opc) {
14213   case BO_Assign:
14214   case BO_DivAssign:
14215   case BO_RemAssign:
14216   case BO_SubAssign:
14217   case BO_AndAssign:
14218   case BO_OrAssign:
14219   case BO_XorAssign:
14220     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14221     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14222     break;
14223   default:
14224     break;
14225   }
14226 
14227   // Find all of the overloaded operators visible from this point.
14228   UnresolvedSet<16> Functions;
14229   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14230 
14231   // Build the (potentially-overloaded, potentially-dependent)
14232   // binary operation.
14233   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14234 }
14235 
14236 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14237                             BinaryOperatorKind Opc,
14238                             Expr *LHSExpr, Expr *RHSExpr) {
14239   ExprResult LHS, RHS;
14240   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14241   if (!LHS.isUsable() || !RHS.isUsable())
14242     return ExprError();
14243   LHSExpr = LHS.get();
14244   RHSExpr = RHS.get();
14245 
14246   // We want to end up calling one of checkPseudoObjectAssignment
14247   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14248   // both expressions are overloadable or either is type-dependent),
14249   // or CreateBuiltinBinOp (in any other case).  We also want to get
14250   // any placeholder types out of the way.
14251 
14252   // Handle pseudo-objects in the LHS.
14253   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14254     // Assignments with a pseudo-object l-value need special analysis.
14255     if (pty->getKind() == BuiltinType::PseudoObject &&
14256         BinaryOperator::isAssignmentOp(Opc))
14257       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14258 
14259     // Don't resolve overloads if the other type is overloadable.
14260     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14261       // We can't actually test that if we still have a placeholder,
14262       // though.  Fortunately, none of the exceptions we see in that
14263       // code below are valid when the LHS is an overload set.  Note
14264       // that an overload set can be dependently-typed, but it never
14265       // instantiates to having an overloadable type.
14266       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14267       if (resolvedRHS.isInvalid()) return ExprError();
14268       RHSExpr = resolvedRHS.get();
14269 
14270       if (RHSExpr->isTypeDependent() ||
14271           RHSExpr->getType()->isOverloadableType())
14272         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14273     }
14274 
14275     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14276     // template, diagnose the missing 'template' keyword instead of diagnosing
14277     // an invalid use of a bound member function.
14278     //
14279     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14280     // to C++1z [over.over]/1.4, but we already checked for that case above.
14281     if (Opc == BO_LT && inTemplateInstantiation() &&
14282         (pty->getKind() == BuiltinType::BoundMember ||
14283          pty->getKind() == BuiltinType::Overload)) {
14284       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14285       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14286           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14287             return isa<FunctionTemplateDecl>(ND);
14288           })) {
14289         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14290                                 : OE->getNameLoc(),
14291              diag::err_template_kw_missing)
14292           << OE->getName().getAsString() << "";
14293         return ExprError();
14294       }
14295     }
14296 
14297     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14298     if (LHS.isInvalid()) return ExprError();
14299     LHSExpr = LHS.get();
14300   }
14301 
14302   // Handle pseudo-objects in the RHS.
14303   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14304     // An overload in the RHS can potentially be resolved by the type
14305     // being assigned to.
14306     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14307       if (getLangOpts().CPlusPlus &&
14308           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14309            LHSExpr->getType()->isOverloadableType()))
14310         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14311 
14312       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14313     }
14314 
14315     // Don't resolve overloads if the other type is overloadable.
14316     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14317         LHSExpr->getType()->isOverloadableType())
14318       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14319 
14320     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14321     if (!resolvedRHS.isUsable()) return ExprError();
14322     RHSExpr = resolvedRHS.get();
14323   }
14324 
14325   if (getLangOpts().CPlusPlus) {
14326     // If either expression is type-dependent, always build an
14327     // overloaded op.
14328     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14329       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14330 
14331     // Otherwise, build an overloaded op if either expression has an
14332     // overloadable type.
14333     if (LHSExpr->getType()->isOverloadableType() ||
14334         RHSExpr->getType()->isOverloadableType())
14335       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14336   }
14337 
14338   // Build a built-in binary operation.
14339   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14340 }
14341 
14342 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14343   if (T.isNull() || T->isDependentType())
14344     return false;
14345 
14346   if (!T->isPromotableIntegerType())
14347     return true;
14348 
14349   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14350 }
14351 
14352 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14353                                       UnaryOperatorKind Opc,
14354                                       Expr *InputExpr) {
14355   ExprResult Input = InputExpr;
14356   ExprValueKind VK = VK_RValue;
14357   ExprObjectKind OK = OK_Ordinary;
14358   QualType resultType;
14359   bool CanOverflow = false;
14360 
14361   bool ConvertHalfVec = false;
14362   if (getLangOpts().OpenCL) {
14363     QualType Ty = InputExpr->getType();
14364     // The only legal unary operation for atomics is '&'.
14365     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14366     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14367     // only with a builtin functions and therefore should be disallowed here.
14368         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14369         || Ty->isBlockPointerType())) {
14370       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14371                        << InputExpr->getType()
14372                        << Input.get()->getSourceRange());
14373     }
14374   }
14375 
14376   switch (Opc) {
14377   case UO_PreInc:
14378   case UO_PreDec:
14379   case UO_PostInc:
14380   case UO_PostDec:
14381     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14382                                                 OpLoc,
14383                                                 Opc == UO_PreInc ||
14384                                                 Opc == UO_PostInc,
14385                                                 Opc == UO_PreInc ||
14386                                                 Opc == UO_PreDec);
14387     CanOverflow = isOverflowingIntegerType(Context, resultType);
14388     break;
14389   case UO_AddrOf:
14390     resultType = CheckAddressOfOperand(Input, OpLoc);
14391     CheckAddressOfNoDeref(InputExpr);
14392     RecordModifiableNonNullParam(*this, InputExpr);
14393     break;
14394   case UO_Deref: {
14395     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14396     if (Input.isInvalid()) return ExprError();
14397     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14398     break;
14399   }
14400   case UO_Plus:
14401   case UO_Minus:
14402     CanOverflow = Opc == UO_Minus &&
14403                   isOverflowingIntegerType(Context, Input.get()->getType());
14404     Input = UsualUnaryConversions(Input.get());
14405     if (Input.isInvalid()) return ExprError();
14406     // Unary plus and minus require promoting an operand of half vector to a
14407     // float vector and truncating the result back to a half vector. For now, we
14408     // do this only when HalfArgsAndReturns is set (that is, when the target is
14409     // arm or arm64).
14410     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14411 
14412     // If the operand is a half vector, promote it to a float vector.
14413     if (ConvertHalfVec)
14414       Input = convertVector(Input.get(), Context.FloatTy, *this);
14415     resultType = Input.get()->getType();
14416     if (resultType->isDependentType())
14417       break;
14418     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14419       break;
14420     else if (resultType->isVectorType() &&
14421              // The z vector extensions don't allow + or - with bool vectors.
14422              (!Context.getLangOpts().ZVector ||
14423               resultType->castAs<VectorType>()->getVectorKind() !=
14424               VectorType::AltiVecBool))
14425       break;
14426     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14427              Opc == UO_Plus &&
14428              resultType->isPointerType())
14429       break;
14430 
14431     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14432       << resultType << Input.get()->getSourceRange());
14433 
14434   case UO_Not: // bitwise complement
14435     Input = UsualUnaryConversions(Input.get());
14436     if (Input.isInvalid())
14437       return ExprError();
14438     resultType = Input.get()->getType();
14439     if (resultType->isDependentType())
14440       break;
14441     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14442     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14443       // C99 does not support '~' for complex conjugation.
14444       Diag(OpLoc, diag::ext_integer_complement_complex)
14445           << resultType << Input.get()->getSourceRange();
14446     else if (resultType->hasIntegerRepresentation())
14447       break;
14448     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14449       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14450       // on vector float types.
14451       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14452       if (!T->isIntegerType())
14453         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14454                           << resultType << Input.get()->getSourceRange());
14455     } else {
14456       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14457                        << resultType << Input.get()->getSourceRange());
14458     }
14459     break;
14460 
14461   case UO_LNot: // logical negation
14462     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14463     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14464     if (Input.isInvalid()) return ExprError();
14465     resultType = Input.get()->getType();
14466 
14467     // Though we still have to promote half FP to float...
14468     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14469       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14470       resultType = Context.FloatTy;
14471     }
14472 
14473     if (resultType->isDependentType())
14474       break;
14475     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14476       // C99 6.5.3.3p1: ok, fallthrough;
14477       if (Context.getLangOpts().CPlusPlus) {
14478         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14479         // operand contextually converted to bool.
14480         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14481                                   ScalarTypeToBooleanCastKind(resultType));
14482       } else if (Context.getLangOpts().OpenCL &&
14483                  Context.getLangOpts().OpenCLVersion < 120) {
14484         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14485         // operate on scalar float types.
14486         if (!resultType->isIntegerType() && !resultType->isPointerType())
14487           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14488                            << resultType << Input.get()->getSourceRange());
14489       }
14490     } else if (resultType->isExtVectorType()) {
14491       if (Context.getLangOpts().OpenCL &&
14492           Context.getLangOpts().OpenCLVersion < 120 &&
14493           !Context.getLangOpts().OpenCLCPlusPlus) {
14494         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14495         // operate on vector float types.
14496         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14497         if (!T->isIntegerType())
14498           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14499                            << resultType << Input.get()->getSourceRange());
14500       }
14501       // Vector logical not returns the signed variant of the operand type.
14502       resultType = GetSignedVectorType(resultType);
14503       break;
14504     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14505       const VectorType *VTy = resultType->castAs<VectorType>();
14506       if (VTy->getVectorKind() != VectorType::GenericVector)
14507         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14508                          << resultType << Input.get()->getSourceRange());
14509 
14510       // Vector logical not returns the signed variant of the operand type.
14511       resultType = GetSignedVectorType(resultType);
14512       break;
14513     } else {
14514       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14515         << resultType << Input.get()->getSourceRange());
14516     }
14517 
14518     // LNot always has type int. C99 6.5.3.3p5.
14519     // In C++, it's bool. C++ 5.3.1p8
14520     resultType = Context.getLogicalOperationType();
14521     break;
14522   case UO_Real:
14523   case UO_Imag:
14524     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14525     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14526     // complex l-values to ordinary l-values and all other values to r-values.
14527     if (Input.isInvalid()) return ExprError();
14528     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14529       if (Input.get()->getValueKind() != VK_RValue &&
14530           Input.get()->getObjectKind() == OK_Ordinary)
14531         VK = Input.get()->getValueKind();
14532     } else if (!getLangOpts().CPlusPlus) {
14533       // In C, a volatile scalar is read by __imag. In C++, it is not.
14534       Input = DefaultLvalueConversion(Input.get());
14535     }
14536     break;
14537   case UO_Extension:
14538     resultType = Input.get()->getType();
14539     VK = Input.get()->getValueKind();
14540     OK = Input.get()->getObjectKind();
14541     break;
14542   case UO_Coawait:
14543     // It's unnecessary to represent the pass-through operator co_await in the
14544     // AST; just return the input expression instead.
14545     assert(!Input.get()->getType()->isDependentType() &&
14546                    "the co_await expression must be non-dependant before "
14547                    "building operator co_await");
14548     return Input;
14549   }
14550   if (resultType.isNull() || Input.isInvalid())
14551     return ExprError();
14552 
14553   // Check for array bounds violations in the operand of the UnaryOperator,
14554   // except for the '*' and '&' operators that have to be handled specially
14555   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14556   // that are explicitly defined as valid by the standard).
14557   if (Opc != UO_AddrOf && Opc != UO_Deref)
14558     CheckArrayAccess(Input.get());
14559 
14560   auto *UO =
14561       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14562                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14563 
14564   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14565       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14566     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14567 
14568   // Convert the result back to a half vector.
14569   if (ConvertHalfVec)
14570     return convertVector(UO, Context.HalfTy, *this);
14571   return UO;
14572 }
14573 
14574 /// Determine whether the given expression is a qualified member
14575 /// access expression, of a form that could be turned into a pointer to member
14576 /// with the address-of operator.
14577 bool Sema::isQualifiedMemberAccess(Expr *E) {
14578   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14579     if (!DRE->getQualifier())
14580       return false;
14581 
14582     ValueDecl *VD = DRE->getDecl();
14583     if (!VD->isCXXClassMember())
14584       return false;
14585 
14586     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14587       return true;
14588     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14589       return Method->isInstance();
14590 
14591     return false;
14592   }
14593 
14594   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14595     if (!ULE->getQualifier())
14596       return false;
14597 
14598     for (NamedDecl *D : ULE->decls()) {
14599       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14600         if (Method->isInstance())
14601           return true;
14602       } else {
14603         // Overload set does not contain methods.
14604         break;
14605       }
14606     }
14607 
14608     return false;
14609   }
14610 
14611   return false;
14612 }
14613 
14614 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14615                               UnaryOperatorKind Opc, Expr *Input) {
14616   // First things first: handle placeholders so that the
14617   // overloaded-operator check considers the right type.
14618   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14619     // Increment and decrement of pseudo-object references.
14620     if (pty->getKind() == BuiltinType::PseudoObject &&
14621         UnaryOperator::isIncrementDecrementOp(Opc))
14622       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14623 
14624     // extension is always a builtin operator.
14625     if (Opc == UO_Extension)
14626       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14627 
14628     // & gets special logic for several kinds of placeholder.
14629     // The builtin code knows what to do.
14630     if (Opc == UO_AddrOf &&
14631         (pty->getKind() == BuiltinType::Overload ||
14632          pty->getKind() == BuiltinType::UnknownAny ||
14633          pty->getKind() == BuiltinType::BoundMember))
14634       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14635 
14636     // Anything else needs to be handled now.
14637     ExprResult Result = CheckPlaceholderExpr(Input);
14638     if (Result.isInvalid()) return ExprError();
14639     Input = Result.get();
14640   }
14641 
14642   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14643       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14644       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14645     // Find all of the overloaded operators visible from this point.
14646     UnresolvedSet<16> Functions;
14647     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14648     if (S && OverOp != OO_None)
14649       LookupOverloadedOperatorName(OverOp, S, Functions);
14650 
14651     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14652   }
14653 
14654   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14655 }
14656 
14657 // Unary Operators.  'Tok' is the token for the operator.
14658 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14659                               tok::TokenKind Op, Expr *Input) {
14660   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14661 }
14662 
14663 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14664 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14665                                 LabelDecl *TheDecl) {
14666   TheDecl->markUsed(Context);
14667   // Create the AST node.  The address of a label always has type 'void*'.
14668   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14669                                      Context.getPointerType(Context.VoidTy));
14670 }
14671 
14672 void Sema::ActOnStartStmtExpr() {
14673   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14674 }
14675 
14676 void Sema::ActOnStmtExprError() {
14677   // Note that function is also called by TreeTransform when leaving a
14678   // StmtExpr scope without rebuilding anything.
14679 
14680   DiscardCleanupsInEvaluationContext();
14681   PopExpressionEvaluationContext();
14682 }
14683 
14684 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14685                                SourceLocation RPLoc) {
14686   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14687 }
14688 
14689 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14690                                SourceLocation RPLoc, unsigned TemplateDepth) {
14691   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14692   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14693 
14694   if (hasAnyUnrecoverableErrorsInThisFunction())
14695     DiscardCleanupsInEvaluationContext();
14696   assert(!Cleanup.exprNeedsCleanups() &&
14697          "cleanups within StmtExpr not correctly bound!");
14698   PopExpressionEvaluationContext();
14699 
14700   // FIXME: there are a variety of strange constraints to enforce here, for
14701   // example, it is not possible to goto into a stmt expression apparently.
14702   // More semantic analysis is needed.
14703 
14704   // If there are sub-stmts in the compound stmt, take the type of the last one
14705   // as the type of the stmtexpr.
14706   QualType Ty = Context.VoidTy;
14707   bool StmtExprMayBindToTemp = false;
14708   if (!Compound->body_empty()) {
14709     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14710     if (const auto *LastStmt =
14711             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14712       if (const Expr *Value = LastStmt->getExprStmt()) {
14713         StmtExprMayBindToTemp = true;
14714         Ty = Value->getType();
14715       }
14716     }
14717   }
14718 
14719   // FIXME: Check that expression type is complete/non-abstract; statement
14720   // expressions are not lvalues.
14721   Expr *ResStmtExpr =
14722       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14723   if (StmtExprMayBindToTemp)
14724     return MaybeBindToTemporary(ResStmtExpr);
14725   return ResStmtExpr;
14726 }
14727 
14728 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14729   if (ER.isInvalid())
14730     return ExprError();
14731 
14732   // Do function/array conversion on the last expression, but not
14733   // lvalue-to-rvalue.  However, initialize an unqualified type.
14734   ER = DefaultFunctionArrayConversion(ER.get());
14735   if (ER.isInvalid())
14736     return ExprError();
14737   Expr *E = ER.get();
14738 
14739   if (E->isTypeDependent())
14740     return E;
14741 
14742   // In ARC, if the final expression ends in a consume, splice
14743   // the consume out and bind it later.  In the alternate case
14744   // (when dealing with a retainable type), the result
14745   // initialization will create a produce.  In both cases the
14746   // result will be +1, and we'll need to balance that out with
14747   // a bind.
14748   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14749   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14750     return Cast->getSubExpr();
14751 
14752   // FIXME: Provide a better location for the initialization.
14753   return PerformCopyInitialization(
14754       InitializedEntity::InitializeStmtExprResult(
14755           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14756       SourceLocation(), E);
14757 }
14758 
14759 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14760                                       TypeSourceInfo *TInfo,
14761                                       ArrayRef<OffsetOfComponent> Components,
14762                                       SourceLocation RParenLoc) {
14763   QualType ArgTy = TInfo->getType();
14764   bool Dependent = ArgTy->isDependentType();
14765   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14766 
14767   // We must have at least one component that refers to the type, and the first
14768   // one is known to be a field designator.  Verify that the ArgTy represents
14769   // a struct/union/class.
14770   if (!Dependent && !ArgTy->isRecordType())
14771     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14772                        << ArgTy << TypeRange);
14773 
14774   // Type must be complete per C99 7.17p3 because a declaring a variable
14775   // with an incomplete type would be ill-formed.
14776   if (!Dependent
14777       && RequireCompleteType(BuiltinLoc, ArgTy,
14778                              diag::err_offsetof_incomplete_type, TypeRange))
14779     return ExprError();
14780 
14781   bool DidWarnAboutNonPOD = false;
14782   QualType CurrentType = ArgTy;
14783   SmallVector<OffsetOfNode, 4> Comps;
14784   SmallVector<Expr*, 4> Exprs;
14785   for (const OffsetOfComponent &OC : Components) {
14786     if (OC.isBrackets) {
14787       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14788       if (!CurrentType->isDependentType()) {
14789         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14790         if(!AT)
14791           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14792                            << CurrentType);
14793         CurrentType = AT->getElementType();
14794       } else
14795         CurrentType = Context.DependentTy;
14796 
14797       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14798       if (IdxRval.isInvalid())
14799         return ExprError();
14800       Expr *Idx = IdxRval.get();
14801 
14802       // The expression must be an integral expression.
14803       // FIXME: An integral constant expression?
14804       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14805           !Idx->getType()->isIntegerType())
14806         return ExprError(
14807             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14808             << Idx->getSourceRange());
14809 
14810       // Record this array index.
14811       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14812       Exprs.push_back(Idx);
14813       continue;
14814     }
14815 
14816     // Offset of a field.
14817     if (CurrentType->isDependentType()) {
14818       // We have the offset of a field, but we can't look into the dependent
14819       // type. Just record the identifier of the field.
14820       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14821       CurrentType = Context.DependentTy;
14822       continue;
14823     }
14824 
14825     // We need to have a complete type to look into.
14826     if (RequireCompleteType(OC.LocStart, CurrentType,
14827                             diag::err_offsetof_incomplete_type))
14828       return ExprError();
14829 
14830     // Look for the designated field.
14831     const RecordType *RC = CurrentType->getAs<RecordType>();
14832     if (!RC)
14833       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14834                        << CurrentType);
14835     RecordDecl *RD = RC->getDecl();
14836 
14837     // C++ [lib.support.types]p5:
14838     //   The macro offsetof accepts a restricted set of type arguments in this
14839     //   International Standard. type shall be a POD structure or a POD union
14840     //   (clause 9).
14841     // C++11 [support.types]p4:
14842     //   If type is not a standard-layout class (Clause 9), the results are
14843     //   undefined.
14844     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14845       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14846       unsigned DiagID =
14847         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14848                             : diag::ext_offsetof_non_pod_type;
14849 
14850       if (!IsSafe && !DidWarnAboutNonPOD &&
14851           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14852                               PDiag(DiagID)
14853                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14854                               << CurrentType))
14855         DidWarnAboutNonPOD = true;
14856     }
14857 
14858     // Look for the field.
14859     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14860     LookupQualifiedName(R, RD);
14861     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14862     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14863     if (!MemberDecl) {
14864       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14865         MemberDecl = IndirectMemberDecl->getAnonField();
14866     }
14867 
14868     if (!MemberDecl)
14869       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14870                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14871                                                               OC.LocEnd));
14872 
14873     // C99 7.17p3:
14874     //   (If the specified member is a bit-field, the behavior is undefined.)
14875     //
14876     // We diagnose this as an error.
14877     if (MemberDecl->isBitField()) {
14878       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14879         << MemberDecl->getDeclName()
14880         << SourceRange(BuiltinLoc, RParenLoc);
14881       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14882       return ExprError();
14883     }
14884 
14885     RecordDecl *Parent = MemberDecl->getParent();
14886     if (IndirectMemberDecl)
14887       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14888 
14889     // If the member was found in a base class, introduce OffsetOfNodes for
14890     // the base class indirections.
14891     CXXBasePaths Paths;
14892     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14893                       Paths)) {
14894       if (Paths.getDetectedVirtual()) {
14895         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14896           << MemberDecl->getDeclName()
14897           << SourceRange(BuiltinLoc, RParenLoc);
14898         return ExprError();
14899       }
14900 
14901       CXXBasePath &Path = Paths.front();
14902       for (const CXXBasePathElement &B : Path)
14903         Comps.push_back(OffsetOfNode(B.Base));
14904     }
14905 
14906     if (IndirectMemberDecl) {
14907       for (auto *FI : IndirectMemberDecl->chain()) {
14908         assert(isa<FieldDecl>(FI));
14909         Comps.push_back(OffsetOfNode(OC.LocStart,
14910                                      cast<FieldDecl>(FI), OC.LocEnd));
14911       }
14912     } else
14913       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14914 
14915     CurrentType = MemberDecl->getType().getNonReferenceType();
14916   }
14917 
14918   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14919                               Comps, Exprs, RParenLoc);
14920 }
14921 
14922 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14923                                       SourceLocation BuiltinLoc,
14924                                       SourceLocation TypeLoc,
14925                                       ParsedType ParsedArgTy,
14926                                       ArrayRef<OffsetOfComponent> Components,
14927                                       SourceLocation RParenLoc) {
14928 
14929   TypeSourceInfo *ArgTInfo;
14930   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14931   if (ArgTy.isNull())
14932     return ExprError();
14933 
14934   if (!ArgTInfo)
14935     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14936 
14937   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14938 }
14939 
14940 
14941 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14942                                  Expr *CondExpr,
14943                                  Expr *LHSExpr, Expr *RHSExpr,
14944                                  SourceLocation RPLoc) {
14945   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14946 
14947   ExprValueKind VK = VK_RValue;
14948   ExprObjectKind OK = OK_Ordinary;
14949   QualType resType;
14950   bool CondIsTrue = false;
14951   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14952     resType = Context.DependentTy;
14953   } else {
14954     // The conditional expression is required to be a constant expression.
14955     llvm::APSInt condEval(32);
14956     ExprResult CondICE
14957       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14958           diag::err_typecheck_choose_expr_requires_constant, false);
14959     if (CondICE.isInvalid())
14960       return ExprError();
14961     CondExpr = CondICE.get();
14962     CondIsTrue = condEval.getZExtValue();
14963 
14964     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14965     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14966 
14967     resType = ActiveExpr->getType();
14968     VK = ActiveExpr->getValueKind();
14969     OK = ActiveExpr->getObjectKind();
14970   }
14971 
14972   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14973                                   resType, VK, OK, RPLoc, CondIsTrue);
14974 }
14975 
14976 //===----------------------------------------------------------------------===//
14977 // Clang Extensions.
14978 //===----------------------------------------------------------------------===//
14979 
14980 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14981 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14982   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14983 
14984   if (LangOpts.CPlusPlus) {
14985     MangleNumberingContext *MCtx;
14986     Decl *ManglingContextDecl;
14987     std::tie(MCtx, ManglingContextDecl) =
14988         getCurrentMangleNumberContext(Block->getDeclContext());
14989     if (MCtx) {
14990       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14991       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14992     }
14993   }
14994 
14995   PushBlockScope(CurScope, Block);
14996   CurContext->addDecl(Block);
14997   if (CurScope)
14998     PushDeclContext(CurScope, Block);
14999   else
15000     CurContext = Block;
15001 
15002   getCurBlock()->HasImplicitReturnType = true;
15003 
15004   // Enter a new evaluation context to insulate the block from any
15005   // cleanups from the enclosing full-expression.
15006   PushExpressionEvaluationContext(
15007       ExpressionEvaluationContext::PotentiallyEvaluated);
15008 }
15009 
15010 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15011                                Scope *CurScope) {
15012   assert(ParamInfo.getIdentifier() == nullptr &&
15013          "block-id should have no identifier!");
15014   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15015   BlockScopeInfo *CurBlock = getCurBlock();
15016 
15017   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15018   QualType T = Sig->getType();
15019 
15020   // FIXME: We should allow unexpanded parameter packs here, but that would,
15021   // in turn, make the block expression contain unexpanded parameter packs.
15022   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15023     // Drop the parameters.
15024     FunctionProtoType::ExtProtoInfo EPI;
15025     EPI.HasTrailingReturn = false;
15026     EPI.TypeQuals.addConst();
15027     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15028     Sig = Context.getTrivialTypeSourceInfo(T);
15029   }
15030 
15031   // GetTypeForDeclarator always produces a function type for a block
15032   // literal signature.  Furthermore, it is always a FunctionProtoType
15033   // unless the function was written with a typedef.
15034   assert(T->isFunctionType() &&
15035          "GetTypeForDeclarator made a non-function block signature");
15036 
15037   // Look for an explicit signature in that function type.
15038   FunctionProtoTypeLoc ExplicitSignature;
15039 
15040   if ((ExplicitSignature = Sig->getTypeLoc()
15041                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15042 
15043     // Check whether that explicit signature was synthesized by
15044     // GetTypeForDeclarator.  If so, don't save that as part of the
15045     // written signature.
15046     if (ExplicitSignature.getLocalRangeBegin() ==
15047         ExplicitSignature.getLocalRangeEnd()) {
15048       // This would be much cheaper if we stored TypeLocs instead of
15049       // TypeSourceInfos.
15050       TypeLoc Result = ExplicitSignature.getReturnLoc();
15051       unsigned Size = Result.getFullDataSize();
15052       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15053       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15054 
15055       ExplicitSignature = FunctionProtoTypeLoc();
15056     }
15057   }
15058 
15059   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15060   CurBlock->FunctionType = T;
15061 
15062   const FunctionType *Fn = T->getAs<FunctionType>();
15063   QualType RetTy = Fn->getReturnType();
15064   bool isVariadic =
15065     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15066 
15067   CurBlock->TheDecl->setIsVariadic(isVariadic);
15068 
15069   // Context.DependentTy is used as a placeholder for a missing block
15070   // return type.  TODO:  what should we do with declarators like:
15071   //   ^ * { ... }
15072   // If the answer is "apply template argument deduction"....
15073   if (RetTy != Context.DependentTy) {
15074     CurBlock->ReturnType = RetTy;
15075     CurBlock->TheDecl->setBlockMissingReturnType(false);
15076     CurBlock->HasImplicitReturnType = false;
15077   }
15078 
15079   // Push block parameters from the declarator if we had them.
15080   SmallVector<ParmVarDecl*, 8> Params;
15081   if (ExplicitSignature) {
15082     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15083       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15084       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15085           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15086         // Diagnose this as an extension in C17 and earlier.
15087         if (!getLangOpts().C2x)
15088           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15089       }
15090       Params.push_back(Param);
15091     }
15092 
15093   // Fake up parameter variables if we have a typedef, like
15094   //   ^ fntype { ... }
15095   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15096     for (const auto &I : Fn->param_types()) {
15097       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15098           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15099       Params.push_back(Param);
15100     }
15101   }
15102 
15103   // Set the parameters on the block decl.
15104   if (!Params.empty()) {
15105     CurBlock->TheDecl->setParams(Params);
15106     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15107                              /*CheckParameterNames=*/false);
15108   }
15109 
15110   // Finally we can process decl attributes.
15111   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15112 
15113   // Put the parameter variables in scope.
15114   for (auto AI : CurBlock->TheDecl->parameters()) {
15115     AI->setOwningFunction(CurBlock->TheDecl);
15116 
15117     // If this has an identifier, add it to the scope stack.
15118     if (AI->getIdentifier()) {
15119       CheckShadow(CurBlock->TheScope, AI);
15120 
15121       PushOnScopeChains(AI, CurBlock->TheScope);
15122     }
15123   }
15124 }
15125 
15126 /// ActOnBlockError - If there is an error parsing a block, this callback
15127 /// is invoked to pop the information about the block from the action impl.
15128 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15129   // Leave the expression-evaluation context.
15130   DiscardCleanupsInEvaluationContext();
15131   PopExpressionEvaluationContext();
15132 
15133   // Pop off CurBlock, handle nested blocks.
15134   PopDeclContext();
15135   PopFunctionScopeInfo();
15136 }
15137 
15138 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15139 /// literal was successfully completed.  ^(int x){...}
15140 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15141                                     Stmt *Body, Scope *CurScope) {
15142   // If blocks are disabled, emit an error.
15143   if (!LangOpts.Blocks)
15144     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15145 
15146   // Leave the expression-evaluation context.
15147   if (hasAnyUnrecoverableErrorsInThisFunction())
15148     DiscardCleanupsInEvaluationContext();
15149   assert(!Cleanup.exprNeedsCleanups() &&
15150          "cleanups within block not correctly bound!");
15151   PopExpressionEvaluationContext();
15152 
15153   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15154   BlockDecl *BD = BSI->TheDecl;
15155 
15156   if (BSI->HasImplicitReturnType)
15157     deduceClosureReturnType(*BSI);
15158 
15159   QualType RetTy = Context.VoidTy;
15160   if (!BSI->ReturnType.isNull())
15161     RetTy = BSI->ReturnType;
15162 
15163   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15164   QualType BlockTy;
15165 
15166   // If the user wrote a function type in some form, try to use that.
15167   if (!BSI->FunctionType.isNull()) {
15168     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15169 
15170     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15171     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15172 
15173     // Turn protoless block types into nullary block types.
15174     if (isa<FunctionNoProtoType>(FTy)) {
15175       FunctionProtoType::ExtProtoInfo EPI;
15176       EPI.ExtInfo = Ext;
15177       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15178 
15179     // Otherwise, if we don't need to change anything about the function type,
15180     // preserve its sugar structure.
15181     } else if (FTy->getReturnType() == RetTy &&
15182                (!NoReturn || FTy->getNoReturnAttr())) {
15183       BlockTy = BSI->FunctionType;
15184 
15185     // Otherwise, make the minimal modifications to the function type.
15186     } else {
15187       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15188       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15189       EPI.TypeQuals = Qualifiers();
15190       EPI.ExtInfo = Ext;
15191       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15192     }
15193 
15194   // If we don't have a function type, just build one from nothing.
15195   } else {
15196     FunctionProtoType::ExtProtoInfo EPI;
15197     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15198     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15199   }
15200 
15201   DiagnoseUnusedParameters(BD->parameters());
15202   BlockTy = Context.getBlockPointerType(BlockTy);
15203 
15204   // If needed, diagnose invalid gotos and switches in the block.
15205   if (getCurFunction()->NeedsScopeChecking() &&
15206       !PP.isCodeCompletionEnabled())
15207     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15208 
15209   BD->setBody(cast<CompoundStmt>(Body));
15210 
15211   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15212     DiagnoseUnguardedAvailabilityViolations(BD);
15213 
15214   // Try to apply the named return value optimization. We have to check again
15215   // if we can do this, though, because blocks keep return statements around
15216   // to deduce an implicit return type.
15217   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15218       !BD->isDependentContext())
15219     computeNRVO(Body, BSI);
15220 
15221   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15222       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15223     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15224                           NTCUK_Destruct|NTCUK_Copy);
15225 
15226   PopDeclContext();
15227 
15228   // Pop the block scope now but keep it alive to the end of this function.
15229   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15230   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15231 
15232   // Set the captured variables on the block.
15233   SmallVector<BlockDecl::Capture, 4> Captures;
15234   for (Capture &Cap : BSI->Captures) {
15235     if (Cap.isInvalid() || Cap.isThisCapture())
15236       continue;
15237 
15238     VarDecl *Var = Cap.getVariable();
15239     Expr *CopyExpr = nullptr;
15240     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15241       if (const RecordType *Record =
15242               Cap.getCaptureType()->getAs<RecordType>()) {
15243         // The capture logic needs the destructor, so make sure we mark it.
15244         // Usually this is unnecessary because most local variables have
15245         // their destructors marked at declaration time, but parameters are
15246         // an exception because it's technically only the call site that
15247         // actually requires the destructor.
15248         if (isa<ParmVarDecl>(Var))
15249           FinalizeVarWithDestructor(Var, Record);
15250 
15251         // Enter a separate potentially-evaluated context while building block
15252         // initializers to isolate their cleanups from those of the block
15253         // itself.
15254         // FIXME: Is this appropriate even when the block itself occurs in an
15255         // unevaluated operand?
15256         EnterExpressionEvaluationContext EvalContext(
15257             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15258 
15259         SourceLocation Loc = Cap.getLocation();
15260 
15261         ExprResult Result = BuildDeclarationNameExpr(
15262             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15263 
15264         // According to the blocks spec, the capture of a variable from
15265         // the stack requires a const copy constructor.  This is not true
15266         // of the copy/move done to move a __block variable to the heap.
15267         if (!Result.isInvalid() &&
15268             !Result.get()->getType().isConstQualified()) {
15269           Result = ImpCastExprToType(Result.get(),
15270                                      Result.get()->getType().withConst(),
15271                                      CK_NoOp, VK_LValue);
15272         }
15273 
15274         if (!Result.isInvalid()) {
15275           Result = PerformCopyInitialization(
15276               InitializedEntity::InitializeBlock(Var->getLocation(),
15277                                                  Cap.getCaptureType(), false),
15278               Loc, Result.get());
15279         }
15280 
15281         // Build a full-expression copy expression if initialization
15282         // succeeded and used a non-trivial constructor.  Recover from
15283         // errors by pretending that the copy isn't necessary.
15284         if (!Result.isInvalid() &&
15285             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15286                 ->isTrivial()) {
15287           Result = MaybeCreateExprWithCleanups(Result);
15288           CopyExpr = Result.get();
15289         }
15290       }
15291     }
15292 
15293     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15294                               CopyExpr);
15295     Captures.push_back(NewCap);
15296   }
15297   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15298 
15299   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15300 
15301   // If the block isn't obviously global, i.e. it captures anything at
15302   // all, then we need to do a few things in the surrounding context:
15303   if (Result->getBlockDecl()->hasCaptures()) {
15304     // First, this expression has a new cleanup object.
15305     ExprCleanupObjects.push_back(Result->getBlockDecl());
15306     Cleanup.setExprNeedsCleanups(true);
15307 
15308     // It also gets a branch-protected scope if any of the captured
15309     // variables needs destruction.
15310     for (const auto &CI : Result->getBlockDecl()->captures()) {
15311       const VarDecl *var = CI.getVariable();
15312       if (var->getType().isDestructedType() != QualType::DK_none) {
15313         setFunctionHasBranchProtectedScope();
15314         break;
15315       }
15316     }
15317   }
15318 
15319   if (getCurFunction())
15320     getCurFunction()->addBlock(BD);
15321 
15322   return Result;
15323 }
15324 
15325 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15326                             SourceLocation RPLoc) {
15327   TypeSourceInfo *TInfo;
15328   GetTypeFromParser(Ty, &TInfo);
15329   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15330 }
15331 
15332 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15333                                 Expr *E, TypeSourceInfo *TInfo,
15334                                 SourceLocation RPLoc) {
15335   Expr *OrigExpr = E;
15336   bool IsMS = false;
15337 
15338   // CUDA device code does not support varargs.
15339   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15340     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15341       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15342       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15343         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15344     }
15345   }
15346 
15347   // NVPTX does not support va_arg expression.
15348   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15349       Context.getTargetInfo().getTriple().isNVPTX())
15350     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15351 
15352   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15353   // as Microsoft ABI on an actual Microsoft platform, where
15354   // __builtin_ms_va_list and __builtin_va_list are the same.)
15355   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15356       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15357     QualType MSVaListType = Context.getBuiltinMSVaListType();
15358     if (Context.hasSameType(MSVaListType, E->getType())) {
15359       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15360         return ExprError();
15361       IsMS = true;
15362     }
15363   }
15364 
15365   // Get the va_list type
15366   QualType VaListType = Context.getBuiltinVaListType();
15367   if (!IsMS) {
15368     if (VaListType->isArrayType()) {
15369       // Deal with implicit array decay; for example, on x86-64,
15370       // va_list is an array, but it's supposed to decay to
15371       // a pointer for va_arg.
15372       VaListType = Context.getArrayDecayedType(VaListType);
15373       // Make sure the input expression also decays appropriately.
15374       ExprResult Result = UsualUnaryConversions(E);
15375       if (Result.isInvalid())
15376         return ExprError();
15377       E = Result.get();
15378     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15379       // If va_list is a record type and we are compiling in C++ mode,
15380       // check the argument using reference binding.
15381       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15382           Context, Context.getLValueReferenceType(VaListType), false);
15383       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15384       if (Init.isInvalid())
15385         return ExprError();
15386       E = Init.getAs<Expr>();
15387     } else {
15388       // Otherwise, the va_list argument must be an l-value because
15389       // it is modified by va_arg.
15390       if (!E->isTypeDependent() &&
15391           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15392         return ExprError();
15393     }
15394   }
15395 
15396   if (!IsMS && !E->isTypeDependent() &&
15397       !Context.hasSameType(VaListType, E->getType()))
15398     return ExprError(
15399         Diag(E->getBeginLoc(),
15400              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15401         << OrigExpr->getType() << E->getSourceRange());
15402 
15403   if (!TInfo->getType()->isDependentType()) {
15404     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15405                             diag::err_second_parameter_to_va_arg_incomplete,
15406                             TInfo->getTypeLoc()))
15407       return ExprError();
15408 
15409     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15410                                TInfo->getType(),
15411                                diag::err_second_parameter_to_va_arg_abstract,
15412                                TInfo->getTypeLoc()))
15413       return ExprError();
15414 
15415     if (!TInfo->getType().isPODType(Context)) {
15416       Diag(TInfo->getTypeLoc().getBeginLoc(),
15417            TInfo->getType()->isObjCLifetimeType()
15418              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15419              : diag::warn_second_parameter_to_va_arg_not_pod)
15420         << TInfo->getType()
15421         << TInfo->getTypeLoc().getSourceRange();
15422     }
15423 
15424     // Check for va_arg where arguments of the given type will be promoted
15425     // (i.e. this va_arg is guaranteed to have undefined behavior).
15426     QualType PromoteType;
15427     if (TInfo->getType()->isPromotableIntegerType()) {
15428       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15429       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15430         PromoteType = QualType();
15431     }
15432     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15433       PromoteType = Context.DoubleTy;
15434     if (!PromoteType.isNull())
15435       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15436                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15437                           << TInfo->getType()
15438                           << PromoteType
15439                           << TInfo->getTypeLoc().getSourceRange());
15440   }
15441 
15442   QualType T = TInfo->getType().getNonLValueExprType(Context);
15443   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15444 }
15445 
15446 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15447   // The type of __null will be int or long, depending on the size of
15448   // pointers on the target.
15449   QualType Ty;
15450   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15451   if (pw == Context.getTargetInfo().getIntWidth())
15452     Ty = Context.IntTy;
15453   else if (pw == Context.getTargetInfo().getLongWidth())
15454     Ty = Context.LongTy;
15455   else if (pw == Context.getTargetInfo().getLongLongWidth())
15456     Ty = Context.LongLongTy;
15457   else {
15458     llvm_unreachable("I don't know size of pointer!");
15459   }
15460 
15461   return new (Context) GNUNullExpr(Ty, TokenLoc);
15462 }
15463 
15464 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15465                                     SourceLocation BuiltinLoc,
15466                                     SourceLocation RPLoc) {
15467   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15468 }
15469 
15470 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15471                                     SourceLocation BuiltinLoc,
15472                                     SourceLocation RPLoc,
15473                                     DeclContext *ParentContext) {
15474   return new (Context)
15475       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15476 }
15477 
15478 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15479                                         bool Diagnose) {
15480   if (!getLangOpts().ObjC)
15481     return false;
15482 
15483   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15484   if (!PT)
15485     return false;
15486   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15487 
15488   // Ignore any parens, implicit casts (should only be
15489   // array-to-pointer decays), and not-so-opaque values.  The last is
15490   // important for making this trigger for property assignments.
15491   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15492   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15493     if (OV->getSourceExpr())
15494       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15495 
15496   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15497     if (!PT->isObjCIdType() &&
15498         !(ID && ID->getIdentifier()->isStr("NSString")))
15499       return false;
15500     if (!SL->isAscii())
15501       return false;
15502 
15503     if (Diagnose) {
15504       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15505           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15506       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15507     }
15508     return true;
15509   }
15510 
15511   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15512       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15513       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15514       !SrcExpr->isNullPointerConstant(
15515           getASTContext(), Expr::NPC_NeverValueDependent)) {
15516     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15517       return false;
15518     if (Diagnose) {
15519       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15520           << /*number*/1
15521           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15522       Expr *NumLit =
15523           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15524       if (NumLit)
15525         Exp = NumLit;
15526     }
15527     return true;
15528   }
15529 
15530   return false;
15531 }
15532 
15533 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15534                                               const Expr *SrcExpr) {
15535   if (!DstType->isFunctionPointerType() ||
15536       !SrcExpr->getType()->isFunctionType())
15537     return false;
15538 
15539   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15540   if (!DRE)
15541     return false;
15542 
15543   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15544   if (!FD)
15545     return false;
15546 
15547   return !S.checkAddressOfFunctionIsAvailable(FD,
15548                                               /*Complain=*/true,
15549                                               SrcExpr->getBeginLoc());
15550 }
15551 
15552 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15553                                     SourceLocation Loc,
15554                                     QualType DstType, QualType SrcType,
15555                                     Expr *SrcExpr, AssignmentAction Action,
15556                                     bool *Complained) {
15557   if (Complained)
15558     *Complained = false;
15559 
15560   // Decode the result (notice that AST's are still created for extensions).
15561   bool CheckInferredResultType = false;
15562   bool isInvalid = false;
15563   unsigned DiagKind = 0;
15564   ConversionFixItGenerator ConvHints;
15565   bool MayHaveConvFixit = false;
15566   bool MayHaveFunctionDiff = false;
15567   const ObjCInterfaceDecl *IFace = nullptr;
15568   const ObjCProtocolDecl *PDecl = nullptr;
15569 
15570   switch (ConvTy) {
15571   case Compatible:
15572       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15573       return false;
15574 
15575   case PointerToInt:
15576     if (getLangOpts().CPlusPlus) {
15577       DiagKind = diag::err_typecheck_convert_pointer_int;
15578       isInvalid = true;
15579     } else {
15580       DiagKind = diag::ext_typecheck_convert_pointer_int;
15581     }
15582     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15583     MayHaveConvFixit = true;
15584     break;
15585   case IntToPointer:
15586     if (getLangOpts().CPlusPlus) {
15587       DiagKind = diag::err_typecheck_convert_int_pointer;
15588       isInvalid = true;
15589     } else {
15590       DiagKind = diag::ext_typecheck_convert_int_pointer;
15591     }
15592     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15593     MayHaveConvFixit = true;
15594     break;
15595   case IncompatibleFunctionPointer:
15596     if (getLangOpts().CPlusPlus) {
15597       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15598       isInvalid = true;
15599     } else {
15600       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15601     }
15602     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15603     MayHaveConvFixit = true;
15604     break;
15605   case IncompatiblePointer:
15606     if (Action == AA_Passing_CFAudited) {
15607       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15608     } else if (getLangOpts().CPlusPlus) {
15609       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15610       isInvalid = true;
15611     } else {
15612       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15613     }
15614     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15615       SrcType->isObjCObjectPointerType();
15616     if (!CheckInferredResultType) {
15617       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15618     } else if (CheckInferredResultType) {
15619       SrcType = SrcType.getUnqualifiedType();
15620       DstType = DstType.getUnqualifiedType();
15621     }
15622     MayHaveConvFixit = true;
15623     break;
15624   case IncompatiblePointerSign:
15625     if (getLangOpts().CPlusPlus) {
15626       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15627       isInvalid = true;
15628     } else {
15629       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15630     }
15631     break;
15632   case FunctionVoidPointer:
15633     if (getLangOpts().CPlusPlus) {
15634       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15635       isInvalid = true;
15636     } else {
15637       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15638     }
15639     break;
15640   case IncompatiblePointerDiscardsQualifiers: {
15641     // Perform array-to-pointer decay if necessary.
15642     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15643 
15644     isInvalid = true;
15645 
15646     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15647     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15648     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15649       DiagKind = diag::err_typecheck_incompatible_address_space;
15650       break;
15651 
15652     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15653       DiagKind = diag::err_typecheck_incompatible_ownership;
15654       break;
15655     }
15656 
15657     llvm_unreachable("unknown error case for discarding qualifiers!");
15658     // fallthrough
15659   }
15660   case CompatiblePointerDiscardsQualifiers:
15661     // If the qualifiers lost were because we were applying the
15662     // (deprecated) C++ conversion from a string literal to a char*
15663     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15664     // Ideally, this check would be performed in
15665     // checkPointerTypesForAssignment. However, that would require a
15666     // bit of refactoring (so that the second argument is an
15667     // expression, rather than a type), which should be done as part
15668     // of a larger effort to fix checkPointerTypesForAssignment for
15669     // C++ semantics.
15670     if (getLangOpts().CPlusPlus &&
15671         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15672       return false;
15673     if (getLangOpts().CPlusPlus) {
15674       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15675       isInvalid = true;
15676     } else {
15677       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15678     }
15679 
15680     break;
15681   case IncompatibleNestedPointerQualifiers:
15682     if (getLangOpts().CPlusPlus) {
15683       isInvalid = true;
15684       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15685     } else {
15686       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15687     }
15688     break;
15689   case IncompatibleNestedPointerAddressSpaceMismatch:
15690     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15691     isInvalid = true;
15692     break;
15693   case IntToBlockPointer:
15694     DiagKind = diag::err_int_to_block_pointer;
15695     isInvalid = true;
15696     break;
15697   case IncompatibleBlockPointer:
15698     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15699     isInvalid = true;
15700     break;
15701   case IncompatibleObjCQualifiedId: {
15702     if (SrcType->isObjCQualifiedIdType()) {
15703       const ObjCObjectPointerType *srcOPT =
15704                 SrcType->castAs<ObjCObjectPointerType>();
15705       for (auto *srcProto : srcOPT->quals()) {
15706         PDecl = srcProto;
15707         break;
15708       }
15709       if (const ObjCInterfaceType *IFaceT =
15710             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15711         IFace = IFaceT->getDecl();
15712     }
15713     else if (DstType->isObjCQualifiedIdType()) {
15714       const ObjCObjectPointerType *dstOPT =
15715         DstType->castAs<ObjCObjectPointerType>();
15716       for (auto *dstProto : dstOPT->quals()) {
15717         PDecl = dstProto;
15718         break;
15719       }
15720       if (const ObjCInterfaceType *IFaceT =
15721             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15722         IFace = IFaceT->getDecl();
15723     }
15724     if (getLangOpts().CPlusPlus) {
15725       DiagKind = diag::err_incompatible_qualified_id;
15726       isInvalid = true;
15727     } else {
15728       DiagKind = diag::warn_incompatible_qualified_id;
15729     }
15730     break;
15731   }
15732   case IncompatibleVectors:
15733     if (getLangOpts().CPlusPlus) {
15734       DiagKind = diag::err_incompatible_vectors;
15735       isInvalid = true;
15736     } else {
15737       DiagKind = diag::warn_incompatible_vectors;
15738     }
15739     break;
15740   case IncompatibleObjCWeakRef:
15741     DiagKind = diag::err_arc_weak_unavailable_assign;
15742     isInvalid = true;
15743     break;
15744   case Incompatible:
15745     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15746       if (Complained)
15747         *Complained = true;
15748       return true;
15749     }
15750 
15751     DiagKind = diag::err_typecheck_convert_incompatible;
15752     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15753     MayHaveConvFixit = true;
15754     isInvalid = true;
15755     MayHaveFunctionDiff = true;
15756     break;
15757   }
15758 
15759   QualType FirstType, SecondType;
15760   switch (Action) {
15761   case AA_Assigning:
15762   case AA_Initializing:
15763     // The destination type comes first.
15764     FirstType = DstType;
15765     SecondType = SrcType;
15766     break;
15767 
15768   case AA_Returning:
15769   case AA_Passing:
15770   case AA_Passing_CFAudited:
15771   case AA_Converting:
15772   case AA_Sending:
15773   case AA_Casting:
15774     // The source type comes first.
15775     FirstType = SrcType;
15776     SecondType = DstType;
15777     break;
15778   }
15779 
15780   PartialDiagnostic FDiag = PDiag(DiagKind);
15781   if (Action == AA_Passing_CFAudited)
15782     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15783   else
15784     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15785 
15786   // If we can fix the conversion, suggest the FixIts.
15787   if (!ConvHints.isNull()) {
15788     for (FixItHint &H : ConvHints.Hints)
15789       FDiag << H;
15790   }
15791 
15792   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15793 
15794   if (MayHaveFunctionDiff)
15795     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15796 
15797   Diag(Loc, FDiag);
15798   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15799        DiagKind == diag::err_incompatible_qualified_id) &&
15800       PDecl && IFace && !IFace->hasDefinition())
15801     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15802         << IFace << PDecl;
15803 
15804   if (SecondType == Context.OverloadTy)
15805     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15806                               FirstType, /*TakingAddress=*/true);
15807 
15808   if (CheckInferredResultType)
15809     EmitRelatedResultTypeNote(SrcExpr);
15810 
15811   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15812     EmitRelatedResultTypeNoteForReturn(DstType);
15813 
15814   if (Complained)
15815     *Complained = true;
15816   return isInvalid;
15817 }
15818 
15819 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15820                                                  llvm::APSInt *Result) {
15821   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15822   public:
15823     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15824                                              QualType T) override {
15825       return S.Diag(Loc, diag::err_ice_not_integral)
15826              << T << S.LangOpts.CPlusPlus;
15827     }
15828     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15829       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15830     }
15831   } Diagnoser;
15832 
15833   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15834 }
15835 
15836 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15837                                                  llvm::APSInt *Result,
15838                                                  unsigned DiagID,
15839                                                  bool AllowFold) {
15840   class IDDiagnoser : public VerifyICEDiagnoser {
15841     unsigned DiagID;
15842 
15843   public:
15844     IDDiagnoser(unsigned DiagID)
15845       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15846 
15847     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15848       return S.Diag(Loc, DiagID);
15849     }
15850   } Diagnoser(DiagID);
15851 
15852   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15853 }
15854 
15855 Sema::SemaDiagnosticBuilder
15856 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15857                                              QualType T) {
15858   return diagnoseNotICE(S, Loc);
15859 }
15860 
15861 Sema::SemaDiagnosticBuilder
15862 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15863   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15864 }
15865 
15866 ExprResult
15867 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15868                                       VerifyICEDiagnoser &Diagnoser,
15869                                       bool AllowFold) {
15870   SourceLocation DiagLoc = E->getBeginLoc();
15871 
15872   if (getLangOpts().CPlusPlus11) {
15873     // C++11 [expr.const]p5:
15874     //   If an expression of literal class type is used in a context where an
15875     //   integral constant expression is required, then that class type shall
15876     //   have a single non-explicit conversion function to an integral or
15877     //   unscoped enumeration type
15878     ExprResult Converted;
15879     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15880       VerifyICEDiagnoser &BaseDiagnoser;
15881     public:
15882       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15883           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15884                                 BaseDiagnoser.Suppress, true),
15885             BaseDiagnoser(BaseDiagnoser) {}
15886 
15887       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15888                                            QualType T) override {
15889         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15890       }
15891 
15892       SemaDiagnosticBuilder diagnoseIncomplete(
15893           Sema &S, SourceLocation Loc, QualType T) override {
15894         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15895       }
15896 
15897       SemaDiagnosticBuilder diagnoseExplicitConv(
15898           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15899         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15900       }
15901 
15902       SemaDiagnosticBuilder noteExplicitConv(
15903           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15904         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15905                  << ConvTy->isEnumeralType() << ConvTy;
15906       }
15907 
15908       SemaDiagnosticBuilder diagnoseAmbiguous(
15909           Sema &S, SourceLocation Loc, QualType T) override {
15910         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15911       }
15912 
15913       SemaDiagnosticBuilder noteAmbiguous(
15914           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15915         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15916                  << ConvTy->isEnumeralType() << ConvTy;
15917       }
15918 
15919       SemaDiagnosticBuilder diagnoseConversion(
15920           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15921         llvm_unreachable("conversion functions are permitted");
15922       }
15923     } ConvertDiagnoser(Diagnoser);
15924 
15925     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15926                                                     ConvertDiagnoser);
15927     if (Converted.isInvalid())
15928       return Converted;
15929     E = Converted.get();
15930     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15931       return ExprError();
15932   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15933     // An ICE must be of integral or unscoped enumeration type.
15934     if (!Diagnoser.Suppress)
15935       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
15936           << E->getSourceRange();
15937     return ExprError();
15938   }
15939 
15940   ExprResult RValueExpr = DefaultLvalueConversion(E);
15941   if (RValueExpr.isInvalid())
15942     return ExprError();
15943 
15944   E = RValueExpr.get();
15945 
15946   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15947   // in the non-ICE case.
15948   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15949     if (Result)
15950       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15951     if (!isa<ConstantExpr>(E))
15952       E = ConstantExpr::Create(Context, E);
15953     return E;
15954   }
15955 
15956   Expr::EvalResult EvalResult;
15957   SmallVector<PartialDiagnosticAt, 8> Notes;
15958   EvalResult.Diag = &Notes;
15959 
15960   // Try to evaluate the expression, and produce diagnostics explaining why it's
15961   // not a constant expression as a side-effect.
15962   bool Folded =
15963       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15964       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15965 
15966   if (!isa<ConstantExpr>(E))
15967     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15968 
15969   // In C++11, we can rely on diagnostics being produced for any expression
15970   // which is not a constant expression. If no diagnostics were produced, then
15971   // this is a constant expression.
15972   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15973     if (Result)
15974       *Result = EvalResult.Val.getInt();
15975     return E;
15976   }
15977 
15978   // If our only note is the usual "invalid subexpression" note, just point
15979   // the caret at its location rather than producing an essentially
15980   // redundant note.
15981   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15982         diag::note_invalid_subexpr_in_const_expr) {
15983     DiagLoc = Notes[0].first;
15984     Notes.clear();
15985   }
15986 
15987   if (!Folded || !AllowFold) {
15988     if (!Diagnoser.Suppress) {
15989       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
15990       for (const PartialDiagnosticAt &Note : Notes)
15991         Diag(Note.first, Note.second);
15992     }
15993 
15994     return ExprError();
15995   }
15996 
15997   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
15998   for (const PartialDiagnosticAt &Note : Notes)
15999     Diag(Note.first, Note.second);
16000 
16001   if (Result)
16002     *Result = EvalResult.Val.getInt();
16003   return E;
16004 }
16005 
16006 namespace {
16007   // Handle the case where we conclude a expression which we speculatively
16008   // considered to be unevaluated is actually evaluated.
16009   class TransformToPE : public TreeTransform<TransformToPE> {
16010     typedef TreeTransform<TransformToPE> BaseTransform;
16011 
16012   public:
16013     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16014 
16015     // Make sure we redo semantic analysis
16016     bool AlwaysRebuild() { return true; }
16017     bool ReplacingOriginal() { return true; }
16018 
16019     // We need to special-case DeclRefExprs referring to FieldDecls which
16020     // are not part of a member pointer formation; normal TreeTransforming
16021     // doesn't catch this case because of the way we represent them in the AST.
16022     // FIXME: This is a bit ugly; is it really the best way to handle this
16023     // case?
16024     //
16025     // Error on DeclRefExprs referring to FieldDecls.
16026     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16027       if (isa<FieldDecl>(E->getDecl()) &&
16028           !SemaRef.isUnevaluatedContext())
16029         return SemaRef.Diag(E->getLocation(),
16030                             diag::err_invalid_non_static_member_use)
16031             << E->getDecl() << E->getSourceRange();
16032 
16033       return BaseTransform::TransformDeclRefExpr(E);
16034     }
16035 
16036     // Exception: filter out member pointer formation
16037     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16038       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16039         return E;
16040 
16041       return BaseTransform::TransformUnaryOperator(E);
16042     }
16043 
16044     // The body of a lambda-expression is in a separate expression evaluation
16045     // context so never needs to be transformed.
16046     // FIXME: Ideally we wouldn't transform the closure type either, and would
16047     // just recreate the capture expressions and lambda expression.
16048     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16049       return SkipLambdaBody(E, Body);
16050     }
16051   };
16052 }
16053 
16054 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16055   assert(isUnevaluatedContext() &&
16056          "Should only transform unevaluated expressions");
16057   ExprEvalContexts.back().Context =
16058       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16059   if (isUnevaluatedContext())
16060     return E;
16061   return TransformToPE(*this).TransformExpr(E);
16062 }
16063 
16064 void
16065 Sema::PushExpressionEvaluationContext(
16066     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16067     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16068   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16069                                 LambdaContextDecl, ExprContext);
16070   Cleanup.reset();
16071   if (!MaybeODRUseExprs.empty())
16072     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16073 }
16074 
16075 void
16076 Sema::PushExpressionEvaluationContext(
16077     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16078     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16079   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16080   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16081 }
16082 
16083 namespace {
16084 
16085 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16086   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16087   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16088     if (E->getOpcode() == UO_Deref)
16089       return CheckPossibleDeref(S, E->getSubExpr());
16090   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16091     return CheckPossibleDeref(S, E->getBase());
16092   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16093     return CheckPossibleDeref(S, E->getBase());
16094   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16095     QualType Inner;
16096     QualType Ty = E->getType();
16097     if (const auto *Ptr = Ty->getAs<PointerType>())
16098       Inner = Ptr->getPointeeType();
16099     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16100       Inner = Arr->getElementType();
16101     else
16102       return nullptr;
16103 
16104     if (Inner->hasAttr(attr::NoDeref))
16105       return E;
16106   }
16107   return nullptr;
16108 }
16109 
16110 } // namespace
16111 
16112 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16113   for (const Expr *E : Rec.PossibleDerefs) {
16114     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16115     if (DeclRef) {
16116       const ValueDecl *Decl = DeclRef->getDecl();
16117       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16118           << Decl->getName() << E->getSourceRange();
16119       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16120     } else {
16121       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16122           << E->getSourceRange();
16123     }
16124   }
16125   Rec.PossibleDerefs.clear();
16126 }
16127 
16128 /// Check whether E, which is either a discarded-value expression or an
16129 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16130 /// and if so, remove it from the list of volatile-qualified assignments that
16131 /// we are going to warn are deprecated.
16132 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16133   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16134     return;
16135 
16136   // Note: ignoring parens here is not justified by the standard rules, but
16137   // ignoring parentheses seems like a more reasonable approach, and this only
16138   // drives a deprecation warning so doesn't affect conformance.
16139   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16140     if (BO->getOpcode() == BO_Assign) {
16141       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16142       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16143                  LHSs.end());
16144     }
16145   }
16146 }
16147 
16148 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16149   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16150       RebuildingImmediateInvocation)
16151     return E;
16152 
16153   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16154   /// It's OK if this fails; we'll also remove this in
16155   /// HandleImmediateInvocations, but catching it here allows us to avoid
16156   /// walking the AST looking for it in simple cases.
16157   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16158     if (auto *DeclRef =
16159             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16160       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16161 
16162   E = MaybeCreateExprWithCleanups(E);
16163 
16164   ConstantExpr *Res = ConstantExpr::Create(
16165       getASTContext(), E.get(),
16166       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16167                                    getASTContext()),
16168       /*IsImmediateInvocation*/ true);
16169   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16170   return Res;
16171 }
16172 
16173 static void EvaluateAndDiagnoseImmediateInvocation(
16174     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16175   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16176   Expr::EvalResult Eval;
16177   Eval.Diag = &Notes;
16178   ConstantExpr *CE = Candidate.getPointer();
16179   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16180                                            SemaRef.getASTContext(), true);
16181   if (!Result || !Notes.empty()) {
16182     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16183     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16184       InnerExpr = FunctionalCast->getSubExpr();
16185     FunctionDecl *FD = nullptr;
16186     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16187       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16188     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16189       FD = Call->getConstructor();
16190     else
16191       llvm_unreachable("unhandled decl kind");
16192     assert(FD->isConsteval());
16193     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16194     for (auto &Note : Notes)
16195       SemaRef.Diag(Note.first, Note.second);
16196     return;
16197   }
16198   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16199 }
16200 
16201 static void RemoveNestedImmediateInvocation(
16202     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16203     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16204   struct ComplexRemove : TreeTransform<ComplexRemove> {
16205     using Base = TreeTransform<ComplexRemove>;
16206     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16207     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16208     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16209         CurrentII;
16210     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16211                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16212                   SmallVector<Sema::ImmediateInvocationCandidate,
16213                               4>::reverse_iterator Current)
16214         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16215     void RemoveImmediateInvocation(ConstantExpr* E) {
16216       auto It = std::find_if(CurrentII, IISet.rend(),
16217                              [E](Sema::ImmediateInvocationCandidate Elem) {
16218                                return Elem.getPointer() == E;
16219                              });
16220       assert(It != IISet.rend() &&
16221              "ConstantExpr marked IsImmediateInvocation should "
16222              "be present");
16223       It->setInt(1); // Mark as deleted
16224     }
16225     ExprResult TransformConstantExpr(ConstantExpr *E) {
16226       if (!E->isImmediateInvocation())
16227         return Base::TransformConstantExpr(E);
16228       RemoveImmediateInvocation(E);
16229       return Base::TransformExpr(E->getSubExpr());
16230     }
16231     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16232     /// we need to remove its DeclRefExpr from the DRSet.
16233     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16234       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16235       return Base::TransformCXXOperatorCallExpr(E);
16236     }
16237     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16238     /// here.
16239     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16240       if (!Init)
16241         return Init;
16242       /// ConstantExpr are the first layer of implicit node to be removed so if
16243       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16244       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16245         if (CE->isImmediateInvocation())
16246           RemoveImmediateInvocation(CE);
16247       return Base::TransformInitializer(Init, NotCopyInit);
16248     }
16249     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16250       DRSet.erase(E);
16251       return E;
16252     }
16253     bool AlwaysRebuild() { return false; }
16254     bool ReplacingOriginal() { return true; }
16255     bool AllowSkippingCXXConstructExpr() {
16256       bool Res = AllowSkippingFirstCXXConstructExpr;
16257       AllowSkippingFirstCXXConstructExpr = true;
16258       return Res;
16259     }
16260     bool AllowSkippingFirstCXXConstructExpr = true;
16261   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16262                 Rec.ImmediateInvocationCandidates, It);
16263 
16264   /// CXXConstructExpr with a single argument are getting skipped by
16265   /// TreeTransform in some situtation because they could be implicit. This
16266   /// can only occur for the top-level CXXConstructExpr because it is used
16267   /// nowhere in the expression being transformed therefore will not be rebuilt.
16268   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16269   /// skipping the first CXXConstructExpr.
16270   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16271     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16272 
16273   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16274   assert(Res.isUsable());
16275   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16276   It->getPointer()->setSubExpr(Res.get());
16277 }
16278 
16279 static void
16280 HandleImmediateInvocations(Sema &SemaRef,
16281                            Sema::ExpressionEvaluationContextRecord &Rec) {
16282   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16283        Rec.ReferenceToConsteval.size() == 0) ||
16284       SemaRef.RebuildingImmediateInvocation)
16285     return;
16286 
16287   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16288   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16289   /// need to remove ReferenceToConsteval in the immediate invocation.
16290   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16291 
16292     /// Prevent sema calls during the tree transform from adding pointers that
16293     /// are already in the sets.
16294     llvm::SaveAndRestore<bool> DisableIITracking(
16295         SemaRef.RebuildingImmediateInvocation, true);
16296 
16297     /// Prevent diagnostic during tree transfrom as they are duplicates
16298     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16299 
16300     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16301          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16302       if (!It->getInt())
16303         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16304   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16305              Rec.ReferenceToConsteval.size()) {
16306     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16307       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16308       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16309       bool VisitDeclRefExpr(DeclRefExpr *E) {
16310         DRSet.erase(E);
16311         return DRSet.size();
16312       }
16313     } Visitor(Rec.ReferenceToConsteval);
16314     Visitor.TraverseStmt(
16315         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16316   }
16317   for (auto CE : Rec.ImmediateInvocationCandidates)
16318     if (!CE.getInt())
16319       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16320   for (auto DR : Rec.ReferenceToConsteval) {
16321     auto *FD = cast<FunctionDecl>(DR->getDecl());
16322     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16323         << FD;
16324     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16325   }
16326 }
16327 
16328 void Sema::PopExpressionEvaluationContext() {
16329   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16330   unsigned NumTypos = Rec.NumTypos;
16331 
16332   if (!Rec.Lambdas.empty()) {
16333     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16334     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16335         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16336       unsigned D;
16337       if (Rec.isUnevaluated()) {
16338         // C++11 [expr.prim.lambda]p2:
16339         //   A lambda-expression shall not appear in an unevaluated operand
16340         //   (Clause 5).
16341         D = diag::err_lambda_unevaluated_operand;
16342       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16343         // C++1y [expr.const]p2:
16344         //   A conditional-expression e is a core constant expression unless the
16345         //   evaluation of e, following the rules of the abstract machine, would
16346         //   evaluate [...] a lambda-expression.
16347         D = diag::err_lambda_in_constant_expression;
16348       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16349         // C++17 [expr.prim.lamda]p2:
16350         // A lambda-expression shall not appear [...] in a template-argument.
16351         D = diag::err_lambda_in_invalid_context;
16352       } else
16353         llvm_unreachable("Couldn't infer lambda error message.");
16354 
16355       for (const auto *L : Rec.Lambdas)
16356         Diag(L->getBeginLoc(), D);
16357     }
16358   }
16359 
16360   WarnOnPendingNoDerefs(Rec);
16361   HandleImmediateInvocations(*this, Rec);
16362 
16363   // Warn on any volatile-qualified simple-assignments that are not discarded-
16364   // value expressions nor unevaluated operands (those cases get removed from
16365   // this list by CheckUnusedVolatileAssignment).
16366   for (auto *BO : Rec.VolatileAssignmentLHSs)
16367     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16368         << BO->getType();
16369 
16370   // When are coming out of an unevaluated context, clear out any
16371   // temporaries that we may have created as part of the evaluation of
16372   // the expression in that context: they aren't relevant because they
16373   // will never be constructed.
16374   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16375     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16376                              ExprCleanupObjects.end());
16377     Cleanup = Rec.ParentCleanup;
16378     CleanupVarDeclMarking();
16379     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16380   // Otherwise, merge the contexts together.
16381   } else {
16382     Cleanup.mergeFrom(Rec.ParentCleanup);
16383     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16384                             Rec.SavedMaybeODRUseExprs.end());
16385   }
16386 
16387   // Pop the current expression evaluation context off the stack.
16388   ExprEvalContexts.pop_back();
16389 
16390   // The global expression evaluation context record is never popped.
16391   ExprEvalContexts.back().NumTypos += NumTypos;
16392 }
16393 
16394 void Sema::DiscardCleanupsInEvaluationContext() {
16395   ExprCleanupObjects.erase(
16396          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16397          ExprCleanupObjects.end());
16398   Cleanup.reset();
16399   MaybeODRUseExprs.clear();
16400 }
16401 
16402 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16403   ExprResult Result = CheckPlaceholderExpr(E);
16404   if (Result.isInvalid())
16405     return ExprError();
16406   E = Result.get();
16407   if (!E->getType()->isVariablyModifiedType())
16408     return E;
16409   return TransformToPotentiallyEvaluated(E);
16410 }
16411 
16412 /// Are we in a context that is potentially constant evaluated per C++20
16413 /// [expr.const]p12?
16414 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16415   /// C++2a [expr.const]p12:
16416   //   An expression or conversion is potentially constant evaluated if it is
16417   switch (SemaRef.ExprEvalContexts.back().Context) {
16418     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16419       // -- a manifestly constant-evaluated expression,
16420     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16421     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16422     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16423       // -- a potentially-evaluated expression,
16424     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16425       // -- an immediate subexpression of a braced-init-list,
16426 
16427       // -- [FIXME] an expression of the form & cast-expression that occurs
16428       //    within a templated entity
16429       // -- a subexpression of one of the above that is not a subexpression of
16430       // a nested unevaluated operand.
16431       return true;
16432 
16433     case Sema::ExpressionEvaluationContext::Unevaluated:
16434     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16435       // Expressions in this context are never evaluated.
16436       return false;
16437   }
16438   llvm_unreachable("Invalid context");
16439 }
16440 
16441 /// Return true if this function has a calling convention that requires mangling
16442 /// in the size of the parameter pack.
16443 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16444   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16445   // we don't need parameter type sizes.
16446   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16447   if (!TT.isOSWindows() || !TT.isX86())
16448     return false;
16449 
16450   // If this is C++ and this isn't an extern "C" function, parameters do not
16451   // need to be complete. In this case, C++ mangling will apply, which doesn't
16452   // use the size of the parameters.
16453   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16454     return false;
16455 
16456   // Stdcall, fastcall, and vectorcall need this special treatment.
16457   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16458   switch (CC) {
16459   case CC_X86StdCall:
16460   case CC_X86FastCall:
16461   case CC_X86VectorCall:
16462     return true;
16463   default:
16464     break;
16465   }
16466   return false;
16467 }
16468 
16469 /// Require that all of the parameter types of function be complete. Normally,
16470 /// parameter types are only required to be complete when a function is called
16471 /// or defined, but to mangle functions with certain calling conventions, the
16472 /// mangler needs to know the size of the parameter list. In this situation,
16473 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16474 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16475 /// result in a linker error. Clang doesn't implement this behavior, and instead
16476 /// attempts to error at compile time.
16477 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16478                                                   SourceLocation Loc) {
16479   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16480     FunctionDecl *FD;
16481     ParmVarDecl *Param;
16482 
16483   public:
16484     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16485         : FD(FD), Param(Param) {}
16486 
16487     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16488       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16489       StringRef CCName;
16490       switch (CC) {
16491       case CC_X86StdCall:
16492         CCName = "stdcall";
16493         break;
16494       case CC_X86FastCall:
16495         CCName = "fastcall";
16496         break;
16497       case CC_X86VectorCall:
16498         CCName = "vectorcall";
16499         break;
16500       default:
16501         llvm_unreachable("CC does not need mangling");
16502       }
16503 
16504       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16505           << Param->getDeclName() << FD->getDeclName() << CCName;
16506     }
16507   };
16508 
16509   for (ParmVarDecl *Param : FD->parameters()) {
16510     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16511     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16512   }
16513 }
16514 
16515 namespace {
16516 enum class OdrUseContext {
16517   /// Declarations in this context are not odr-used.
16518   None,
16519   /// Declarations in this context are formally odr-used, but this is a
16520   /// dependent context.
16521   Dependent,
16522   /// Declarations in this context are odr-used but not actually used (yet).
16523   FormallyOdrUsed,
16524   /// Declarations in this context are used.
16525   Used
16526 };
16527 }
16528 
16529 /// Are we within a context in which references to resolved functions or to
16530 /// variables result in odr-use?
16531 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16532   OdrUseContext Result;
16533 
16534   switch (SemaRef.ExprEvalContexts.back().Context) {
16535     case Sema::ExpressionEvaluationContext::Unevaluated:
16536     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16537     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16538       return OdrUseContext::None;
16539 
16540     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16541     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16542       Result = OdrUseContext::Used;
16543       break;
16544 
16545     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16546       Result = OdrUseContext::FormallyOdrUsed;
16547       break;
16548 
16549     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16550       // A default argument formally results in odr-use, but doesn't actually
16551       // result in a use in any real sense until it itself is used.
16552       Result = OdrUseContext::FormallyOdrUsed;
16553       break;
16554   }
16555 
16556   if (SemaRef.CurContext->isDependentContext())
16557     return OdrUseContext::Dependent;
16558 
16559   return Result;
16560 }
16561 
16562 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16563   return Func->isConstexpr() &&
16564          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16565 }
16566 
16567 /// Mark a function referenced, and check whether it is odr-used
16568 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16569 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16570                                   bool MightBeOdrUse) {
16571   assert(Func && "No function?");
16572 
16573   Func->setReferenced();
16574 
16575   // Recursive functions aren't really used until they're used from some other
16576   // context.
16577   bool IsRecursiveCall = CurContext == Func;
16578 
16579   // C++11 [basic.def.odr]p3:
16580   //   A function whose name appears as a potentially-evaluated expression is
16581   //   odr-used if it is the unique lookup result or the selected member of a
16582   //   set of overloaded functions [...].
16583   //
16584   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16585   // can just check that here.
16586   OdrUseContext OdrUse =
16587       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16588   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16589     OdrUse = OdrUseContext::FormallyOdrUsed;
16590 
16591   // Trivial default constructors and destructors are never actually used.
16592   // FIXME: What about other special members?
16593   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16594       OdrUse == OdrUseContext::Used) {
16595     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16596       if (Constructor->isDefaultConstructor())
16597         OdrUse = OdrUseContext::FormallyOdrUsed;
16598     if (isa<CXXDestructorDecl>(Func))
16599       OdrUse = OdrUseContext::FormallyOdrUsed;
16600   }
16601 
16602   // C++20 [expr.const]p12:
16603   //   A function [...] is needed for constant evaluation if it is [...] a
16604   //   constexpr function that is named by an expression that is potentially
16605   //   constant evaluated
16606   bool NeededForConstantEvaluation =
16607       isPotentiallyConstantEvaluatedContext(*this) &&
16608       isImplicitlyDefinableConstexprFunction(Func);
16609 
16610   // Determine whether we require a function definition to exist, per
16611   // C++11 [temp.inst]p3:
16612   //   Unless a function template specialization has been explicitly
16613   //   instantiated or explicitly specialized, the function template
16614   //   specialization is implicitly instantiated when the specialization is
16615   //   referenced in a context that requires a function definition to exist.
16616   // C++20 [temp.inst]p7:
16617   //   The existence of a definition of a [...] function is considered to
16618   //   affect the semantics of the program if the [...] function is needed for
16619   //   constant evaluation by an expression
16620   // C++20 [basic.def.odr]p10:
16621   //   Every program shall contain exactly one definition of every non-inline
16622   //   function or variable that is odr-used in that program outside of a
16623   //   discarded statement
16624   // C++20 [special]p1:
16625   //   The implementation will implicitly define [defaulted special members]
16626   //   if they are odr-used or needed for constant evaluation.
16627   //
16628   // Note that we skip the implicit instantiation of templates that are only
16629   // used in unused default arguments or by recursive calls to themselves.
16630   // This is formally non-conforming, but seems reasonable in practice.
16631   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16632                                              NeededForConstantEvaluation);
16633 
16634   // C++14 [temp.expl.spec]p6:
16635   //   If a template [...] is explicitly specialized then that specialization
16636   //   shall be declared before the first use of that specialization that would
16637   //   cause an implicit instantiation to take place, in every translation unit
16638   //   in which such a use occurs
16639   if (NeedDefinition &&
16640       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16641        Func->getMemberSpecializationInfo()))
16642     checkSpecializationVisibility(Loc, Func);
16643 
16644   if (getLangOpts().CUDA)
16645     CheckCUDACall(Loc, Func);
16646 
16647   if (getLangOpts().SYCLIsDevice)
16648     checkSYCLDeviceFunction(Loc, Func);
16649 
16650   // If we need a definition, try to create one.
16651   if (NeedDefinition && !Func->getBody()) {
16652     runWithSufficientStackSpace(Loc, [&] {
16653       if (CXXConstructorDecl *Constructor =
16654               dyn_cast<CXXConstructorDecl>(Func)) {
16655         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16656         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16657           if (Constructor->isDefaultConstructor()) {
16658             if (Constructor->isTrivial() &&
16659                 !Constructor->hasAttr<DLLExportAttr>())
16660               return;
16661             DefineImplicitDefaultConstructor(Loc, Constructor);
16662           } else if (Constructor->isCopyConstructor()) {
16663             DefineImplicitCopyConstructor(Loc, Constructor);
16664           } else if (Constructor->isMoveConstructor()) {
16665             DefineImplicitMoveConstructor(Loc, Constructor);
16666           }
16667         } else if (Constructor->getInheritedConstructor()) {
16668           DefineInheritingConstructor(Loc, Constructor);
16669         }
16670       } else if (CXXDestructorDecl *Destructor =
16671                      dyn_cast<CXXDestructorDecl>(Func)) {
16672         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16673         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16674           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16675             return;
16676           DefineImplicitDestructor(Loc, Destructor);
16677         }
16678         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16679           MarkVTableUsed(Loc, Destructor->getParent());
16680       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16681         if (MethodDecl->isOverloadedOperator() &&
16682             MethodDecl->getOverloadedOperator() == OO_Equal) {
16683           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16684           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16685             if (MethodDecl->isCopyAssignmentOperator())
16686               DefineImplicitCopyAssignment(Loc, MethodDecl);
16687             else if (MethodDecl->isMoveAssignmentOperator())
16688               DefineImplicitMoveAssignment(Loc, MethodDecl);
16689           }
16690         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16691                    MethodDecl->getParent()->isLambda()) {
16692           CXXConversionDecl *Conversion =
16693               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16694           if (Conversion->isLambdaToBlockPointerConversion())
16695             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16696           else
16697             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16698         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16699           MarkVTableUsed(Loc, MethodDecl->getParent());
16700       }
16701 
16702       if (Func->isDefaulted() && !Func->isDeleted()) {
16703         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16704         if (DCK != DefaultedComparisonKind::None)
16705           DefineDefaultedComparison(Loc, Func, DCK);
16706       }
16707 
16708       // Implicit instantiation of function templates and member functions of
16709       // class templates.
16710       if (Func->isImplicitlyInstantiable()) {
16711         TemplateSpecializationKind TSK =
16712             Func->getTemplateSpecializationKindForInstantiation();
16713         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16714         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16715         if (FirstInstantiation) {
16716           PointOfInstantiation = Loc;
16717           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16718         } else if (TSK != TSK_ImplicitInstantiation) {
16719           // Use the point of use as the point of instantiation, instead of the
16720           // point of explicit instantiation (which we track as the actual point
16721           // of instantiation). This gives better backtraces in diagnostics.
16722           PointOfInstantiation = Loc;
16723         }
16724 
16725         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16726             Func->isConstexpr()) {
16727           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16728               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16729               CodeSynthesisContexts.size())
16730             PendingLocalImplicitInstantiations.push_back(
16731                 std::make_pair(Func, PointOfInstantiation));
16732           else if (Func->isConstexpr())
16733             // Do not defer instantiations of constexpr functions, to avoid the
16734             // expression evaluator needing to call back into Sema if it sees a
16735             // call to such a function.
16736             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16737           else {
16738             Func->setInstantiationIsPending(true);
16739             PendingInstantiations.push_back(
16740                 std::make_pair(Func, PointOfInstantiation));
16741             // Notify the consumer that a function was implicitly instantiated.
16742             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16743           }
16744         }
16745       } else {
16746         // Walk redefinitions, as some of them may be instantiable.
16747         for (auto i : Func->redecls()) {
16748           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16749             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16750         }
16751       }
16752     });
16753   }
16754 
16755   // C++14 [except.spec]p17:
16756   //   An exception-specification is considered to be needed when:
16757   //   - the function is odr-used or, if it appears in an unevaluated operand,
16758   //     would be odr-used if the expression were potentially-evaluated;
16759   //
16760   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16761   // function is a pure virtual function we're calling, and in that case the
16762   // function was selected by overload resolution and we need to resolve its
16763   // exception specification for a different reason.
16764   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16765   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16766     ResolveExceptionSpec(Loc, FPT);
16767 
16768   // If this is the first "real" use, act on that.
16769   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16770     // Keep track of used but undefined functions.
16771     if (!Func->isDefined()) {
16772       if (mightHaveNonExternalLinkage(Func))
16773         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16774       else if (Func->getMostRecentDecl()->isInlined() &&
16775                !LangOpts.GNUInline &&
16776                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16777         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16778       else if (isExternalWithNoLinkageType(Func))
16779         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16780     }
16781 
16782     // Some x86 Windows calling conventions mangle the size of the parameter
16783     // pack into the name. Computing the size of the parameters requires the
16784     // parameter types to be complete. Check that now.
16785     if (funcHasParameterSizeMangling(*this, Func))
16786       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16787 
16788     // In the MS C++ ABI, the compiler emits destructor variants where they are
16789     // used. If the destructor is used here but defined elsewhere, mark the
16790     // virtual base destructors referenced. If those virtual base destructors
16791     // are inline, this will ensure they are defined when emitting the complete
16792     // destructor variant. This checking may be redundant if the destructor is
16793     // provided later in this TU.
16794     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16795       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16796         CXXRecordDecl *Parent = Dtor->getParent();
16797         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16798           CheckCompleteDestructorVariant(Loc, Dtor);
16799       }
16800     }
16801 
16802     Func->markUsed(Context);
16803   }
16804 }
16805 
16806 /// Directly mark a variable odr-used. Given a choice, prefer to use
16807 /// MarkVariableReferenced since it does additional checks and then
16808 /// calls MarkVarDeclODRUsed.
16809 /// If the variable must be captured:
16810 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16811 ///  - else capture it in the DeclContext that maps to the
16812 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16813 static void
16814 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16815                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16816   // Keep track of used but undefined variables.
16817   // FIXME: We shouldn't suppress this warning for static data members.
16818   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16819       (!Var->isExternallyVisible() || Var->isInline() ||
16820        SemaRef.isExternalWithNoLinkageType(Var)) &&
16821       !(Var->isStaticDataMember() && Var->hasInit())) {
16822     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16823     if (old.isInvalid())
16824       old = Loc;
16825   }
16826   QualType CaptureType, DeclRefType;
16827   if (SemaRef.LangOpts.OpenMP)
16828     SemaRef.tryCaptureOpenMPLambdas(Var);
16829   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16830     /*EllipsisLoc*/ SourceLocation(),
16831     /*BuildAndDiagnose*/ true,
16832     CaptureType, DeclRefType,
16833     FunctionScopeIndexToStopAt);
16834 
16835   Var->markUsed(SemaRef.Context);
16836 }
16837 
16838 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16839                                              SourceLocation Loc,
16840                                              unsigned CapturingScopeIndex) {
16841   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16842 }
16843 
16844 static void
16845 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16846                                    ValueDecl *var, DeclContext *DC) {
16847   DeclContext *VarDC = var->getDeclContext();
16848 
16849   //  If the parameter still belongs to the translation unit, then
16850   //  we're actually just using one parameter in the declaration of
16851   //  the next.
16852   if (isa<ParmVarDecl>(var) &&
16853       isa<TranslationUnitDecl>(VarDC))
16854     return;
16855 
16856   // For C code, don't diagnose about capture if we're not actually in code
16857   // right now; it's impossible to write a non-constant expression outside of
16858   // function context, so we'll get other (more useful) diagnostics later.
16859   //
16860   // For C++, things get a bit more nasty... it would be nice to suppress this
16861   // diagnostic for certain cases like using a local variable in an array bound
16862   // for a member of a local class, but the correct predicate is not obvious.
16863   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16864     return;
16865 
16866   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16867   unsigned ContextKind = 3; // unknown
16868   if (isa<CXXMethodDecl>(VarDC) &&
16869       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16870     ContextKind = 2;
16871   } else if (isa<FunctionDecl>(VarDC)) {
16872     ContextKind = 0;
16873   } else if (isa<BlockDecl>(VarDC)) {
16874     ContextKind = 1;
16875   }
16876 
16877   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16878     << var << ValueKind << ContextKind << VarDC;
16879   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16880       << var;
16881 
16882   // FIXME: Add additional diagnostic info about class etc. which prevents
16883   // capture.
16884 }
16885 
16886 
16887 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16888                                       bool &SubCapturesAreNested,
16889                                       QualType &CaptureType,
16890                                       QualType &DeclRefType) {
16891    // Check whether we've already captured it.
16892   if (CSI->CaptureMap.count(Var)) {
16893     // If we found a capture, any subcaptures are nested.
16894     SubCapturesAreNested = true;
16895 
16896     // Retrieve the capture type for this variable.
16897     CaptureType = CSI->getCapture(Var).getCaptureType();
16898 
16899     // Compute the type of an expression that refers to this variable.
16900     DeclRefType = CaptureType.getNonReferenceType();
16901 
16902     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16903     // are mutable in the sense that user can change their value - they are
16904     // private instances of the captured declarations.
16905     const Capture &Cap = CSI->getCapture(Var);
16906     if (Cap.isCopyCapture() &&
16907         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16908         !(isa<CapturedRegionScopeInfo>(CSI) &&
16909           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16910       DeclRefType.addConst();
16911     return true;
16912   }
16913   return false;
16914 }
16915 
16916 // Only block literals, captured statements, and lambda expressions can
16917 // capture; other scopes don't work.
16918 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16919                                  SourceLocation Loc,
16920                                  const bool Diagnose, Sema &S) {
16921   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16922     return getLambdaAwareParentOfDeclContext(DC);
16923   else if (Var->hasLocalStorage()) {
16924     if (Diagnose)
16925        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16926   }
16927   return nullptr;
16928 }
16929 
16930 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16931 // certain types of variables (unnamed, variably modified types etc.)
16932 // so check for eligibility.
16933 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16934                                  SourceLocation Loc,
16935                                  const bool Diagnose, Sema &S) {
16936 
16937   bool IsBlock = isa<BlockScopeInfo>(CSI);
16938   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16939 
16940   // Lambdas are not allowed to capture unnamed variables
16941   // (e.g. anonymous unions).
16942   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16943   // assuming that's the intent.
16944   if (IsLambda && !Var->getDeclName()) {
16945     if (Diagnose) {
16946       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16947       S.Diag(Var->getLocation(), diag::note_declared_at);
16948     }
16949     return false;
16950   }
16951 
16952   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16953   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16954     if (Diagnose) {
16955       S.Diag(Loc, diag::err_ref_vm_type);
16956       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16957     }
16958     return false;
16959   }
16960   // Prohibit structs with flexible array members too.
16961   // We cannot capture what is in the tail end of the struct.
16962   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16963     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16964       if (Diagnose) {
16965         if (IsBlock)
16966           S.Diag(Loc, diag::err_ref_flexarray_type);
16967         else
16968           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16969         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16970       }
16971       return false;
16972     }
16973   }
16974   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16975   // Lambdas and captured statements are not allowed to capture __block
16976   // variables; they don't support the expected semantics.
16977   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16978     if (Diagnose) {
16979       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
16980       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16981     }
16982     return false;
16983   }
16984   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16985   if (S.getLangOpts().OpenCL && IsBlock &&
16986       Var->getType()->isBlockPointerType()) {
16987     if (Diagnose)
16988       S.Diag(Loc, diag::err_opencl_block_ref_block);
16989     return false;
16990   }
16991 
16992   return true;
16993 }
16994 
16995 // Returns true if the capture by block was successful.
16996 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16997                                  SourceLocation Loc,
16998                                  const bool BuildAndDiagnose,
16999                                  QualType &CaptureType,
17000                                  QualType &DeclRefType,
17001                                  const bool Nested,
17002                                  Sema &S, bool Invalid) {
17003   bool ByRef = false;
17004 
17005   // Blocks are not allowed to capture arrays, excepting OpenCL.
17006   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17007   // (decayed to pointers).
17008   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17009     if (BuildAndDiagnose) {
17010       S.Diag(Loc, diag::err_ref_array_type);
17011       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17012       Invalid = true;
17013     } else {
17014       return false;
17015     }
17016   }
17017 
17018   // Forbid the block-capture of autoreleasing variables.
17019   if (!Invalid &&
17020       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17021     if (BuildAndDiagnose) {
17022       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17023         << /*block*/ 0;
17024       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17025       Invalid = true;
17026     } else {
17027       return false;
17028     }
17029   }
17030 
17031   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17032   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17033     QualType PointeeTy = PT->getPointeeType();
17034 
17035     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17036         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17037         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17038       if (BuildAndDiagnose) {
17039         SourceLocation VarLoc = Var->getLocation();
17040         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17041         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17042       }
17043     }
17044   }
17045 
17046   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17047   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17048       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17049     // Block capture by reference does not change the capture or
17050     // declaration reference types.
17051     ByRef = true;
17052   } else {
17053     // Block capture by copy introduces 'const'.
17054     CaptureType = CaptureType.getNonReferenceType().withConst();
17055     DeclRefType = CaptureType;
17056   }
17057 
17058   // Actually capture the variable.
17059   if (BuildAndDiagnose)
17060     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17061                     CaptureType, Invalid);
17062 
17063   return !Invalid;
17064 }
17065 
17066 
17067 /// Capture the given variable in the captured region.
17068 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17069                                     VarDecl *Var,
17070                                     SourceLocation Loc,
17071                                     const bool BuildAndDiagnose,
17072                                     QualType &CaptureType,
17073                                     QualType &DeclRefType,
17074                                     const bool RefersToCapturedVariable,
17075                                     Sema &S, bool Invalid) {
17076   // By default, capture variables by reference.
17077   bool ByRef = true;
17078   // Using an LValue reference type is consistent with Lambdas (see below).
17079   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17080     if (S.isOpenMPCapturedDecl(Var)) {
17081       bool HasConst = DeclRefType.isConstQualified();
17082       DeclRefType = DeclRefType.getUnqualifiedType();
17083       // Don't lose diagnostics about assignments to const.
17084       if (HasConst)
17085         DeclRefType.addConst();
17086     }
17087     // Do not capture firstprivates in tasks.
17088     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17089         OMPC_unknown)
17090       return true;
17091     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17092                                     RSI->OpenMPCaptureLevel);
17093   }
17094 
17095   if (ByRef)
17096     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17097   else
17098     CaptureType = DeclRefType;
17099 
17100   // Actually capture the variable.
17101   if (BuildAndDiagnose)
17102     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17103                     Loc, SourceLocation(), CaptureType, Invalid);
17104 
17105   return !Invalid;
17106 }
17107 
17108 /// Capture the given variable in the lambda.
17109 static bool captureInLambda(LambdaScopeInfo *LSI,
17110                             VarDecl *Var,
17111                             SourceLocation Loc,
17112                             const bool BuildAndDiagnose,
17113                             QualType &CaptureType,
17114                             QualType &DeclRefType,
17115                             const bool RefersToCapturedVariable,
17116                             const Sema::TryCaptureKind Kind,
17117                             SourceLocation EllipsisLoc,
17118                             const bool IsTopScope,
17119                             Sema &S, bool Invalid) {
17120   // Determine whether we are capturing by reference or by value.
17121   bool ByRef = false;
17122   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17123     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17124   } else {
17125     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17126   }
17127 
17128   // Compute the type of the field that will capture this variable.
17129   if (ByRef) {
17130     // C++11 [expr.prim.lambda]p15:
17131     //   An entity is captured by reference if it is implicitly or
17132     //   explicitly captured but not captured by copy. It is
17133     //   unspecified whether additional unnamed non-static data
17134     //   members are declared in the closure type for entities
17135     //   captured by reference.
17136     //
17137     // FIXME: It is not clear whether we want to build an lvalue reference
17138     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17139     // to do the former, while EDG does the latter. Core issue 1249 will
17140     // clarify, but for now we follow GCC because it's a more permissive and
17141     // easily defensible position.
17142     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17143   } else {
17144     // C++11 [expr.prim.lambda]p14:
17145     //   For each entity captured by copy, an unnamed non-static
17146     //   data member is declared in the closure type. The
17147     //   declaration order of these members is unspecified. The type
17148     //   of such a data member is the type of the corresponding
17149     //   captured entity if the entity is not a reference to an
17150     //   object, or the referenced type otherwise. [Note: If the
17151     //   captured entity is a reference to a function, the
17152     //   corresponding data member is also a reference to a
17153     //   function. - end note ]
17154     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17155       if (!RefType->getPointeeType()->isFunctionType())
17156         CaptureType = RefType->getPointeeType();
17157     }
17158 
17159     // Forbid the lambda copy-capture of autoreleasing variables.
17160     if (!Invalid &&
17161         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17162       if (BuildAndDiagnose) {
17163         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17164         S.Diag(Var->getLocation(), diag::note_previous_decl)
17165           << Var->getDeclName();
17166         Invalid = true;
17167       } else {
17168         return false;
17169       }
17170     }
17171 
17172     // Make sure that by-copy captures are of a complete and non-abstract type.
17173     if (!Invalid && BuildAndDiagnose) {
17174       if (!CaptureType->isDependentType() &&
17175           S.RequireCompleteSizedType(
17176               Loc, CaptureType,
17177               diag::err_capture_of_incomplete_or_sizeless_type,
17178               Var->getDeclName()))
17179         Invalid = true;
17180       else if (S.RequireNonAbstractType(Loc, CaptureType,
17181                                         diag::err_capture_of_abstract_type))
17182         Invalid = true;
17183     }
17184   }
17185 
17186   // Compute the type of a reference to this captured variable.
17187   if (ByRef)
17188     DeclRefType = CaptureType.getNonReferenceType();
17189   else {
17190     // C++ [expr.prim.lambda]p5:
17191     //   The closure type for a lambda-expression has a public inline
17192     //   function call operator [...]. This function call operator is
17193     //   declared const (9.3.1) if and only if the lambda-expression's
17194     //   parameter-declaration-clause is not followed by mutable.
17195     DeclRefType = CaptureType.getNonReferenceType();
17196     if (!LSI->Mutable && !CaptureType->isReferenceType())
17197       DeclRefType.addConst();
17198   }
17199 
17200   // Add the capture.
17201   if (BuildAndDiagnose)
17202     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17203                     Loc, EllipsisLoc, CaptureType, Invalid);
17204 
17205   return !Invalid;
17206 }
17207 
17208 bool Sema::tryCaptureVariable(
17209     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17210     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17211     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17212   // An init-capture is notionally from the context surrounding its
17213   // declaration, but its parent DC is the lambda class.
17214   DeclContext *VarDC = Var->getDeclContext();
17215   if (Var->isInitCapture())
17216     VarDC = VarDC->getParent();
17217 
17218   DeclContext *DC = CurContext;
17219   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17220       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17221   // We need to sync up the Declaration Context with the
17222   // FunctionScopeIndexToStopAt
17223   if (FunctionScopeIndexToStopAt) {
17224     unsigned FSIndex = FunctionScopes.size() - 1;
17225     while (FSIndex != MaxFunctionScopesIndex) {
17226       DC = getLambdaAwareParentOfDeclContext(DC);
17227       --FSIndex;
17228     }
17229   }
17230 
17231 
17232   // If the variable is declared in the current context, there is no need to
17233   // capture it.
17234   if (VarDC == DC) return true;
17235 
17236   // Capture global variables if it is required to use private copy of this
17237   // variable.
17238   bool IsGlobal = !Var->hasLocalStorage();
17239   if (IsGlobal &&
17240       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17241                                                 MaxFunctionScopesIndex)))
17242     return true;
17243   Var = Var->getCanonicalDecl();
17244 
17245   // Walk up the stack to determine whether we can capture the variable,
17246   // performing the "simple" checks that don't depend on type. We stop when
17247   // we've either hit the declared scope of the variable or find an existing
17248   // capture of that variable.  We start from the innermost capturing-entity
17249   // (the DC) and ensure that all intervening capturing-entities
17250   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17251   // declcontext can either capture the variable or have already captured
17252   // the variable.
17253   CaptureType = Var->getType();
17254   DeclRefType = CaptureType.getNonReferenceType();
17255   bool Nested = false;
17256   bool Explicit = (Kind != TryCapture_Implicit);
17257   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17258   do {
17259     // Only block literals, captured statements, and lambda expressions can
17260     // capture; other scopes don't work.
17261     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17262                                                               ExprLoc,
17263                                                               BuildAndDiagnose,
17264                                                               *this);
17265     // We need to check for the parent *first* because, if we *have*
17266     // private-captured a global variable, we need to recursively capture it in
17267     // intermediate blocks, lambdas, etc.
17268     if (!ParentDC) {
17269       if (IsGlobal) {
17270         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17271         break;
17272       }
17273       return true;
17274     }
17275 
17276     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17277     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17278 
17279 
17280     // Check whether we've already captured it.
17281     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17282                                              DeclRefType)) {
17283       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17284       break;
17285     }
17286     // If we are instantiating a generic lambda call operator body,
17287     // we do not want to capture new variables.  What was captured
17288     // during either a lambdas transformation or initial parsing
17289     // should be used.
17290     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17291       if (BuildAndDiagnose) {
17292         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17293         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17294           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17295           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17296           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17297         } else
17298           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17299       }
17300       return true;
17301     }
17302 
17303     // Try to capture variable-length arrays types.
17304     if (Var->getType()->isVariablyModifiedType()) {
17305       // We're going to walk down into the type and look for VLA
17306       // expressions.
17307       QualType QTy = Var->getType();
17308       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17309         QTy = PVD->getOriginalType();
17310       captureVariablyModifiedType(Context, QTy, CSI);
17311     }
17312 
17313     if (getLangOpts().OpenMP) {
17314       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17315         // OpenMP private variables should not be captured in outer scope, so
17316         // just break here. Similarly, global variables that are captured in a
17317         // target region should not be captured outside the scope of the region.
17318         if (RSI->CapRegionKind == CR_OpenMP) {
17319           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17320               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17321           // If the variable is private (i.e. not captured) and has variably
17322           // modified type, we still need to capture the type for correct
17323           // codegen in all regions, associated with the construct. Currently,
17324           // it is captured in the innermost captured region only.
17325           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17326               Var->getType()->isVariablyModifiedType()) {
17327             QualType QTy = Var->getType();
17328             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17329               QTy = PVD->getOriginalType();
17330             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17331                  I < E; ++I) {
17332               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17333                   FunctionScopes[FunctionScopesIndex - I]);
17334               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17335                      "Wrong number of captured regions associated with the "
17336                      "OpenMP construct.");
17337               captureVariablyModifiedType(Context, QTy, OuterRSI);
17338             }
17339           }
17340           bool IsTargetCap =
17341               IsOpenMPPrivateDecl != OMPC_private &&
17342               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17343                                          RSI->OpenMPCaptureLevel);
17344           // Do not capture global if it is not privatized in outer regions.
17345           bool IsGlobalCap =
17346               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17347                                                      RSI->OpenMPCaptureLevel);
17348 
17349           // When we detect target captures we are looking from inside the
17350           // target region, therefore we need to propagate the capture from the
17351           // enclosing region. Therefore, the capture is not initially nested.
17352           if (IsTargetCap)
17353             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17354 
17355           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17356               (IsGlobal && !IsGlobalCap)) {
17357             Nested = !IsTargetCap;
17358             DeclRefType = DeclRefType.getUnqualifiedType();
17359             CaptureType = Context.getLValueReferenceType(DeclRefType);
17360             break;
17361           }
17362         }
17363       }
17364     }
17365     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17366       // No capture-default, and this is not an explicit capture
17367       // so cannot capture this variable.
17368       if (BuildAndDiagnose) {
17369         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17370         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17371         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17372           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17373                diag::note_lambda_decl);
17374         // FIXME: If we error out because an outer lambda can not implicitly
17375         // capture a variable that an inner lambda explicitly captures, we
17376         // should have the inner lambda do the explicit capture - because
17377         // it makes for cleaner diagnostics later.  This would purely be done
17378         // so that the diagnostic does not misleadingly claim that a variable
17379         // can not be captured by a lambda implicitly even though it is captured
17380         // explicitly.  Suggestion:
17381         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17382         //    at the function head
17383         //  - cache the StartingDeclContext - this must be a lambda
17384         //  - captureInLambda in the innermost lambda the variable.
17385       }
17386       return true;
17387     }
17388 
17389     FunctionScopesIndex--;
17390     DC = ParentDC;
17391     Explicit = false;
17392   } while (!VarDC->Equals(DC));
17393 
17394   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17395   // computing the type of the capture at each step, checking type-specific
17396   // requirements, and adding captures if requested.
17397   // If the variable had already been captured previously, we start capturing
17398   // at the lambda nested within that one.
17399   bool Invalid = false;
17400   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17401        ++I) {
17402     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17403 
17404     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17405     // certain types of variables (unnamed, variably modified types etc.)
17406     // so check for eligibility.
17407     if (!Invalid)
17408       Invalid =
17409           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17410 
17411     // After encountering an error, if we're actually supposed to capture, keep
17412     // capturing in nested contexts to suppress any follow-on diagnostics.
17413     if (Invalid && !BuildAndDiagnose)
17414       return true;
17415 
17416     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17417       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17418                                DeclRefType, Nested, *this, Invalid);
17419       Nested = true;
17420     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17421       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17422                                          CaptureType, DeclRefType, Nested,
17423                                          *this, Invalid);
17424       Nested = true;
17425     } else {
17426       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17427       Invalid =
17428           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17429                            DeclRefType, Nested, Kind, EllipsisLoc,
17430                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17431       Nested = true;
17432     }
17433 
17434     if (Invalid && !BuildAndDiagnose)
17435       return true;
17436   }
17437   return Invalid;
17438 }
17439 
17440 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17441                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17442   QualType CaptureType;
17443   QualType DeclRefType;
17444   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17445                             /*BuildAndDiagnose=*/true, CaptureType,
17446                             DeclRefType, nullptr);
17447 }
17448 
17449 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17450   QualType CaptureType;
17451   QualType DeclRefType;
17452   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17453                              /*BuildAndDiagnose=*/false, CaptureType,
17454                              DeclRefType, nullptr);
17455 }
17456 
17457 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17458   QualType CaptureType;
17459   QualType DeclRefType;
17460 
17461   // Determine whether we can capture this variable.
17462   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17463                          /*BuildAndDiagnose=*/false, CaptureType,
17464                          DeclRefType, nullptr))
17465     return QualType();
17466 
17467   return DeclRefType;
17468 }
17469 
17470 namespace {
17471 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17472 // The produced TemplateArgumentListInfo* points to data stored within this
17473 // object, so should only be used in contexts where the pointer will not be
17474 // used after the CopiedTemplateArgs object is destroyed.
17475 class CopiedTemplateArgs {
17476   bool HasArgs;
17477   TemplateArgumentListInfo TemplateArgStorage;
17478 public:
17479   template<typename RefExpr>
17480   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17481     if (HasArgs)
17482       E->copyTemplateArgumentsInto(TemplateArgStorage);
17483   }
17484   operator TemplateArgumentListInfo*()
17485 #ifdef __has_cpp_attribute
17486 #if __has_cpp_attribute(clang::lifetimebound)
17487   [[clang::lifetimebound]]
17488 #endif
17489 #endif
17490   {
17491     return HasArgs ? &TemplateArgStorage : nullptr;
17492   }
17493 };
17494 }
17495 
17496 /// Walk the set of potential results of an expression and mark them all as
17497 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17498 ///
17499 /// \return A new expression if we found any potential results, ExprEmpty() if
17500 ///         not, and ExprError() if we diagnosed an error.
17501 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17502                                                       NonOdrUseReason NOUR) {
17503   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17504   // an object that satisfies the requirements for appearing in a
17505   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17506   // is immediately applied."  This function handles the lvalue-to-rvalue
17507   // conversion part.
17508   //
17509   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17510   // transform it into the relevant kind of non-odr-use node and rebuild the
17511   // tree of nodes leading to it.
17512   //
17513   // This is a mini-TreeTransform that only transforms a restricted subset of
17514   // nodes (and only certain operands of them).
17515 
17516   // Rebuild a subexpression.
17517   auto Rebuild = [&](Expr *Sub) {
17518     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17519   };
17520 
17521   // Check whether a potential result satisfies the requirements of NOUR.
17522   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17523     // Any entity other than a VarDecl is always odr-used whenever it's named
17524     // in a potentially-evaluated expression.
17525     auto *VD = dyn_cast<VarDecl>(D);
17526     if (!VD)
17527       return true;
17528 
17529     // C++2a [basic.def.odr]p4:
17530     //   A variable x whose name appears as a potentially-evalauted expression
17531     //   e is odr-used by e unless
17532     //   -- x is a reference that is usable in constant expressions, or
17533     //   -- x is a variable of non-reference type that is usable in constant
17534     //      expressions and has no mutable subobjects, and e is an element of
17535     //      the set of potential results of an expression of
17536     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17537     //      conversion is applied, or
17538     //   -- x is a variable of non-reference type, and e is an element of the
17539     //      set of potential results of a discarded-value expression to which
17540     //      the lvalue-to-rvalue conversion is not applied
17541     //
17542     // We check the first bullet and the "potentially-evaluated" condition in
17543     // BuildDeclRefExpr. We check the type requirements in the second bullet
17544     // in CheckLValueToRValueConversionOperand below.
17545     switch (NOUR) {
17546     case NOUR_None:
17547     case NOUR_Unevaluated:
17548       llvm_unreachable("unexpected non-odr-use-reason");
17549 
17550     case NOUR_Constant:
17551       // Constant references were handled when they were built.
17552       if (VD->getType()->isReferenceType())
17553         return true;
17554       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17555         if (RD->hasMutableFields())
17556           return true;
17557       if (!VD->isUsableInConstantExpressions(S.Context))
17558         return true;
17559       break;
17560 
17561     case NOUR_Discarded:
17562       if (VD->getType()->isReferenceType())
17563         return true;
17564       break;
17565     }
17566     return false;
17567   };
17568 
17569   // Mark that this expression does not constitute an odr-use.
17570   auto MarkNotOdrUsed = [&] {
17571     S.MaybeODRUseExprs.remove(E);
17572     if (LambdaScopeInfo *LSI = S.getCurLambda())
17573       LSI->markVariableExprAsNonODRUsed(E);
17574   };
17575 
17576   // C++2a [basic.def.odr]p2:
17577   //   The set of potential results of an expression e is defined as follows:
17578   switch (E->getStmtClass()) {
17579   //   -- If e is an id-expression, ...
17580   case Expr::DeclRefExprClass: {
17581     auto *DRE = cast<DeclRefExpr>(E);
17582     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17583       break;
17584 
17585     // Rebuild as a non-odr-use DeclRefExpr.
17586     MarkNotOdrUsed();
17587     return DeclRefExpr::Create(
17588         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17589         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17590         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17591         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17592   }
17593 
17594   case Expr::FunctionParmPackExprClass: {
17595     auto *FPPE = cast<FunctionParmPackExpr>(E);
17596     // If any of the declarations in the pack is odr-used, then the expression
17597     // as a whole constitutes an odr-use.
17598     for (VarDecl *D : *FPPE)
17599       if (IsPotentialResultOdrUsed(D))
17600         return ExprEmpty();
17601 
17602     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17603     // nothing cares about whether we marked this as an odr-use, but it might
17604     // be useful for non-compiler tools.
17605     MarkNotOdrUsed();
17606     break;
17607   }
17608 
17609   //   -- If e is a subscripting operation with an array operand...
17610   case Expr::ArraySubscriptExprClass: {
17611     auto *ASE = cast<ArraySubscriptExpr>(E);
17612     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17613     if (!OldBase->getType()->isArrayType())
17614       break;
17615     ExprResult Base = Rebuild(OldBase);
17616     if (!Base.isUsable())
17617       return Base;
17618     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17619     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17620     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17621     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17622                                      ASE->getRBracketLoc());
17623   }
17624 
17625   case Expr::MemberExprClass: {
17626     auto *ME = cast<MemberExpr>(E);
17627     // -- If e is a class member access expression [...] naming a non-static
17628     //    data member...
17629     if (isa<FieldDecl>(ME->getMemberDecl())) {
17630       ExprResult Base = Rebuild(ME->getBase());
17631       if (!Base.isUsable())
17632         return Base;
17633       return MemberExpr::Create(
17634           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17635           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17636           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17637           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17638           ME->getObjectKind(), ME->isNonOdrUse());
17639     }
17640 
17641     if (ME->getMemberDecl()->isCXXInstanceMember())
17642       break;
17643 
17644     // -- If e is a class member access expression naming a static data member,
17645     //    ...
17646     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17647       break;
17648 
17649     // Rebuild as a non-odr-use MemberExpr.
17650     MarkNotOdrUsed();
17651     return MemberExpr::Create(
17652         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17653         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17654         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17655         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17656     return ExprEmpty();
17657   }
17658 
17659   case Expr::BinaryOperatorClass: {
17660     auto *BO = cast<BinaryOperator>(E);
17661     Expr *LHS = BO->getLHS();
17662     Expr *RHS = BO->getRHS();
17663     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17664     if (BO->getOpcode() == BO_PtrMemD) {
17665       ExprResult Sub = Rebuild(LHS);
17666       if (!Sub.isUsable())
17667         return Sub;
17668       LHS = Sub.get();
17669     //   -- If e is a comma expression, ...
17670     } else if (BO->getOpcode() == BO_Comma) {
17671       ExprResult Sub = Rebuild(RHS);
17672       if (!Sub.isUsable())
17673         return Sub;
17674       RHS = Sub.get();
17675     } else {
17676       break;
17677     }
17678     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17679                         LHS, RHS);
17680   }
17681 
17682   //   -- If e has the form (e1)...
17683   case Expr::ParenExprClass: {
17684     auto *PE = cast<ParenExpr>(E);
17685     ExprResult Sub = Rebuild(PE->getSubExpr());
17686     if (!Sub.isUsable())
17687       return Sub;
17688     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17689   }
17690 
17691   //   -- If e is a glvalue conditional expression, ...
17692   // We don't apply this to a binary conditional operator. FIXME: Should we?
17693   case Expr::ConditionalOperatorClass: {
17694     auto *CO = cast<ConditionalOperator>(E);
17695     ExprResult LHS = Rebuild(CO->getLHS());
17696     if (LHS.isInvalid())
17697       return ExprError();
17698     ExprResult RHS = Rebuild(CO->getRHS());
17699     if (RHS.isInvalid())
17700       return ExprError();
17701     if (!LHS.isUsable() && !RHS.isUsable())
17702       return ExprEmpty();
17703     if (!LHS.isUsable())
17704       LHS = CO->getLHS();
17705     if (!RHS.isUsable())
17706       RHS = CO->getRHS();
17707     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17708                                 CO->getCond(), LHS.get(), RHS.get());
17709   }
17710 
17711   // [Clang extension]
17712   //   -- If e has the form __extension__ e1...
17713   case Expr::UnaryOperatorClass: {
17714     auto *UO = cast<UnaryOperator>(E);
17715     if (UO->getOpcode() != UO_Extension)
17716       break;
17717     ExprResult Sub = Rebuild(UO->getSubExpr());
17718     if (!Sub.isUsable())
17719       return Sub;
17720     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17721                           Sub.get());
17722   }
17723 
17724   // [Clang extension]
17725   //   -- If e has the form _Generic(...), the set of potential results is the
17726   //      union of the sets of potential results of the associated expressions.
17727   case Expr::GenericSelectionExprClass: {
17728     auto *GSE = cast<GenericSelectionExpr>(E);
17729 
17730     SmallVector<Expr *, 4> AssocExprs;
17731     bool AnyChanged = false;
17732     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17733       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17734       if (AssocExpr.isInvalid())
17735         return ExprError();
17736       if (AssocExpr.isUsable()) {
17737         AssocExprs.push_back(AssocExpr.get());
17738         AnyChanged = true;
17739       } else {
17740         AssocExprs.push_back(OrigAssocExpr);
17741       }
17742     }
17743 
17744     return AnyChanged ? S.CreateGenericSelectionExpr(
17745                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17746                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17747                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17748                       : ExprEmpty();
17749   }
17750 
17751   // [Clang extension]
17752   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17753   //      results is the union of the sets of potential results of the
17754   //      second and third subexpressions.
17755   case Expr::ChooseExprClass: {
17756     auto *CE = cast<ChooseExpr>(E);
17757 
17758     ExprResult LHS = Rebuild(CE->getLHS());
17759     if (LHS.isInvalid())
17760       return ExprError();
17761 
17762     ExprResult RHS = Rebuild(CE->getLHS());
17763     if (RHS.isInvalid())
17764       return ExprError();
17765 
17766     if (!LHS.get() && !RHS.get())
17767       return ExprEmpty();
17768     if (!LHS.isUsable())
17769       LHS = CE->getLHS();
17770     if (!RHS.isUsable())
17771       RHS = CE->getRHS();
17772 
17773     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17774                              RHS.get(), CE->getRParenLoc());
17775   }
17776 
17777   // Step through non-syntactic nodes.
17778   case Expr::ConstantExprClass: {
17779     auto *CE = cast<ConstantExpr>(E);
17780     ExprResult Sub = Rebuild(CE->getSubExpr());
17781     if (!Sub.isUsable())
17782       return Sub;
17783     return ConstantExpr::Create(S.Context, Sub.get());
17784   }
17785 
17786   // We could mostly rely on the recursive rebuilding to rebuild implicit
17787   // casts, but not at the top level, so rebuild them here.
17788   case Expr::ImplicitCastExprClass: {
17789     auto *ICE = cast<ImplicitCastExpr>(E);
17790     // Only step through the narrow set of cast kinds we expect to encounter.
17791     // Anything else suggests we've left the region in which potential results
17792     // can be found.
17793     switch (ICE->getCastKind()) {
17794     case CK_NoOp:
17795     case CK_DerivedToBase:
17796     case CK_UncheckedDerivedToBase: {
17797       ExprResult Sub = Rebuild(ICE->getSubExpr());
17798       if (!Sub.isUsable())
17799         return Sub;
17800       CXXCastPath Path(ICE->path());
17801       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17802                                  ICE->getValueKind(), &Path);
17803     }
17804 
17805     default:
17806       break;
17807     }
17808     break;
17809   }
17810 
17811   default:
17812     break;
17813   }
17814 
17815   // Can't traverse through this node. Nothing to do.
17816   return ExprEmpty();
17817 }
17818 
17819 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17820   // Check whether the operand is or contains an object of non-trivial C union
17821   // type.
17822   if (E->getType().isVolatileQualified() &&
17823       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17824        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17825     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17826                           Sema::NTCUC_LValueToRValueVolatile,
17827                           NTCUK_Destruct|NTCUK_Copy);
17828 
17829   // C++2a [basic.def.odr]p4:
17830   //   [...] an expression of non-volatile-qualified non-class type to which
17831   //   the lvalue-to-rvalue conversion is applied [...]
17832   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17833     return E;
17834 
17835   ExprResult Result =
17836       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17837   if (Result.isInvalid())
17838     return ExprError();
17839   return Result.get() ? Result : E;
17840 }
17841 
17842 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17843   Res = CorrectDelayedTyposInExpr(Res);
17844 
17845   if (!Res.isUsable())
17846     return Res;
17847 
17848   // If a constant-expression is a reference to a variable where we delay
17849   // deciding whether it is an odr-use, just assume we will apply the
17850   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17851   // (a non-type template argument), we have special handling anyway.
17852   return CheckLValueToRValueConversionOperand(Res.get());
17853 }
17854 
17855 void Sema::CleanupVarDeclMarking() {
17856   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17857   // call.
17858   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17859   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17860 
17861   for (Expr *E : LocalMaybeODRUseExprs) {
17862     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17863       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17864                          DRE->getLocation(), *this);
17865     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17866       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17867                          *this);
17868     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17869       for (VarDecl *VD : *FP)
17870         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17871     } else {
17872       llvm_unreachable("Unexpected expression");
17873     }
17874   }
17875 
17876   assert(MaybeODRUseExprs.empty() &&
17877          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17878 }
17879 
17880 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17881                                     VarDecl *Var, Expr *E) {
17882   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17883           isa<FunctionParmPackExpr>(E)) &&
17884          "Invalid Expr argument to DoMarkVarDeclReferenced");
17885   Var->setReferenced();
17886 
17887   if (Var->isInvalidDecl())
17888     return;
17889 
17890   // Record a CUDA/HIP static device/constant variable if it is referenced
17891   // by host code. This is done conservatively, when the variable is referenced
17892   // in any of the following contexts:
17893   //   - a non-function context
17894   //   - a host function
17895   //   - a host device function
17896   // This also requires the reference of the static device/constant variable by
17897   // host code to be visible in the device compilation for the compiler to be
17898   // able to externalize the static device/constant variable.
17899   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17900     auto *CurContext = SemaRef.CurContext;
17901     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17902         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17903         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17904          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17905       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17906   }
17907 
17908   auto *MSI = Var->getMemberSpecializationInfo();
17909   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17910                                        : Var->getTemplateSpecializationKind();
17911 
17912   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17913   bool UsableInConstantExpr =
17914       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17915 
17916   // C++20 [expr.const]p12:
17917   //   A variable [...] is needed for constant evaluation if it is [...] a
17918   //   variable whose name appears as a potentially constant evaluated
17919   //   expression that is either a contexpr variable or is of non-volatile
17920   //   const-qualified integral type or of reference type
17921   bool NeededForConstantEvaluation =
17922       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17923 
17924   bool NeedDefinition =
17925       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17926 
17927   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17928          "Can't instantiate a partial template specialization.");
17929 
17930   // If this might be a member specialization of a static data member, check
17931   // the specialization is visible. We already did the checks for variable
17932   // template specializations when we created them.
17933   if (NeedDefinition && TSK != TSK_Undeclared &&
17934       !isa<VarTemplateSpecializationDecl>(Var))
17935     SemaRef.checkSpecializationVisibility(Loc, Var);
17936 
17937   // Perform implicit instantiation of static data members, static data member
17938   // templates of class templates, and variable template specializations. Delay
17939   // instantiations of variable templates, except for those that could be used
17940   // in a constant expression.
17941   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17942     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17943     // instantiation declaration if a variable is usable in a constant
17944     // expression (among other cases).
17945     bool TryInstantiating =
17946         TSK == TSK_ImplicitInstantiation ||
17947         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17948 
17949     if (TryInstantiating) {
17950       SourceLocation PointOfInstantiation =
17951           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17952       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17953       if (FirstInstantiation) {
17954         PointOfInstantiation = Loc;
17955         if (MSI)
17956           MSI->setPointOfInstantiation(PointOfInstantiation);
17957         else
17958           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17959       }
17960 
17961       if (UsableInConstantExpr) {
17962         // Do not defer instantiations of variables that could be used in a
17963         // constant expression.
17964         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17965           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17966         });
17967       } else if (FirstInstantiation ||
17968                  isa<VarTemplateSpecializationDecl>(Var)) {
17969         // FIXME: For a specialization of a variable template, we don't
17970         // distinguish between "declaration and type implicitly instantiated"
17971         // and "implicit instantiation of definition requested", so we have
17972         // no direct way to avoid enqueueing the pending instantiation
17973         // multiple times.
17974         SemaRef.PendingInstantiations
17975             .push_back(std::make_pair(Var, PointOfInstantiation));
17976       }
17977     }
17978   }
17979 
17980   // C++2a [basic.def.odr]p4:
17981   //   A variable x whose name appears as a potentially-evaluated expression e
17982   //   is odr-used by e unless
17983   //   -- x is a reference that is usable in constant expressions
17984   //   -- x is a variable of non-reference type that is usable in constant
17985   //      expressions and has no mutable subobjects [FIXME], and e is an
17986   //      element of the set of potential results of an expression of
17987   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17988   //      conversion is applied
17989   //   -- x is a variable of non-reference type, and e is an element of the set
17990   //      of potential results of a discarded-value expression to which the
17991   //      lvalue-to-rvalue conversion is not applied [FIXME]
17992   //
17993   // We check the first part of the second bullet here, and
17994   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17995   // FIXME: To get the third bullet right, we need to delay this even for
17996   // variables that are not usable in constant expressions.
17997 
17998   // If we already know this isn't an odr-use, there's nothing more to do.
17999   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18000     if (DRE->isNonOdrUse())
18001       return;
18002   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18003     if (ME->isNonOdrUse())
18004       return;
18005 
18006   switch (OdrUse) {
18007   case OdrUseContext::None:
18008     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18009            "missing non-odr-use marking for unevaluated decl ref");
18010     break;
18011 
18012   case OdrUseContext::FormallyOdrUsed:
18013     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18014     // behavior.
18015     break;
18016 
18017   case OdrUseContext::Used:
18018     // If we might later find that this expression isn't actually an odr-use,
18019     // delay the marking.
18020     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18021       SemaRef.MaybeODRUseExprs.insert(E);
18022     else
18023       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18024     break;
18025 
18026   case OdrUseContext::Dependent:
18027     // If this is a dependent context, we don't need to mark variables as
18028     // odr-used, but we may still need to track them for lambda capture.
18029     // FIXME: Do we also need to do this inside dependent typeid expressions
18030     // (which are modeled as unevaluated at this point)?
18031     const bool RefersToEnclosingScope =
18032         (SemaRef.CurContext != Var->getDeclContext() &&
18033          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18034     if (RefersToEnclosingScope) {
18035       LambdaScopeInfo *const LSI =
18036           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18037       if (LSI && (!LSI->CallOperator ||
18038                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18039         // If a variable could potentially be odr-used, defer marking it so
18040         // until we finish analyzing the full expression for any
18041         // lvalue-to-rvalue
18042         // or discarded value conversions that would obviate odr-use.
18043         // Add it to the list of potential captures that will be analyzed
18044         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18045         // unless the variable is a reference that was initialized by a constant
18046         // expression (this will never need to be captured or odr-used).
18047         //
18048         // FIXME: We can simplify this a lot after implementing P0588R1.
18049         assert(E && "Capture variable should be used in an expression.");
18050         if (!Var->getType()->isReferenceType() ||
18051             !Var->isUsableInConstantExpressions(SemaRef.Context))
18052           LSI->addPotentialCapture(E->IgnoreParens());
18053       }
18054     }
18055     break;
18056   }
18057 }
18058 
18059 /// Mark a variable referenced, and check whether it is odr-used
18060 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18061 /// used directly for normal expressions referring to VarDecl.
18062 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18063   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18064 }
18065 
18066 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18067                                Decl *D, Expr *E, bool MightBeOdrUse) {
18068   if (SemaRef.isInOpenMPDeclareTargetContext())
18069     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18070 
18071   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18072     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18073     return;
18074   }
18075 
18076   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18077 
18078   // If this is a call to a method via a cast, also mark the method in the
18079   // derived class used in case codegen can devirtualize the call.
18080   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18081   if (!ME)
18082     return;
18083   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18084   if (!MD)
18085     return;
18086   // Only attempt to devirtualize if this is truly a virtual call.
18087   bool IsVirtualCall = MD->isVirtual() &&
18088                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18089   if (!IsVirtualCall)
18090     return;
18091 
18092   // If it's possible to devirtualize the call, mark the called function
18093   // referenced.
18094   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18095       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18096   if (DM)
18097     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18098 }
18099 
18100 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18101 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18102   // TODO: update this with DR# once a defect report is filed.
18103   // C++11 defect. The address of a pure member should not be an ODR use, even
18104   // if it's a qualified reference.
18105   bool OdrUse = true;
18106   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18107     if (Method->isVirtual() &&
18108         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18109       OdrUse = false;
18110 
18111   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18112     if (!isConstantEvaluated() && FD->isConsteval() &&
18113         !RebuildingImmediateInvocation)
18114       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18115   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18116 }
18117 
18118 /// Perform reference-marking and odr-use handling for a MemberExpr.
18119 void Sema::MarkMemberReferenced(MemberExpr *E) {
18120   // C++11 [basic.def.odr]p2:
18121   //   A non-overloaded function whose name appears as a potentially-evaluated
18122   //   expression or a member of a set of candidate functions, if selected by
18123   //   overload resolution when referred to from a potentially-evaluated
18124   //   expression, is odr-used, unless it is a pure virtual function and its
18125   //   name is not explicitly qualified.
18126   bool MightBeOdrUse = true;
18127   if (E->performsVirtualDispatch(getLangOpts())) {
18128     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18129       if (Method->isPure())
18130         MightBeOdrUse = false;
18131   }
18132   SourceLocation Loc =
18133       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18134   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18135 }
18136 
18137 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18138 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18139   for (VarDecl *VD : *E)
18140     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18141 }
18142 
18143 /// Perform marking for a reference to an arbitrary declaration.  It
18144 /// marks the declaration referenced, and performs odr-use checking for
18145 /// functions and variables. This method should not be used when building a
18146 /// normal expression which refers to a variable.
18147 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18148                                  bool MightBeOdrUse) {
18149   if (MightBeOdrUse) {
18150     if (auto *VD = dyn_cast<VarDecl>(D)) {
18151       MarkVariableReferenced(Loc, VD);
18152       return;
18153     }
18154   }
18155   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18156     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18157     return;
18158   }
18159   D->setReferenced();
18160 }
18161 
18162 namespace {
18163   // Mark all of the declarations used by a type as referenced.
18164   // FIXME: Not fully implemented yet! We need to have a better understanding
18165   // of when we're entering a context we should not recurse into.
18166   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18167   // TreeTransforms rebuilding the type in a new context. Rather than
18168   // duplicating the TreeTransform logic, we should consider reusing it here.
18169   // Currently that causes problems when rebuilding LambdaExprs.
18170   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18171     Sema &S;
18172     SourceLocation Loc;
18173 
18174   public:
18175     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18176 
18177     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18178 
18179     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18180   };
18181 }
18182 
18183 bool MarkReferencedDecls::TraverseTemplateArgument(
18184     const TemplateArgument &Arg) {
18185   {
18186     // A non-type template argument is a constant-evaluated context.
18187     EnterExpressionEvaluationContext Evaluated(
18188         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18189     if (Arg.getKind() == TemplateArgument::Declaration) {
18190       if (Decl *D = Arg.getAsDecl())
18191         S.MarkAnyDeclReferenced(Loc, D, true);
18192     } else if (Arg.getKind() == TemplateArgument::Expression) {
18193       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18194     }
18195   }
18196 
18197   return Inherited::TraverseTemplateArgument(Arg);
18198 }
18199 
18200 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18201   MarkReferencedDecls Marker(*this, Loc);
18202   Marker.TraverseType(T);
18203 }
18204 
18205 namespace {
18206 /// Helper class that marks all of the declarations referenced by
18207 /// potentially-evaluated subexpressions as "referenced".
18208 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18209 public:
18210   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18211   bool SkipLocalVariables;
18212 
18213   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18214       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18215 
18216   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18217     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18218   }
18219 
18220   void VisitDeclRefExpr(DeclRefExpr *E) {
18221     // If we were asked not to visit local variables, don't.
18222     if (SkipLocalVariables) {
18223       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18224         if (VD->hasLocalStorage())
18225           return;
18226     }
18227     S.MarkDeclRefReferenced(E);
18228   }
18229 
18230   void VisitMemberExpr(MemberExpr *E) {
18231     S.MarkMemberReferenced(E);
18232     Visit(E->getBase());
18233   }
18234 };
18235 } // namespace
18236 
18237 /// Mark any declarations that appear within this expression or any
18238 /// potentially-evaluated subexpressions as "referenced".
18239 ///
18240 /// \param SkipLocalVariables If true, don't mark local variables as
18241 /// 'referenced'.
18242 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18243                                             bool SkipLocalVariables) {
18244   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18245 }
18246 
18247 /// Emit a diagnostic that describes an effect on the run-time behavior
18248 /// of the program being compiled.
18249 ///
18250 /// This routine emits the given diagnostic when the code currently being
18251 /// type-checked is "potentially evaluated", meaning that there is a
18252 /// possibility that the code will actually be executable. Code in sizeof()
18253 /// expressions, code used only during overload resolution, etc., are not
18254 /// potentially evaluated. This routine will suppress such diagnostics or,
18255 /// in the absolutely nutty case of potentially potentially evaluated
18256 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18257 /// later.
18258 ///
18259 /// This routine should be used for all diagnostics that describe the run-time
18260 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18261 /// Failure to do so will likely result in spurious diagnostics or failures
18262 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18263 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18264                                const PartialDiagnostic &PD) {
18265   switch (ExprEvalContexts.back().Context) {
18266   case ExpressionEvaluationContext::Unevaluated:
18267   case ExpressionEvaluationContext::UnevaluatedList:
18268   case ExpressionEvaluationContext::UnevaluatedAbstract:
18269   case ExpressionEvaluationContext::DiscardedStatement:
18270     // The argument will never be evaluated, so don't complain.
18271     break;
18272 
18273   case ExpressionEvaluationContext::ConstantEvaluated:
18274     // Relevant diagnostics should be produced by constant evaluation.
18275     break;
18276 
18277   case ExpressionEvaluationContext::PotentiallyEvaluated:
18278   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18279     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18280       FunctionScopes.back()->PossiblyUnreachableDiags.
18281         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18282       return true;
18283     }
18284 
18285     // The initializer of a constexpr variable or of the first declaration of a
18286     // static data member is not syntactically a constant evaluated constant,
18287     // but nonetheless is always required to be a constant expression, so we
18288     // can skip diagnosing.
18289     // FIXME: Using the mangling context here is a hack.
18290     if (auto *VD = dyn_cast_or_null<VarDecl>(
18291             ExprEvalContexts.back().ManglingContextDecl)) {
18292       if (VD->isConstexpr() ||
18293           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18294         break;
18295       // FIXME: For any other kind of variable, we should build a CFG for its
18296       // initializer and check whether the context in question is reachable.
18297     }
18298 
18299     Diag(Loc, PD);
18300     return true;
18301   }
18302 
18303   return false;
18304 }
18305 
18306 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18307                                const PartialDiagnostic &PD) {
18308   return DiagRuntimeBehavior(
18309       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18310 }
18311 
18312 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18313                                CallExpr *CE, FunctionDecl *FD) {
18314   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18315     return false;
18316 
18317   // If we're inside a decltype's expression, don't check for a valid return
18318   // type or construct temporaries until we know whether this is the last call.
18319   if (ExprEvalContexts.back().ExprContext ==
18320       ExpressionEvaluationContextRecord::EK_Decltype) {
18321     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18322     return false;
18323   }
18324 
18325   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18326     FunctionDecl *FD;
18327     CallExpr *CE;
18328 
18329   public:
18330     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18331       : FD(FD), CE(CE) { }
18332 
18333     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18334       if (!FD) {
18335         S.Diag(Loc, diag::err_call_incomplete_return)
18336           << T << CE->getSourceRange();
18337         return;
18338       }
18339 
18340       S.Diag(Loc, diag::err_call_function_incomplete_return)
18341           << CE->getSourceRange() << FD << T;
18342       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18343           << FD->getDeclName();
18344     }
18345   } Diagnoser(FD, CE);
18346 
18347   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18348     return true;
18349 
18350   return false;
18351 }
18352 
18353 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18354 // will prevent this condition from triggering, which is what we want.
18355 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18356   SourceLocation Loc;
18357 
18358   unsigned diagnostic = diag::warn_condition_is_assignment;
18359   bool IsOrAssign = false;
18360 
18361   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18362     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18363       return;
18364 
18365     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18366 
18367     // Greylist some idioms by putting them into a warning subcategory.
18368     if (ObjCMessageExpr *ME
18369           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18370       Selector Sel = ME->getSelector();
18371 
18372       // self = [<foo> init...]
18373       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18374         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18375 
18376       // <foo> = [<bar> nextObject]
18377       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18378         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18379     }
18380 
18381     Loc = Op->getOperatorLoc();
18382   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18383     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18384       return;
18385 
18386     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18387     Loc = Op->getOperatorLoc();
18388   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18389     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18390   else {
18391     // Not an assignment.
18392     return;
18393   }
18394 
18395   Diag(Loc, diagnostic) << E->getSourceRange();
18396 
18397   SourceLocation Open = E->getBeginLoc();
18398   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18399   Diag(Loc, diag::note_condition_assign_silence)
18400         << FixItHint::CreateInsertion(Open, "(")
18401         << FixItHint::CreateInsertion(Close, ")");
18402 
18403   if (IsOrAssign)
18404     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18405       << FixItHint::CreateReplacement(Loc, "!=");
18406   else
18407     Diag(Loc, diag::note_condition_assign_to_comparison)
18408       << FixItHint::CreateReplacement(Loc, "==");
18409 }
18410 
18411 /// Redundant parentheses over an equality comparison can indicate
18412 /// that the user intended an assignment used as condition.
18413 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18414   // Don't warn if the parens came from a macro.
18415   SourceLocation parenLoc = ParenE->getBeginLoc();
18416   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18417     return;
18418   // Don't warn for dependent expressions.
18419   if (ParenE->isTypeDependent())
18420     return;
18421 
18422   Expr *E = ParenE->IgnoreParens();
18423 
18424   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18425     if (opE->getOpcode() == BO_EQ &&
18426         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18427                                                            == Expr::MLV_Valid) {
18428       SourceLocation Loc = opE->getOperatorLoc();
18429 
18430       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18431       SourceRange ParenERange = ParenE->getSourceRange();
18432       Diag(Loc, diag::note_equality_comparison_silence)
18433         << FixItHint::CreateRemoval(ParenERange.getBegin())
18434         << FixItHint::CreateRemoval(ParenERange.getEnd());
18435       Diag(Loc, diag::note_equality_comparison_to_assign)
18436         << FixItHint::CreateReplacement(Loc, "=");
18437     }
18438 }
18439 
18440 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18441                                        bool IsConstexpr) {
18442   DiagnoseAssignmentAsCondition(E);
18443   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18444     DiagnoseEqualityWithExtraParens(parenE);
18445 
18446   ExprResult result = CheckPlaceholderExpr(E);
18447   if (result.isInvalid()) return ExprError();
18448   E = result.get();
18449 
18450   if (!E->isTypeDependent()) {
18451     if (getLangOpts().CPlusPlus)
18452       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18453 
18454     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18455     if (ERes.isInvalid())
18456       return ExprError();
18457     E = ERes.get();
18458 
18459     QualType T = E->getType();
18460     if (!T->isScalarType()) { // C99 6.8.4.1p1
18461       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18462         << T << E->getSourceRange();
18463       return ExprError();
18464     }
18465     CheckBoolLikeConversion(E, Loc);
18466   }
18467 
18468   return E;
18469 }
18470 
18471 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18472                                            Expr *SubExpr, ConditionKind CK) {
18473   // Empty conditions are valid in for-statements.
18474   if (!SubExpr)
18475     return ConditionResult();
18476 
18477   ExprResult Cond;
18478   switch (CK) {
18479   case ConditionKind::Boolean:
18480     Cond = CheckBooleanCondition(Loc, SubExpr);
18481     break;
18482 
18483   case ConditionKind::ConstexprIf:
18484     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18485     break;
18486 
18487   case ConditionKind::Switch:
18488     Cond = CheckSwitchCondition(Loc, SubExpr);
18489     break;
18490   }
18491   if (Cond.isInvalid()) {
18492     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18493                               {SubExpr});
18494     if (!Cond.get())
18495       return ConditionError();
18496   }
18497   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18498   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18499   if (!FullExpr.get())
18500     return ConditionError();
18501 
18502   return ConditionResult(*this, nullptr, FullExpr,
18503                          CK == ConditionKind::ConstexprIf);
18504 }
18505 
18506 namespace {
18507   /// A visitor for rebuilding a call to an __unknown_any expression
18508   /// to have an appropriate type.
18509   struct RebuildUnknownAnyFunction
18510     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18511 
18512     Sema &S;
18513 
18514     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18515 
18516     ExprResult VisitStmt(Stmt *S) {
18517       llvm_unreachable("unexpected statement!");
18518     }
18519 
18520     ExprResult VisitExpr(Expr *E) {
18521       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18522         << E->getSourceRange();
18523       return ExprError();
18524     }
18525 
18526     /// Rebuild an expression which simply semantically wraps another
18527     /// expression which it shares the type and value kind of.
18528     template <class T> ExprResult rebuildSugarExpr(T *E) {
18529       ExprResult SubResult = Visit(E->getSubExpr());
18530       if (SubResult.isInvalid()) return ExprError();
18531 
18532       Expr *SubExpr = SubResult.get();
18533       E->setSubExpr(SubExpr);
18534       E->setType(SubExpr->getType());
18535       E->setValueKind(SubExpr->getValueKind());
18536       assert(E->getObjectKind() == OK_Ordinary);
18537       return E;
18538     }
18539 
18540     ExprResult VisitParenExpr(ParenExpr *E) {
18541       return rebuildSugarExpr(E);
18542     }
18543 
18544     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18545       return rebuildSugarExpr(E);
18546     }
18547 
18548     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18549       ExprResult SubResult = Visit(E->getSubExpr());
18550       if (SubResult.isInvalid()) return ExprError();
18551 
18552       Expr *SubExpr = SubResult.get();
18553       E->setSubExpr(SubExpr);
18554       E->setType(S.Context.getPointerType(SubExpr->getType()));
18555       assert(E->getValueKind() == VK_RValue);
18556       assert(E->getObjectKind() == OK_Ordinary);
18557       return E;
18558     }
18559 
18560     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18561       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18562 
18563       E->setType(VD->getType());
18564 
18565       assert(E->getValueKind() == VK_RValue);
18566       if (S.getLangOpts().CPlusPlus &&
18567           !(isa<CXXMethodDecl>(VD) &&
18568             cast<CXXMethodDecl>(VD)->isInstance()))
18569         E->setValueKind(VK_LValue);
18570 
18571       return E;
18572     }
18573 
18574     ExprResult VisitMemberExpr(MemberExpr *E) {
18575       return resolveDecl(E, E->getMemberDecl());
18576     }
18577 
18578     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18579       return resolveDecl(E, E->getDecl());
18580     }
18581   };
18582 }
18583 
18584 /// Given a function expression of unknown-any type, try to rebuild it
18585 /// to have a function type.
18586 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18587   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18588   if (Result.isInvalid()) return ExprError();
18589   return S.DefaultFunctionArrayConversion(Result.get());
18590 }
18591 
18592 namespace {
18593   /// A visitor for rebuilding an expression of type __unknown_anytype
18594   /// into one which resolves the type directly on the referring
18595   /// expression.  Strict preservation of the original source
18596   /// structure is not a goal.
18597   struct RebuildUnknownAnyExpr
18598     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18599 
18600     Sema &S;
18601 
18602     /// The current destination type.
18603     QualType DestType;
18604 
18605     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18606       : S(S), DestType(CastType) {}
18607 
18608     ExprResult VisitStmt(Stmt *S) {
18609       llvm_unreachable("unexpected statement!");
18610     }
18611 
18612     ExprResult VisitExpr(Expr *E) {
18613       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18614         << E->getSourceRange();
18615       return ExprError();
18616     }
18617 
18618     ExprResult VisitCallExpr(CallExpr *E);
18619     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18620 
18621     /// Rebuild an expression which simply semantically wraps another
18622     /// expression which it shares the type and value kind of.
18623     template <class T> ExprResult rebuildSugarExpr(T *E) {
18624       ExprResult SubResult = Visit(E->getSubExpr());
18625       if (SubResult.isInvalid()) return ExprError();
18626       Expr *SubExpr = SubResult.get();
18627       E->setSubExpr(SubExpr);
18628       E->setType(SubExpr->getType());
18629       E->setValueKind(SubExpr->getValueKind());
18630       assert(E->getObjectKind() == OK_Ordinary);
18631       return E;
18632     }
18633 
18634     ExprResult VisitParenExpr(ParenExpr *E) {
18635       return rebuildSugarExpr(E);
18636     }
18637 
18638     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18639       return rebuildSugarExpr(E);
18640     }
18641 
18642     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18643       const PointerType *Ptr = DestType->getAs<PointerType>();
18644       if (!Ptr) {
18645         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18646           << E->getSourceRange();
18647         return ExprError();
18648       }
18649 
18650       if (isa<CallExpr>(E->getSubExpr())) {
18651         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18652           << E->getSourceRange();
18653         return ExprError();
18654       }
18655 
18656       assert(E->getValueKind() == VK_RValue);
18657       assert(E->getObjectKind() == OK_Ordinary);
18658       E->setType(DestType);
18659 
18660       // Build the sub-expression as if it were an object of the pointee type.
18661       DestType = Ptr->getPointeeType();
18662       ExprResult SubResult = Visit(E->getSubExpr());
18663       if (SubResult.isInvalid()) return ExprError();
18664       E->setSubExpr(SubResult.get());
18665       return E;
18666     }
18667 
18668     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18669 
18670     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18671 
18672     ExprResult VisitMemberExpr(MemberExpr *E) {
18673       return resolveDecl(E, E->getMemberDecl());
18674     }
18675 
18676     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18677       return resolveDecl(E, E->getDecl());
18678     }
18679   };
18680 }
18681 
18682 /// Rebuilds a call expression which yielded __unknown_anytype.
18683 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18684   Expr *CalleeExpr = E->getCallee();
18685 
18686   enum FnKind {
18687     FK_MemberFunction,
18688     FK_FunctionPointer,
18689     FK_BlockPointer
18690   };
18691 
18692   FnKind Kind;
18693   QualType CalleeType = CalleeExpr->getType();
18694   if (CalleeType == S.Context.BoundMemberTy) {
18695     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18696     Kind = FK_MemberFunction;
18697     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18698   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18699     CalleeType = Ptr->getPointeeType();
18700     Kind = FK_FunctionPointer;
18701   } else {
18702     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18703     Kind = FK_BlockPointer;
18704   }
18705   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18706 
18707   // Verify that this is a legal result type of a function.
18708   if (DestType->isArrayType() || DestType->isFunctionType()) {
18709     unsigned diagID = diag::err_func_returning_array_function;
18710     if (Kind == FK_BlockPointer)
18711       diagID = diag::err_block_returning_array_function;
18712 
18713     S.Diag(E->getExprLoc(), diagID)
18714       << DestType->isFunctionType() << DestType;
18715     return ExprError();
18716   }
18717 
18718   // Otherwise, go ahead and set DestType as the call's result.
18719   E->setType(DestType.getNonLValueExprType(S.Context));
18720   E->setValueKind(Expr::getValueKindForType(DestType));
18721   assert(E->getObjectKind() == OK_Ordinary);
18722 
18723   // Rebuild the function type, replacing the result type with DestType.
18724   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18725   if (Proto) {
18726     // __unknown_anytype(...) is a special case used by the debugger when
18727     // it has no idea what a function's signature is.
18728     //
18729     // We want to build this call essentially under the K&R
18730     // unprototyped rules, but making a FunctionNoProtoType in C++
18731     // would foul up all sorts of assumptions.  However, we cannot
18732     // simply pass all arguments as variadic arguments, nor can we
18733     // portably just call the function under a non-variadic type; see
18734     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18735     // However, it turns out that in practice it is generally safe to
18736     // call a function declared as "A foo(B,C,D);" under the prototype
18737     // "A foo(B,C,D,...);".  The only known exception is with the
18738     // Windows ABI, where any variadic function is implicitly cdecl
18739     // regardless of its normal CC.  Therefore we change the parameter
18740     // types to match the types of the arguments.
18741     //
18742     // This is a hack, but it is far superior to moving the
18743     // corresponding target-specific code from IR-gen to Sema/AST.
18744 
18745     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18746     SmallVector<QualType, 8> ArgTypes;
18747     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18748       ArgTypes.reserve(E->getNumArgs());
18749       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18750         Expr *Arg = E->getArg(i);
18751         QualType ArgType = Arg->getType();
18752         if (E->isLValue()) {
18753           ArgType = S.Context.getLValueReferenceType(ArgType);
18754         } else if (E->isXValue()) {
18755           ArgType = S.Context.getRValueReferenceType(ArgType);
18756         }
18757         ArgTypes.push_back(ArgType);
18758       }
18759       ParamTypes = ArgTypes;
18760     }
18761     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18762                                          Proto->getExtProtoInfo());
18763   } else {
18764     DestType = S.Context.getFunctionNoProtoType(DestType,
18765                                                 FnType->getExtInfo());
18766   }
18767 
18768   // Rebuild the appropriate pointer-to-function type.
18769   switch (Kind) {
18770   case FK_MemberFunction:
18771     // Nothing to do.
18772     break;
18773 
18774   case FK_FunctionPointer:
18775     DestType = S.Context.getPointerType(DestType);
18776     break;
18777 
18778   case FK_BlockPointer:
18779     DestType = S.Context.getBlockPointerType(DestType);
18780     break;
18781   }
18782 
18783   // Finally, we can recurse.
18784   ExprResult CalleeResult = Visit(CalleeExpr);
18785   if (!CalleeResult.isUsable()) return ExprError();
18786   E->setCallee(CalleeResult.get());
18787 
18788   // Bind a temporary if necessary.
18789   return S.MaybeBindToTemporary(E);
18790 }
18791 
18792 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18793   // Verify that this is a legal result type of a call.
18794   if (DestType->isArrayType() || DestType->isFunctionType()) {
18795     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18796       << DestType->isFunctionType() << DestType;
18797     return ExprError();
18798   }
18799 
18800   // Rewrite the method result type if available.
18801   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18802     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18803     Method->setReturnType(DestType);
18804   }
18805 
18806   // Change the type of the message.
18807   E->setType(DestType.getNonReferenceType());
18808   E->setValueKind(Expr::getValueKindForType(DestType));
18809 
18810   return S.MaybeBindToTemporary(E);
18811 }
18812 
18813 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18814   // The only case we should ever see here is a function-to-pointer decay.
18815   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18816     assert(E->getValueKind() == VK_RValue);
18817     assert(E->getObjectKind() == OK_Ordinary);
18818 
18819     E->setType(DestType);
18820 
18821     // Rebuild the sub-expression as the pointee (function) type.
18822     DestType = DestType->castAs<PointerType>()->getPointeeType();
18823 
18824     ExprResult Result = Visit(E->getSubExpr());
18825     if (!Result.isUsable()) return ExprError();
18826 
18827     E->setSubExpr(Result.get());
18828     return E;
18829   } else if (E->getCastKind() == CK_LValueToRValue) {
18830     assert(E->getValueKind() == VK_RValue);
18831     assert(E->getObjectKind() == OK_Ordinary);
18832 
18833     assert(isa<BlockPointerType>(E->getType()));
18834 
18835     E->setType(DestType);
18836 
18837     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18838     DestType = S.Context.getLValueReferenceType(DestType);
18839 
18840     ExprResult Result = Visit(E->getSubExpr());
18841     if (!Result.isUsable()) return ExprError();
18842 
18843     E->setSubExpr(Result.get());
18844     return E;
18845   } else {
18846     llvm_unreachable("Unhandled cast type!");
18847   }
18848 }
18849 
18850 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18851   ExprValueKind ValueKind = VK_LValue;
18852   QualType Type = DestType;
18853 
18854   // We know how to make this work for certain kinds of decls:
18855 
18856   //  - functions
18857   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18858     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18859       DestType = Ptr->getPointeeType();
18860       ExprResult Result = resolveDecl(E, VD);
18861       if (Result.isInvalid()) return ExprError();
18862       return S.ImpCastExprToType(Result.get(), Type,
18863                                  CK_FunctionToPointerDecay, VK_RValue);
18864     }
18865 
18866     if (!Type->isFunctionType()) {
18867       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18868         << VD << E->getSourceRange();
18869       return ExprError();
18870     }
18871     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18872       // We must match the FunctionDecl's type to the hack introduced in
18873       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18874       // type. See the lengthy commentary in that routine.
18875       QualType FDT = FD->getType();
18876       const FunctionType *FnType = FDT->castAs<FunctionType>();
18877       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18878       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18879       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18880         SourceLocation Loc = FD->getLocation();
18881         FunctionDecl *NewFD = FunctionDecl::Create(
18882             S.Context, FD->getDeclContext(), Loc, Loc,
18883             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18884             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18885             /*ConstexprKind*/ CSK_unspecified);
18886 
18887         if (FD->getQualifier())
18888           NewFD->setQualifierInfo(FD->getQualifierLoc());
18889 
18890         SmallVector<ParmVarDecl*, 16> Params;
18891         for (const auto &AI : FT->param_types()) {
18892           ParmVarDecl *Param =
18893             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18894           Param->setScopeInfo(0, Params.size());
18895           Params.push_back(Param);
18896         }
18897         NewFD->setParams(Params);
18898         DRE->setDecl(NewFD);
18899         VD = DRE->getDecl();
18900       }
18901     }
18902 
18903     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18904       if (MD->isInstance()) {
18905         ValueKind = VK_RValue;
18906         Type = S.Context.BoundMemberTy;
18907       }
18908 
18909     // Function references aren't l-values in C.
18910     if (!S.getLangOpts().CPlusPlus)
18911       ValueKind = VK_RValue;
18912 
18913   //  - variables
18914   } else if (isa<VarDecl>(VD)) {
18915     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18916       Type = RefTy->getPointeeType();
18917     } else if (Type->isFunctionType()) {
18918       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18919         << VD << E->getSourceRange();
18920       return ExprError();
18921     }
18922 
18923   //  - nothing else
18924   } else {
18925     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18926       << VD << E->getSourceRange();
18927     return ExprError();
18928   }
18929 
18930   // Modifying the declaration like this is friendly to IR-gen but
18931   // also really dangerous.
18932   VD->setType(DestType);
18933   E->setType(Type);
18934   E->setValueKind(ValueKind);
18935   return E;
18936 }
18937 
18938 /// Check a cast of an unknown-any type.  We intentionally only
18939 /// trigger this for C-style casts.
18940 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18941                                      Expr *CastExpr, CastKind &CastKind,
18942                                      ExprValueKind &VK, CXXCastPath &Path) {
18943   // The type we're casting to must be either void or complete.
18944   if (!CastType->isVoidType() &&
18945       RequireCompleteType(TypeRange.getBegin(), CastType,
18946                           diag::err_typecheck_cast_to_incomplete))
18947     return ExprError();
18948 
18949   // Rewrite the casted expression from scratch.
18950   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18951   if (!result.isUsable()) return ExprError();
18952 
18953   CastExpr = result.get();
18954   VK = CastExpr->getValueKind();
18955   CastKind = CK_NoOp;
18956 
18957   return CastExpr;
18958 }
18959 
18960 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18961   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18962 }
18963 
18964 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18965                                     Expr *arg, QualType &paramType) {
18966   // If the syntactic form of the argument is not an explicit cast of
18967   // any sort, just do default argument promotion.
18968   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18969   if (!castArg) {
18970     ExprResult result = DefaultArgumentPromotion(arg);
18971     if (result.isInvalid()) return ExprError();
18972     paramType = result.get()->getType();
18973     return result;
18974   }
18975 
18976   // Otherwise, use the type that was written in the explicit cast.
18977   assert(!arg->hasPlaceholderType());
18978   paramType = castArg->getTypeAsWritten();
18979 
18980   // Copy-initialize a parameter of that type.
18981   InitializedEntity entity =
18982     InitializedEntity::InitializeParameter(Context, paramType,
18983                                            /*consumed*/ false);
18984   return PerformCopyInitialization(entity, callLoc, arg);
18985 }
18986 
18987 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18988   Expr *orig = E;
18989   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18990   while (true) {
18991     E = E->IgnoreParenImpCasts();
18992     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18993       E = call->getCallee();
18994       diagID = diag::err_uncasted_call_of_unknown_any;
18995     } else {
18996       break;
18997     }
18998   }
18999 
19000   SourceLocation loc;
19001   NamedDecl *d;
19002   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19003     loc = ref->getLocation();
19004     d = ref->getDecl();
19005   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19006     loc = mem->getMemberLoc();
19007     d = mem->getMemberDecl();
19008   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19009     diagID = diag::err_uncasted_call_of_unknown_any;
19010     loc = msg->getSelectorStartLoc();
19011     d = msg->getMethodDecl();
19012     if (!d) {
19013       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19014         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19015         << orig->getSourceRange();
19016       return ExprError();
19017     }
19018   } else {
19019     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19020       << E->getSourceRange();
19021     return ExprError();
19022   }
19023 
19024   S.Diag(loc, diagID) << d << orig->getSourceRange();
19025 
19026   // Never recoverable.
19027   return ExprError();
19028 }
19029 
19030 /// Check for operands with placeholder types and complain if found.
19031 /// Returns ExprError() if there was an error and no recovery was possible.
19032 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19033   if (!getLangOpts().CPlusPlus) {
19034     // C cannot handle TypoExpr nodes on either side of a binop because it
19035     // doesn't handle dependent types properly, so make sure any TypoExprs have
19036     // been dealt with before checking the operands.
19037     ExprResult Result = CorrectDelayedTyposInExpr(E);
19038     if (!Result.isUsable()) return ExprError();
19039     E = Result.get();
19040   }
19041 
19042   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19043   if (!placeholderType) return E;
19044 
19045   switch (placeholderType->getKind()) {
19046 
19047   // Overloaded expressions.
19048   case BuiltinType::Overload: {
19049     // Try to resolve a single function template specialization.
19050     // This is obligatory.
19051     ExprResult Result = E;
19052     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19053       return Result;
19054 
19055     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19056     // leaves Result unchanged on failure.
19057     Result = E;
19058     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19059       return Result;
19060 
19061     // If that failed, try to recover with a call.
19062     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19063                          /*complain*/ true);
19064     return Result;
19065   }
19066 
19067   // Bound member functions.
19068   case BuiltinType::BoundMember: {
19069     ExprResult result = E;
19070     const Expr *BME = E->IgnoreParens();
19071     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19072     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19073     if (isa<CXXPseudoDestructorExpr>(BME)) {
19074       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19075     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19076       if (ME->getMemberNameInfo().getName().getNameKind() ==
19077           DeclarationName::CXXDestructorName)
19078         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19079     }
19080     tryToRecoverWithCall(result, PD,
19081                          /*complain*/ true);
19082     return result;
19083   }
19084 
19085   // ARC unbridged casts.
19086   case BuiltinType::ARCUnbridgedCast: {
19087     Expr *realCast = stripARCUnbridgedCast(E);
19088     diagnoseARCUnbridgedCast(realCast);
19089     return realCast;
19090   }
19091 
19092   // Expressions of unknown type.
19093   case BuiltinType::UnknownAny:
19094     return diagnoseUnknownAnyExpr(*this, E);
19095 
19096   // Pseudo-objects.
19097   case BuiltinType::PseudoObject:
19098     return checkPseudoObjectRValue(E);
19099 
19100   case BuiltinType::BuiltinFn: {
19101     // Accept __noop without parens by implicitly converting it to a call expr.
19102     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19103     if (DRE) {
19104       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19105       if (FD->getBuiltinID() == Builtin::BI__noop) {
19106         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19107                               CK_BuiltinFnToFnPtr)
19108                 .get();
19109         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19110                                 VK_RValue, SourceLocation(),
19111                                 FPOptionsOverride());
19112       }
19113     }
19114 
19115     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19116     return ExprError();
19117   }
19118 
19119   case BuiltinType::IncompleteMatrixIdx:
19120     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19121              ->getRowIdx()
19122              ->getBeginLoc(),
19123          diag::err_matrix_incomplete_index);
19124     return ExprError();
19125 
19126   // Expressions of unknown type.
19127   case BuiltinType::OMPArraySection:
19128     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19129     return ExprError();
19130 
19131   // Expressions of unknown type.
19132   case BuiltinType::OMPArrayShaping:
19133     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19134 
19135   case BuiltinType::OMPIterator:
19136     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19137 
19138   // Everything else should be impossible.
19139 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19140   case BuiltinType::Id:
19141 #include "clang/Basic/OpenCLImageTypes.def"
19142 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19143   case BuiltinType::Id:
19144 #include "clang/Basic/OpenCLExtensionTypes.def"
19145 #define SVE_TYPE(Name, Id, SingletonId) \
19146   case BuiltinType::Id:
19147 #include "clang/Basic/AArch64SVEACLETypes.def"
19148 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19149 #define PLACEHOLDER_TYPE(Id, SingletonId)
19150 #include "clang/AST/BuiltinTypes.def"
19151     break;
19152   }
19153 
19154   llvm_unreachable("invalid placeholder type!");
19155 }
19156 
19157 bool Sema::CheckCaseExpression(Expr *E) {
19158   if (E->isTypeDependent())
19159     return true;
19160   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19161     return E->getType()->isIntegralOrEnumerationType();
19162   return false;
19163 }
19164 
19165 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19166 ExprResult
19167 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19168   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19169          "Unknown Objective-C Boolean value!");
19170   QualType BoolT = Context.ObjCBuiltinBoolTy;
19171   if (!Context.getBOOLDecl()) {
19172     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19173                         Sema::LookupOrdinaryName);
19174     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19175       NamedDecl *ND = Result.getFoundDecl();
19176       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19177         Context.setBOOLDecl(TD);
19178     }
19179   }
19180   if (Context.getBOOLDecl())
19181     BoolT = Context.getBOOLType();
19182   return new (Context)
19183       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19184 }
19185 
19186 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19187     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19188     SourceLocation RParen) {
19189 
19190   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19191 
19192   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19193     return Spec.getPlatform() == Platform;
19194   });
19195 
19196   VersionTuple Version;
19197   if (Spec != AvailSpecs.end())
19198     Version = Spec->getVersion();
19199 
19200   // The use of `@available` in the enclosing function should be analyzed to
19201   // warn when it's used inappropriately (i.e. not if(@available)).
19202   if (getCurFunctionOrMethodDecl())
19203     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19204   else if (getCurBlock() || getCurLambda())
19205     getCurFunction()->HasPotentialAvailabilityViolations = true;
19206 
19207   return new (Context)
19208       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19209 }
19210 
19211 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19212                                     ArrayRef<Expr *> SubExprs, QualType T) {
19213   if (!Context.getLangOpts().RecoveryAST)
19214     return ExprError();
19215 
19216   if (isSFINAEContext())
19217     return ExprError();
19218 
19219   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19220     // We don't know the concrete type, fallback to dependent type.
19221     T = Context.DependentTy;
19222   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19223 }
19224