1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 using namespace clang;
53 using namespace sema;
54 using llvm::RoundingMode;
55 
56 /// Determine whether the use of this declaration is valid, without
57 /// emitting diagnostics.
58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
59   // See if this is an auto-typed variable whose initializer we are parsing.
60   if (ParsingInitForAutoVars.count(D))
61     return false;
62 
63   // See if this is a deleted function.
64   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
65     if (FD->isDeleted())
66       return false;
67 
68     // If the function has a deduced return type, and we can't deduce it,
69     // then we can't use it either.
70     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
71         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
72       return false;
73 
74     // See if this is an aligned allocation/deallocation function that is
75     // unavailable.
76     if (TreatUnavailableAsInvalid &&
77         isUnavailableAlignedAllocationFunction(*FD))
78       return false;
79   }
80 
81   // See if this function is unavailable.
82   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
83       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
84     return false;
85 
86   if (isa<UnresolvedUsingIfExistsDecl>(D))
87     return false;
88 
89   return true;
90 }
91 
92 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
93   // Warn if this is used but marked unused.
94   if (const auto *A = D->getAttr<UnusedAttr>()) {
95     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
96     // should diagnose them.
97     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
98         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
99       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
100       if (DC && !DC->hasAttr<UnusedAttr>())
101         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
102     }
103   }
104 }
105 
106 /// Emit a note explaining that this function is deleted.
107 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
108   assert(Decl && Decl->isDeleted());
109 
110   if (Decl->isDefaulted()) {
111     // If the method was explicitly defaulted, point at that declaration.
112     if (!Decl->isImplicit())
113       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
114 
115     // Try to diagnose why this special member function was implicitly
116     // deleted. This might fail, if that reason no longer applies.
117     DiagnoseDeletedDefaultedFunction(Decl);
118     return;
119   }
120 
121   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
122   if (Ctor && Ctor->isInheritingConstructor())
123     return NoteDeletedInheritingConstructor(Ctor);
124 
125   Diag(Decl->getLocation(), diag::note_availability_specified_here)
126     << Decl << 1;
127 }
128 
129 /// Determine whether a FunctionDecl was ever declared with an
130 /// explicit storage class.
131 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
132   for (auto I : D->redecls()) {
133     if (I->getStorageClass() != SC_None)
134       return true;
135   }
136   return false;
137 }
138 
139 /// Check whether we're in an extern inline function and referring to a
140 /// variable or function with internal linkage (C11 6.7.4p3).
141 ///
142 /// This is only a warning because we used to silently accept this code, but
143 /// in many cases it will not behave correctly. This is not enabled in C++ mode
144 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
145 /// and so while there may still be user mistakes, most of the time we can't
146 /// prove that there are errors.
147 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
148                                                       const NamedDecl *D,
149                                                       SourceLocation Loc) {
150   // This is disabled under C++; there are too many ways for this to fire in
151   // contexts where the warning is a false positive, or where it is technically
152   // correct but benign.
153   if (S.getLangOpts().CPlusPlus)
154     return;
155 
156   // Check if this is an inlined function or method.
157   FunctionDecl *Current = S.getCurFunctionDecl();
158   if (!Current)
159     return;
160   if (!Current->isInlined())
161     return;
162   if (!Current->isExternallyVisible())
163     return;
164 
165   // Check if the decl has internal linkage.
166   if (D->getFormalLinkage() != InternalLinkage)
167     return;
168 
169   // Downgrade from ExtWarn to Extension if
170   //  (1) the supposedly external inline function is in the main file,
171   //      and probably won't be included anywhere else.
172   //  (2) the thing we're referencing is a pure function.
173   //  (3) the thing we're referencing is another inline function.
174   // This last can give us false negatives, but it's better than warning on
175   // wrappers for simple C library functions.
176   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
177   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
178   if (!DowngradeWarning && UsedFn)
179     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
180 
181   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
182                                : diag::ext_internal_in_extern_inline)
183     << /*IsVar=*/!UsedFn << D;
184 
185   S.MaybeSuggestAddingStaticToDecl(Current);
186 
187   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
188       << D;
189 }
190 
191 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
192   const FunctionDecl *First = Cur->getFirstDecl();
193 
194   // Suggest "static" on the function, if possible.
195   if (!hasAnyExplicitStorageClass(First)) {
196     SourceLocation DeclBegin = First->getSourceRange().getBegin();
197     Diag(DeclBegin, diag::note_convert_inline_to_static)
198       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
199   }
200 }
201 
202 /// Determine whether the use of this declaration is valid, and
203 /// emit any corresponding diagnostics.
204 ///
205 /// This routine diagnoses various problems with referencing
206 /// declarations that can occur when using a declaration. For example,
207 /// it might warn if a deprecated or unavailable declaration is being
208 /// used, or produce an error (and return true) if a C++0x deleted
209 /// function is being used.
210 ///
211 /// \returns true if there was an error (this declaration cannot be
212 /// referenced), false otherwise.
213 ///
214 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
215                              const ObjCInterfaceDecl *UnknownObjCClass,
216                              bool ObjCPropertyAccess,
217                              bool AvoidPartialAvailabilityChecks,
218                              ObjCInterfaceDecl *ClassReceiver) {
219   SourceLocation Loc = Locs.front();
220   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
221     // If there were any diagnostics suppressed by template argument deduction,
222     // emit them now.
223     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
224     if (Pos != SuppressedDiagnostics.end()) {
225       for (const PartialDiagnosticAt &Suppressed : Pos->second)
226         Diag(Suppressed.first, Suppressed.second);
227 
228       // Clear out the list of suppressed diagnostics, so that we don't emit
229       // them again for this specialization. However, we don't obsolete this
230       // entry from the table, because we want to avoid ever emitting these
231       // diagnostics again.
232       Pos->second.clear();
233     }
234 
235     // C++ [basic.start.main]p3:
236     //   The function 'main' shall not be used within a program.
237     if (cast<FunctionDecl>(D)->isMain())
238       Diag(Loc, diag::ext_main_used);
239 
240     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
241   }
242 
243   // See if this is an auto-typed variable whose initializer we are parsing.
244   if (ParsingInitForAutoVars.count(D)) {
245     if (isa<BindingDecl>(D)) {
246       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
247         << D->getDeclName();
248     } else {
249       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
250         << D->getDeclName() << cast<VarDecl>(D)->getType();
251     }
252     return true;
253   }
254 
255   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
256     // See if this is a deleted function.
257     if (FD->isDeleted()) {
258       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
259       if (Ctor && Ctor->isInheritingConstructor())
260         Diag(Loc, diag::err_deleted_inherited_ctor_use)
261             << Ctor->getParent()
262             << Ctor->getInheritedConstructor().getConstructor()->getParent();
263       else
264         Diag(Loc, diag::err_deleted_function_use);
265       NoteDeletedFunction(FD);
266       return true;
267     }
268 
269     // [expr.prim.id]p4
270     //   A program that refers explicitly or implicitly to a function with a
271     //   trailing requires-clause whose constraint-expression is not satisfied,
272     //   other than to declare it, is ill-formed. [...]
273     //
274     // See if this is a function with constraints that need to be satisfied.
275     // Check this before deducing the return type, as it might instantiate the
276     // definition.
277     if (FD->getTrailingRequiresClause()) {
278       ConstraintSatisfaction Satisfaction;
279       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
280         // A diagnostic will have already been generated (non-constant
281         // constraint expression, for example)
282         return true;
283       if (!Satisfaction.IsSatisfied) {
284         Diag(Loc,
285              diag::err_reference_to_function_with_unsatisfied_constraints)
286             << D;
287         DiagnoseUnsatisfiedConstraint(Satisfaction);
288         return true;
289       }
290     }
291 
292     // If the function has a deduced return type, and we can't deduce it,
293     // then we can't use it either.
294     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
295         DeduceReturnType(FD, Loc))
296       return true;
297 
298     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
299       return true;
300 
301     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
302       return true;
303   }
304 
305   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
306     // Lambdas are only default-constructible or assignable in C++2a onwards.
307     if (MD->getParent()->isLambda() &&
308         ((isa<CXXConstructorDecl>(MD) &&
309           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
310          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
311       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
312         << !isa<CXXConstructorDecl>(MD);
313     }
314   }
315 
316   auto getReferencedObjCProp = [](const NamedDecl *D) ->
317                                       const ObjCPropertyDecl * {
318     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
319       return MD->findPropertyDecl();
320     return nullptr;
321   };
322   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
323     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
324       return true;
325   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
326       return true;
327   }
328 
329   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
330   // Only the variables omp_in and omp_out are allowed in the combiner.
331   // Only the variables omp_priv and omp_orig are allowed in the
332   // initializer-clause.
333   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
334   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
335       isa<VarDecl>(D)) {
336     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
337         << getCurFunction()->HasOMPDeclareReductionCombiner;
338     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
339     return true;
340   }
341 
342   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
343   //  List-items in map clauses on this construct may only refer to the declared
344   //  variable var and entities that could be referenced by a procedure defined
345   //  at the same location
346   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
347       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
348     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
349         << getOpenMPDeclareMapperVarName();
350     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
351     return true;
352   }
353 
354   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
355     Diag(Loc, diag::err_use_of_empty_using_if_exists);
356     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
357     return true;
358   }
359 
360   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
361                              AvoidPartialAvailabilityChecks, ClassReceiver);
362 
363   DiagnoseUnusedOfDecl(*this, D, Loc);
364 
365   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
366 
367   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
368     if (auto *VD = dyn_cast<ValueDecl>(D))
369       checkDeviceDecl(VD, Loc);
370 
371     if (!Context.getTargetInfo().isTLSSupported())
372       if (const auto *VD = dyn_cast<VarDecl>(D))
373         if (VD->getTLSKind() != VarDecl::TLS_None)
374           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
375   }
376 
377   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
378       !isUnevaluatedContext()) {
379     // C++ [expr.prim.req.nested] p3
380     //   A local parameter shall only appear as an unevaluated operand
381     //   (Clause 8) within the constraint-expression.
382     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
383         << D;
384     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
385     return true;
386   }
387 
388   return false;
389 }
390 
391 /// DiagnoseSentinelCalls - This routine checks whether a call or
392 /// message-send is to a declaration with the sentinel attribute, and
393 /// if so, it checks that the requirements of the sentinel are
394 /// satisfied.
395 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
396                                  ArrayRef<Expr *> Args) {
397   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
398   if (!attr)
399     return;
400 
401   // The number of formal parameters of the declaration.
402   unsigned numFormalParams;
403 
404   // The kind of declaration.  This is also an index into a %select in
405   // the diagnostic.
406   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
407 
408   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
409     numFormalParams = MD->param_size();
410     calleeType = CT_Method;
411   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
412     numFormalParams = FD->param_size();
413     calleeType = CT_Function;
414   } else if (isa<VarDecl>(D)) {
415     QualType type = cast<ValueDecl>(D)->getType();
416     const FunctionType *fn = nullptr;
417     if (const PointerType *ptr = type->getAs<PointerType>()) {
418       fn = ptr->getPointeeType()->getAs<FunctionType>();
419       if (!fn) return;
420       calleeType = CT_Function;
421     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
422       fn = ptr->getPointeeType()->castAs<FunctionType>();
423       calleeType = CT_Block;
424     } else {
425       return;
426     }
427 
428     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
429       numFormalParams = proto->getNumParams();
430     } else {
431       numFormalParams = 0;
432     }
433   } else {
434     return;
435   }
436 
437   // "nullPos" is the number of formal parameters at the end which
438   // effectively count as part of the variadic arguments.  This is
439   // useful if you would prefer to not have *any* formal parameters,
440   // but the language forces you to have at least one.
441   unsigned nullPos = attr->getNullPos();
442   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
443   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
444 
445   // The number of arguments which should follow the sentinel.
446   unsigned numArgsAfterSentinel = attr->getSentinel();
447 
448   // If there aren't enough arguments for all the formal parameters,
449   // the sentinel, and the args after the sentinel, complain.
450   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
451     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
452     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
453     return;
454   }
455 
456   // Otherwise, find the sentinel expression.
457   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
458   if (!sentinelExpr) return;
459   if (sentinelExpr->isValueDependent()) return;
460   if (Context.isSentinelNullExpr(sentinelExpr)) return;
461 
462   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
463   // or 'NULL' if those are actually defined in the context.  Only use
464   // 'nil' for ObjC methods, where it's much more likely that the
465   // variadic arguments form a list of object pointers.
466   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
467   std::string NullValue;
468   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
469     NullValue = "nil";
470   else if (getLangOpts().CPlusPlus11)
471     NullValue = "nullptr";
472   else if (PP.isMacroDefined("NULL"))
473     NullValue = "NULL";
474   else
475     NullValue = "(void*) 0";
476 
477   if (MissingNilLoc.isInvalid())
478     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
479   else
480     Diag(MissingNilLoc, diag::warn_missing_sentinel)
481       << int(calleeType)
482       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
483   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
484 }
485 
486 SourceRange Sema::getExprRange(Expr *E) const {
487   return E ? E->getSourceRange() : SourceRange();
488 }
489 
490 //===----------------------------------------------------------------------===//
491 //  Standard Promotions and Conversions
492 //===----------------------------------------------------------------------===//
493 
494 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
495 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
496   // Handle any placeholder expressions which made it here.
497   if (E->getType()->isPlaceholderType()) {
498     ExprResult result = CheckPlaceholderExpr(E);
499     if (result.isInvalid()) return ExprError();
500     E = result.get();
501   }
502 
503   QualType Ty = E->getType();
504   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
505 
506   if (Ty->isFunctionType()) {
507     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
508       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
509         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
510           return ExprError();
511 
512     E = ImpCastExprToType(E, Context.getPointerType(Ty),
513                           CK_FunctionToPointerDecay).get();
514   } else if (Ty->isArrayType()) {
515     // In C90 mode, arrays only promote to pointers if the array expression is
516     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
517     // type 'array of type' is converted to an expression that has type 'pointer
518     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
519     // that has type 'array of type' ...".  The relevant change is "an lvalue"
520     // (C90) to "an expression" (C99).
521     //
522     // C++ 4.2p1:
523     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
524     // T" can be converted to an rvalue of type "pointer to T".
525     //
526     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
527       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
528                             CK_ArrayToPointerDecay).get();
529   }
530   return E;
531 }
532 
533 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
534   // Check to see if we are dereferencing a null pointer.  If so,
535   // and if not volatile-qualified, this is undefined behavior that the
536   // optimizer will delete, so warn about it.  People sometimes try to use this
537   // to get a deterministic trap and are surprised by clang's behavior.  This
538   // only handles the pattern "*null", which is a very syntactic check.
539   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
540   if (UO && UO->getOpcode() == UO_Deref &&
541       UO->getSubExpr()->getType()->isPointerType()) {
542     const LangAS AS =
543         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
544     if ((!isTargetAddressSpace(AS) ||
545          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
546         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
547             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
548         !UO->getType().isVolatileQualified()) {
549       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
550                             S.PDiag(diag::warn_indirection_through_null)
551                                 << UO->getSubExpr()->getSourceRange());
552       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
553                             S.PDiag(diag::note_indirection_through_null));
554     }
555   }
556 }
557 
558 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
559                                     SourceLocation AssignLoc,
560                                     const Expr* RHS) {
561   const ObjCIvarDecl *IV = OIRE->getDecl();
562   if (!IV)
563     return;
564 
565   DeclarationName MemberName = IV->getDeclName();
566   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
567   if (!Member || !Member->isStr("isa"))
568     return;
569 
570   const Expr *Base = OIRE->getBase();
571   QualType BaseType = Base->getType();
572   if (OIRE->isArrow())
573     BaseType = BaseType->getPointeeType();
574   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
575     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
576       ObjCInterfaceDecl *ClassDeclared = nullptr;
577       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
578       if (!ClassDeclared->getSuperClass()
579           && (*ClassDeclared->ivar_begin()) == IV) {
580         if (RHS) {
581           NamedDecl *ObjectSetClass =
582             S.LookupSingleName(S.TUScope,
583                                &S.Context.Idents.get("object_setClass"),
584                                SourceLocation(), S.LookupOrdinaryName);
585           if (ObjectSetClass) {
586             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
587             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
588                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
589                                               "object_setClass(")
590                 << FixItHint::CreateReplacement(
591                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
592                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
593           }
594           else
595             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
596         } else {
597           NamedDecl *ObjectGetClass =
598             S.LookupSingleName(S.TUScope,
599                                &S.Context.Idents.get("object_getClass"),
600                                SourceLocation(), S.LookupOrdinaryName);
601           if (ObjectGetClass)
602             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
603                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
604                                               "object_getClass(")
605                 << FixItHint::CreateReplacement(
606                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
607           else
608             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
609         }
610         S.Diag(IV->getLocation(), diag::note_ivar_decl);
611       }
612     }
613 }
614 
615 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
616   // Handle any placeholder expressions which made it here.
617   if (E->getType()->isPlaceholderType()) {
618     ExprResult result = CheckPlaceholderExpr(E);
619     if (result.isInvalid()) return ExprError();
620     E = result.get();
621   }
622 
623   // C++ [conv.lval]p1:
624   //   A glvalue of a non-function, non-array type T can be
625   //   converted to a prvalue.
626   if (!E->isGLValue()) return E;
627 
628   QualType T = E->getType();
629   assert(!T.isNull() && "r-value conversion on typeless expression?");
630 
631   // lvalue-to-rvalue conversion cannot be applied to function or array types.
632   if (T->isFunctionType() || T->isArrayType())
633     return E;
634 
635   // We don't want to throw lvalue-to-rvalue casts on top of
636   // expressions of certain types in C++.
637   if (getLangOpts().CPlusPlus &&
638       (E->getType() == Context.OverloadTy ||
639        T->isDependentType() ||
640        T->isRecordType()))
641     return E;
642 
643   // The C standard is actually really unclear on this point, and
644   // DR106 tells us what the result should be but not why.  It's
645   // generally best to say that void types just doesn't undergo
646   // lvalue-to-rvalue at all.  Note that expressions of unqualified
647   // 'void' type are never l-values, but qualified void can be.
648   if (T->isVoidType())
649     return E;
650 
651   // OpenCL usually rejects direct accesses to values of 'half' type.
652   if (getLangOpts().OpenCL &&
653       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
654       T->isHalfType()) {
655     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
656       << 0 << T;
657     return ExprError();
658   }
659 
660   CheckForNullPointerDereference(*this, E);
661   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
662     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
663                                      &Context.Idents.get("object_getClass"),
664                                      SourceLocation(), LookupOrdinaryName);
665     if (ObjectGetClass)
666       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
667           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
668           << FixItHint::CreateReplacement(
669                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
670     else
671       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
672   }
673   else if (const ObjCIvarRefExpr *OIRE =
674             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
675     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
676 
677   // C++ [conv.lval]p1:
678   //   [...] If T is a non-class type, the type of the prvalue is the
679   //   cv-unqualified version of T. Otherwise, the type of the
680   //   rvalue is T.
681   //
682   // C99 6.3.2.1p2:
683   //   If the lvalue has qualified type, the value has the unqualified
684   //   version of the type of the lvalue; otherwise, the value has the
685   //   type of the lvalue.
686   if (T.hasQualifiers())
687     T = T.getUnqualifiedType();
688 
689   // Under the MS ABI, lock down the inheritance model now.
690   if (T->isMemberPointerType() &&
691       Context.getTargetInfo().getCXXABI().isMicrosoft())
692     (void)isCompleteType(E->getExprLoc(), T);
693 
694   ExprResult Res = CheckLValueToRValueConversionOperand(E);
695   if (Res.isInvalid())
696     return Res;
697   E = Res.get();
698 
699   // Loading a __weak object implicitly retains the value, so we need a cleanup to
700   // balance that.
701   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
702     Cleanup.setExprNeedsCleanups(true);
703 
704   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
705     Cleanup.setExprNeedsCleanups(true);
706 
707   // C++ [conv.lval]p3:
708   //   If T is cv std::nullptr_t, the result is a null pointer constant.
709   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
710   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
711                                  CurFPFeatureOverrides());
712 
713   // C11 6.3.2.1p2:
714   //   ... if the lvalue has atomic type, the value has the non-atomic version
715   //   of the type of the lvalue ...
716   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
717     T = Atomic->getValueType().getUnqualifiedType();
718     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
719                                    nullptr, VK_RValue, FPOptionsOverride());
720   }
721 
722   return Res;
723 }
724 
725 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
726   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
727   if (Res.isInvalid())
728     return ExprError();
729   Res = DefaultLvalueConversion(Res.get());
730   if (Res.isInvalid())
731     return ExprError();
732   return Res;
733 }
734 
735 /// CallExprUnaryConversions - a special case of an unary conversion
736 /// performed on a function designator of a call expression.
737 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
738   QualType Ty = E->getType();
739   ExprResult Res = E;
740   // Only do implicit cast for a function type, but not for a pointer
741   // to function type.
742   if (Ty->isFunctionType()) {
743     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
744                             CK_FunctionToPointerDecay);
745     if (Res.isInvalid())
746       return ExprError();
747   }
748   Res = DefaultLvalueConversion(Res.get());
749   if (Res.isInvalid())
750     return ExprError();
751   return Res.get();
752 }
753 
754 /// UsualUnaryConversions - Performs various conversions that are common to most
755 /// operators (C99 6.3). The conversions of array and function types are
756 /// sometimes suppressed. For example, the array->pointer conversion doesn't
757 /// apply if the array is an argument to the sizeof or address (&) operators.
758 /// In these instances, this routine should *not* be called.
759 ExprResult Sema::UsualUnaryConversions(Expr *E) {
760   // First, convert to an r-value.
761   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
762   if (Res.isInvalid())
763     return ExprError();
764   E = Res.get();
765 
766   QualType Ty = E->getType();
767   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
768 
769   // Half FP have to be promoted to float unless it is natively supported
770   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
771     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
772 
773   // Try to perform integral promotions if the object has a theoretically
774   // promotable type.
775   if (Ty->isIntegralOrUnscopedEnumerationType()) {
776     // C99 6.3.1.1p2:
777     //
778     //   The following may be used in an expression wherever an int or
779     //   unsigned int may be used:
780     //     - an object or expression with an integer type whose integer
781     //       conversion rank is less than or equal to the rank of int
782     //       and unsigned int.
783     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
784     //
785     //   If an int can represent all values of the original type, the
786     //   value is converted to an int; otherwise, it is converted to an
787     //   unsigned int. These are called the integer promotions. All
788     //   other types are unchanged by the integer promotions.
789 
790     QualType PTy = Context.isPromotableBitField(E);
791     if (!PTy.isNull()) {
792       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
793       return E;
794     }
795     if (Ty->isPromotableIntegerType()) {
796       QualType PT = Context.getPromotedIntegerType(Ty);
797       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
798       return E;
799     }
800   }
801   return E;
802 }
803 
804 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
805 /// do not have a prototype. Arguments that have type float or __fp16
806 /// are promoted to double. All other argument types are converted by
807 /// UsualUnaryConversions().
808 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
809   QualType Ty = E->getType();
810   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
811 
812   ExprResult Res = UsualUnaryConversions(E);
813   if (Res.isInvalid())
814     return ExprError();
815   E = Res.get();
816 
817   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
818   // promote to double.
819   // Note that default argument promotion applies only to float (and
820   // half/fp16); it does not apply to _Float16.
821   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
822   if (BTy && (BTy->getKind() == BuiltinType::Half ||
823               BTy->getKind() == BuiltinType::Float)) {
824     if (getLangOpts().OpenCL &&
825         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
826       if (BTy->getKind() == BuiltinType::Half) {
827         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
828       }
829     } else {
830       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
831     }
832   }
833   if (BTy &&
834       getLangOpts().getExtendIntArgs() ==
835           LangOptions::ExtendArgsKind::ExtendTo64 &&
836       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
837       Context.getTypeSizeInChars(BTy) <
838           Context.getTypeSizeInChars(Context.LongLongTy)) {
839     E = (Ty->isUnsignedIntegerType())
840             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
841                   .get()
842             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
843     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
844            "Unexpected typesize for LongLongTy");
845   }
846 
847   // C++ performs lvalue-to-rvalue conversion as a default argument
848   // promotion, even on class types, but note:
849   //   C++11 [conv.lval]p2:
850   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
851   //     operand or a subexpression thereof the value contained in the
852   //     referenced object is not accessed. Otherwise, if the glvalue
853   //     has a class type, the conversion copy-initializes a temporary
854   //     of type T from the glvalue and the result of the conversion
855   //     is a prvalue for the temporary.
856   // FIXME: add some way to gate this entire thing for correctness in
857   // potentially potentially evaluated contexts.
858   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
859     ExprResult Temp = PerformCopyInitialization(
860                        InitializedEntity::InitializeTemporary(E->getType()),
861                                                 E->getExprLoc(), E);
862     if (Temp.isInvalid())
863       return ExprError();
864     E = Temp.get();
865   }
866 
867   return E;
868 }
869 
870 /// Determine the degree of POD-ness for an expression.
871 /// Incomplete types are considered POD, since this check can be performed
872 /// when we're in an unevaluated context.
873 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
874   if (Ty->isIncompleteType()) {
875     // C++11 [expr.call]p7:
876     //   After these conversions, if the argument does not have arithmetic,
877     //   enumeration, pointer, pointer to member, or class type, the program
878     //   is ill-formed.
879     //
880     // Since we've already performed array-to-pointer and function-to-pointer
881     // decay, the only such type in C++ is cv void. This also handles
882     // initializer lists as variadic arguments.
883     if (Ty->isVoidType())
884       return VAK_Invalid;
885 
886     if (Ty->isObjCObjectType())
887       return VAK_Invalid;
888     return VAK_Valid;
889   }
890 
891   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
892     return VAK_Invalid;
893 
894   if (Ty.isCXX98PODType(Context))
895     return VAK_Valid;
896 
897   // C++11 [expr.call]p7:
898   //   Passing a potentially-evaluated argument of class type (Clause 9)
899   //   having a non-trivial copy constructor, a non-trivial move constructor,
900   //   or a non-trivial destructor, with no corresponding parameter,
901   //   is conditionally-supported with implementation-defined semantics.
902   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
903     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
904       if (!Record->hasNonTrivialCopyConstructor() &&
905           !Record->hasNonTrivialMoveConstructor() &&
906           !Record->hasNonTrivialDestructor())
907         return VAK_ValidInCXX11;
908 
909   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
910     return VAK_Valid;
911 
912   if (Ty->isObjCObjectType())
913     return VAK_Invalid;
914 
915   if (getLangOpts().MSVCCompat)
916     return VAK_MSVCUndefined;
917 
918   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
919   // permitted to reject them. We should consider doing so.
920   return VAK_Undefined;
921 }
922 
923 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
924   // Don't allow one to pass an Objective-C interface to a vararg.
925   const QualType &Ty = E->getType();
926   VarArgKind VAK = isValidVarArgType(Ty);
927 
928   // Complain about passing non-POD types through varargs.
929   switch (VAK) {
930   case VAK_ValidInCXX11:
931     DiagRuntimeBehavior(
932         E->getBeginLoc(), nullptr,
933         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
934     LLVM_FALLTHROUGH;
935   case VAK_Valid:
936     if (Ty->isRecordType()) {
937       // This is unlikely to be what the user intended. If the class has a
938       // 'c_str' member function, the user probably meant to call that.
939       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
940                           PDiag(diag::warn_pass_class_arg_to_vararg)
941                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
942     }
943     break;
944 
945   case VAK_Undefined:
946   case VAK_MSVCUndefined:
947     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
948                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
949                             << getLangOpts().CPlusPlus11 << Ty << CT);
950     break;
951 
952   case VAK_Invalid:
953     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
954       Diag(E->getBeginLoc(),
955            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
956           << Ty << CT;
957     else if (Ty->isObjCObjectType())
958       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
959                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
960                               << Ty << CT);
961     else
962       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
963           << isa<InitListExpr>(E) << Ty << CT;
964     break;
965   }
966 }
967 
968 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
969 /// will create a trap if the resulting type is not a POD type.
970 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
971                                                   FunctionDecl *FDecl) {
972   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
973     // Strip the unbridged-cast placeholder expression off, if applicable.
974     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
975         (CT == VariadicMethod ||
976          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
977       E = stripARCUnbridgedCast(E);
978 
979     // Otherwise, do normal placeholder checking.
980     } else {
981       ExprResult ExprRes = CheckPlaceholderExpr(E);
982       if (ExprRes.isInvalid())
983         return ExprError();
984       E = ExprRes.get();
985     }
986   }
987 
988   ExprResult ExprRes = DefaultArgumentPromotion(E);
989   if (ExprRes.isInvalid())
990     return ExprError();
991 
992   // Copy blocks to the heap.
993   if (ExprRes.get()->getType()->isBlockPointerType())
994     maybeExtendBlockObject(ExprRes);
995 
996   E = ExprRes.get();
997 
998   // Diagnostics regarding non-POD argument types are
999   // emitted along with format string checking in Sema::CheckFunctionCall().
1000   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1001     // Turn this into a trap.
1002     CXXScopeSpec SS;
1003     SourceLocation TemplateKWLoc;
1004     UnqualifiedId Name;
1005     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1006                        E->getBeginLoc());
1007     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1008                                           /*HasTrailingLParen=*/true,
1009                                           /*IsAddressOfOperand=*/false);
1010     if (TrapFn.isInvalid())
1011       return ExprError();
1012 
1013     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1014                                     None, E->getEndLoc());
1015     if (Call.isInvalid())
1016       return ExprError();
1017 
1018     ExprResult Comma =
1019         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1020     if (Comma.isInvalid())
1021       return ExprError();
1022     return Comma.get();
1023   }
1024 
1025   if (!getLangOpts().CPlusPlus &&
1026       RequireCompleteType(E->getExprLoc(), E->getType(),
1027                           diag::err_call_incomplete_argument))
1028     return ExprError();
1029 
1030   return E;
1031 }
1032 
1033 /// Converts an integer to complex float type.  Helper function of
1034 /// UsualArithmeticConversions()
1035 ///
1036 /// \return false if the integer expression is an integer type and is
1037 /// successfully converted to the complex type.
1038 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1039                                                   ExprResult &ComplexExpr,
1040                                                   QualType IntTy,
1041                                                   QualType ComplexTy,
1042                                                   bool SkipCast) {
1043   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1044   if (SkipCast) return false;
1045   if (IntTy->isIntegerType()) {
1046     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1047     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1048     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1049                                   CK_FloatingRealToComplex);
1050   } else {
1051     assert(IntTy->isComplexIntegerType());
1052     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1053                                   CK_IntegralComplexToFloatingComplex);
1054   }
1055   return false;
1056 }
1057 
1058 /// Handle arithmetic conversion with complex types.  Helper function of
1059 /// UsualArithmeticConversions()
1060 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1061                                              ExprResult &RHS, QualType LHSType,
1062                                              QualType RHSType,
1063                                              bool IsCompAssign) {
1064   // if we have an integer operand, the result is the complex type.
1065   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066                                              /*skipCast*/false))
1067     return LHSType;
1068   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1069                                              /*skipCast*/IsCompAssign))
1070     return RHSType;
1071 
1072   // This handles complex/complex, complex/float, or float/complex.
1073   // When both operands are complex, the shorter operand is converted to the
1074   // type of the longer, and that is the type of the result. This corresponds
1075   // to what is done when combining two real floating-point operands.
1076   // The fun begins when size promotion occur across type domains.
1077   // From H&S 6.3.4: When one operand is complex and the other is a real
1078   // floating-point type, the less precise type is converted, within it's
1079   // real or complex domain, to the precision of the other type. For example,
1080   // when combining a "long double" with a "double _Complex", the
1081   // "double _Complex" is promoted to "long double _Complex".
1082 
1083   // Compute the rank of the two types, regardless of whether they are complex.
1084   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1085 
1086   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1087   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1088   QualType LHSElementType =
1089       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1090   QualType RHSElementType =
1091       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1092 
1093   QualType ResultType = S.Context.getComplexType(LHSElementType);
1094   if (Order < 0) {
1095     // Promote the precision of the LHS if not an assignment.
1096     ResultType = S.Context.getComplexType(RHSElementType);
1097     if (!IsCompAssign) {
1098       if (LHSComplexType)
1099         LHS =
1100             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1101       else
1102         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1103     }
1104   } else if (Order > 0) {
1105     // Promote the precision of the RHS.
1106     if (RHSComplexType)
1107       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1108     else
1109       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1110   }
1111   return ResultType;
1112 }
1113 
1114 /// Handle arithmetic conversion from integer to float.  Helper function
1115 /// of UsualArithmeticConversions()
1116 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1117                                            ExprResult &IntExpr,
1118                                            QualType FloatTy, QualType IntTy,
1119                                            bool ConvertFloat, bool ConvertInt) {
1120   if (IntTy->isIntegerType()) {
1121     if (ConvertInt)
1122       // Convert intExpr to the lhs floating point type.
1123       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1124                                     CK_IntegralToFloating);
1125     return FloatTy;
1126   }
1127 
1128   // Convert both sides to the appropriate complex float.
1129   assert(IntTy->isComplexIntegerType());
1130   QualType result = S.Context.getComplexType(FloatTy);
1131 
1132   // _Complex int -> _Complex float
1133   if (ConvertInt)
1134     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1135                                   CK_IntegralComplexToFloatingComplex);
1136 
1137   // float -> _Complex float
1138   if (ConvertFloat)
1139     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1140                                     CK_FloatingRealToComplex);
1141 
1142   return result;
1143 }
1144 
1145 /// Handle arithmethic conversion with floating point types.  Helper
1146 /// function of UsualArithmeticConversions()
1147 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1148                                       ExprResult &RHS, QualType LHSType,
1149                                       QualType RHSType, bool IsCompAssign) {
1150   bool LHSFloat = LHSType->isRealFloatingType();
1151   bool RHSFloat = RHSType->isRealFloatingType();
1152 
1153   // N1169 4.1.4: If one of the operands has a floating type and the other
1154   //              operand has a fixed-point type, the fixed-point operand
1155   //              is converted to the floating type [...]
1156   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1157     if (LHSFloat)
1158       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1159     else if (!IsCompAssign)
1160       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1161     return LHSFloat ? LHSType : RHSType;
1162   }
1163 
1164   // If we have two real floating types, convert the smaller operand
1165   // to the bigger result.
1166   if (LHSFloat && RHSFloat) {
1167     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1168     if (order > 0) {
1169       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1170       return LHSType;
1171     }
1172 
1173     assert(order < 0 && "illegal float comparison");
1174     if (!IsCompAssign)
1175       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1176     return RHSType;
1177   }
1178 
1179   if (LHSFloat) {
1180     // Half FP has to be promoted to float unless it is natively supported
1181     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1182       LHSType = S.Context.FloatTy;
1183 
1184     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1185                                       /*ConvertFloat=*/!IsCompAssign,
1186                                       /*ConvertInt=*/ true);
1187   }
1188   assert(RHSFloat);
1189   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1190                                     /*ConvertFloat=*/ true,
1191                                     /*ConvertInt=*/!IsCompAssign);
1192 }
1193 
1194 /// Diagnose attempts to convert between __float128 and long double if
1195 /// there is no support for such conversion. Helper function of
1196 /// UsualArithmeticConversions().
1197 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1198                                       QualType RHSType) {
1199   /*  No issue converting if at least one of the types is not a floating point
1200       type or the two types have the same rank.
1201   */
1202   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1203       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1204     return false;
1205 
1206   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1207          "The remaining types must be floating point types.");
1208 
1209   auto *LHSComplex = LHSType->getAs<ComplexType>();
1210   auto *RHSComplex = RHSType->getAs<ComplexType>();
1211 
1212   QualType LHSElemType = LHSComplex ?
1213     LHSComplex->getElementType() : LHSType;
1214   QualType RHSElemType = RHSComplex ?
1215     RHSComplex->getElementType() : RHSType;
1216 
1217   // No issue if the two types have the same representation
1218   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1219       &S.Context.getFloatTypeSemantics(RHSElemType))
1220     return false;
1221 
1222   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1223                                 RHSElemType == S.Context.LongDoubleTy);
1224   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1225                             RHSElemType == S.Context.Float128Ty);
1226 
1227   // We've handled the situation where __float128 and long double have the same
1228   // representation. We allow all conversions for all possible long double types
1229   // except PPC's double double.
1230   return Float128AndLongDouble &&
1231     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1232      &llvm::APFloat::PPCDoubleDouble());
1233 }
1234 
1235 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1236 
1237 namespace {
1238 /// These helper callbacks are placed in an anonymous namespace to
1239 /// permit their use as function template parameters.
1240 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1241   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1242 }
1243 
1244 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1245   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1246                              CK_IntegralComplexCast);
1247 }
1248 }
1249 
1250 /// Handle integer arithmetic conversions.  Helper function of
1251 /// UsualArithmeticConversions()
1252 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1253 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1254                                         ExprResult &RHS, QualType LHSType,
1255                                         QualType RHSType, bool IsCompAssign) {
1256   // The rules for this case are in C99 6.3.1.8
1257   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1258   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1259   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1260   if (LHSSigned == RHSSigned) {
1261     // Same signedness; use the higher-ranked type
1262     if (order >= 0) {
1263       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1264       return LHSType;
1265     } else if (!IsCompAssign)
1266       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1267     return RHSType;
1268   } else if (order != (LHSSigned ? 1 : -1)) {
1269     // The unsigned type has greater than or equal rank to the
1270     // signed type, so use the unsigned type
1271     if (RHSSigned) {
1272       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1273       return LHSType;
1274     } else if (!IsCompAssign)
1275       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1276     return RHSType;
1277   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1278     // The two types are different widths; if we are here, that
1279     // means the signed type is larger than the unsigned type, so
1280     // use the signed type.
1281     if (LHSSigned) {
1282       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1283       return LHSType;
1284     } else if (!IsCompAssign)
1285       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1286     return RHSType;
1287   } else {
1288     // The signed type is higher-ranked than the unsigned type,
1289     // but isn't actually any bigger (like unsigned int and long
1290     // on most 32-bit systems).  Use the unsigned type corresponding
1291     // to the signed type.
1292     QualType result =
1293       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1294     RHS = (*doRHSCast)(S, RHS.get(), result);
1295     if (!IsCompAssign)
1296       LHS = (*doLHSCast)(S, LHS.get(), result);
1297     return result;
1298   }
1299 }
1300 
1301 /// Handle conversions with GCC complex int extension.  Helper function
1302 /// of UsualArithmeticConversions()
1303 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1304                                            ExprResult &RHS, QualType LHSType,
1305                                            QualType RHSType,
1306                                            bool IsCompAssign) {
1307   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1308   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1309 
1310   if (LHSComplexInt && RHSComplexInt) {
1311     QualType LHSEltType = LHSComplexInt->getElementType();
1312     QualType RHSEltType = RHSComplexInt->getElementType();
1313     QualType ScalarType =
1314       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1315         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1316 
1317     return S.Context.getComplexType(ScalarType);
1318   }
1319 
1320   if (LHSComplexInt) {
1321     QualType LHSEltType = LHSComplexInt->getElementType();
1322     QualType ScalarType =
1323       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1324         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1325     QualType ComplexType = S.Context.getComplexType(ScalarType);
1326     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1327                               CK_IntegralRealToComplex);
1328 
1329     return ComplexType;
1330   }
1331 
1332   assert(RHSComplexInt);
1333 
1334   QualType RHSEltType = RHSComplexInt->getElementType();
1335   QualType ScalarType =
1336     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1337       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1338   QualType ComplexType = S.Context.getComplexType(ScalarType);
1339 
1340   if (!IsCompAssign)
1341     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1342                               CK_IntegralRealToComplex);
1343   return ComplexType;
1344 }
1345 
1346 /// Return the rank of a given fixed point or integer type. The value itself
1347 /// doesn't matter, but the values must be increasing with proper increasing
1348 /// rank as described in N1169 4.1.1.
1349 static unsigned GetFixedPointRank(QualType Ty) {
1350   const auto *BTy = Ty->getAs<BuiltinType>();
1351   assert(BTy && "Expected a builtin type.");
1352 
1353   switch (BTy->getKind()) {
1354   case BuiltinType::ShortFract:
1355   case BuiltinType::UShortFract:
1356   case BuiltinType::SatShortFract:
1357   case BuiltinType::SatUShortFract:
1358     return 1;
1359   case BuiltinType::Fract:
1360   case BuiltinType::UFract:
1361   case BuiltinType::SatFract:
1362   case BuiltinType::SatUFract:
1363     return 2;
1364   case BuiltinType::LongFract:
1365   case BuiltinType::ULongFract:
1366   case BuiltinType::SatLongFract:
1367   case BuiltinType::SatULongFract:
1368     return 3;
1369   case BuiltinType::ShortAccum:
1370   case BuiltinType::UShortAccum:
1371   case BuiltinType::SatShortAccum:
1372   case BuiltinType::SatUShortAccum:
1373     return 4;
1374   case BuiltinType::Accum:
1375   case BuiltinType::UAccum:
1376   case BuiltinType::SatAccum:
1377   case BuiltinType::SatUAccum:
1378     return 5;
1379   case BuiltinType::LongAccum:
1380   case BuiltinType::ULongAccum:
1381   case BuiltinType::SatLongAccum:
1382   case BuiltinType::SatULongAccum:
1383     return 6;
1384   default:
1385     if (BTy->isInteger())
1386       return 0;
1387     llvm_unreachable("Unexpected fixed point or integer type");
1388   }
1389 }
1390 
1391 /// handleFixedPointConversion - Fixed point operations between fixed
1392 /// point types and integers or other fixed point types do not fall under
1393 /// usual arithmetic conversion since these conversions could result in loss
1394 /// of precsision (N1169 4.1.4). These operations should be calculated with
1395 /// the full precision of their result type (N1169 4.1.6.2.1).
1396 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1397                                            QualType RHSTy) {
1398   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1399          "Expected at least one of the operands to be a fixed point type");
1400   assert((LHSTy->isFixedPointOrIntegerType() ||
1401           RHSTy->isFixedPointOrIntegerType()) &&
1402          "Special fixed point arithmetic operation conversions are only "
1403          "applied to ints or other fixed point types");
1404 
1405   // If one operand has signed fixed-point type and the other operand has
1406   // unsigned fixed-point type, then the unsigned fixed-point operand is
1407   // converted to its corresponding signed fixed-point type and the resulting
1408   // type is the type of the converted operand.
1409   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1410     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1411   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1412     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1413 
1414   // The result type is the type with the highest rank, whereby a fixed-point
1415   // conversion rank is always greater than an integer conversion rank; if the
1416   // type of either of the operands is a saturating fixedpoint type, the result
1417   // type shall be the saturating fixed-point type corresponding to the type
1418   // with the highest rank; the resulting value is converted (taking into
1419   // account rounding and overflow) to the precision of the resulting type.
1420   // Same ranks between signed and unsigned types are resolved earlier, so both
1421   // types are either signed or both unsigned at this point.
1422   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1423   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1424 
1425   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1426 
1427   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1428     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1429 
1430   return ResultTy;
1431 }
1432 
1433 /// Check that the usual arithmetic conversions can be performed on this pair of
1434 /// expressions that might be of enumeration type.
1435 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1436                                            SourceLocation Loc,
1437                                            Sema::ArithConvKind ACK) {
1438   // C++2a [expr.arith.conv]p1:
1439   //   If one operand is of enumeration type and the other operand is of a
1440   //   different enumeration type or a floating-point type, this behavior is
1441   //   deprecated ([depr.arith.conv.enum]).
1442   //
1443   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1444   // Eventually we will presumably reject these cases (in C++23 onwards?).
1445   QualType L = LHS->getType(), R = RHS->getType();
1446   bool LEnum = L->isUnscopedEnumerationType(),
1447        REnum = R->isUnscopedEnumerationType();
1448   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1449   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1450       (REnum && L->isFloatingType())) {
1451     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1452                     ? diag::warn_arith_conv_enum_float_cxx20
1453                     : diag::warn_arith_conv_enum_float)
1454         << LHS->getSourceRange() << RHS->getSourceRange()
1455         << (int)ACK << LEnum << L << R;
1456   } else if (!IsCompAssign && LEnum && REnum &&
1457              !S.Context.hasSameUnqualifiedType(L, R)) {
1458     unsigned DiagID;
1459     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1460         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1461       // If either enumeration type is unnamed, it's less likely that the
1462       // user cares about this, but this situation is still deprecated in
1463       // C++2a. Use a different warning group.
1464       DiagID = S.getLangOpts().CPlusPlus20
1465                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1466                     : diag::warn_arith_conv_mixed_anon_enum_types;
1467     } else if (ACK == Sema::ACK_Conditional) {
1468       // Conditional expressions are separated out because they have
1469       // historically had a different warning flag.
1470       DiagID = S.getLangOpts().CPlusPlus20
1471                    ? diag::warn_conditional_mixed_enum_types_cxx20
1472                    : diag::warn_conditional_mixed_enum_types;
1473     } else if (ACK == Sema::ACK_Comparison) {
1474       // Comparison expressions are separated out because they have
1475       // historically had a different warning flag.
1476       DiagID = S.getLangOpts().CPlusPlus20
1477                    ? diag::warn_comparison_mixed_enum_types_cxx20
1478                    : diag::warn_comparison_mixed_enum_types;
1479     } else {
1480       DiagID = S.getLangOpts().CPlusPlus20
1481                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1482                    : diag::warn_arith_conv_mixed_enum_types;
1483     }
1484     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1485                         << (int)ACK << L << R;
1486   }
1487 }
1488 
1489 /// UsualArithmeticConversions - Performs various conversions that are common to
1490 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1491 /// routine returns the first non-arithmetic type found. The client is
1492 /// responsible for emitting appropriate error diagnostics.
1493 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1494                                           SourceLocation Loc,
1495                                           ArithConvKind ACK) {
1496   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1497 
1498   if (ACK != ACK_CompAssign) {
1499     LHS = UsualUnaryConversions(LHS.get());
1500     if (LHS.isInvalid())
1501       return QualType();
1502   }
1503 
1504   RHS = UsualUnaryConversions(RHS.get());
1505   if (RHS.isInvalid())
1506     return QualType();
1507 
1508   // For conversion purposes, we ignore any qualifiers.
1509   // For example, "const float" and "float" are equivalent.
1510   QualType LHSType =
1511     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1512   QualType RHSType =
1513     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1514 
1515   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1516   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1517     LHSType = AtomicLHS->getValueType();
1518 
1519   // If both types are identical, no conversion is needed.
1520   if (LHSType == RHSType)
1521     return LHSType;
1522 
1523   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1524   // The caller can deal with this (e.g. pointer + int).
1525   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1526     return QualType();
1527 
1528   // Apply unary and bitfield promotions to the LHS's type.
1529   QualType LHSUnpromotedType = LHSType;
1530   if (LHSType->isPromotableIntegerType())
1531     LHSType = Context.getPromotedIntegerType(LHSType);
1532   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1533   if (!LHSBitfieldPromoteTy.isNull())
1534     LHSType = LHSBitfieldPromoteTy;
1535   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1536     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1537 
1538   // If both types are identical, no conversion is needed.
1539   if (LHSType == RHSType)
1540     return LHSType;
1541 
1542   // ExtInt types aren't subject to conversions between them or normal integers,
1543   // so this fails.
1544   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1545     return QualType();
1546 
1547   // At this point, we have two different arithmetic types.
1548 
1549   // Diagnose attempts to convert between __float128 and long double where
1550   // such conversions currently can't be handled.
1551   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1552     return QualType();
1553 
1554   // Handle complex types first (C99 6.3.1.8p1).
1555   if (LHSType->isComplexType() || RHSType->isComplexType())
1556     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1557                                         ACK == ACK_CompAssign);
1558 
1559   // Now handle "real" floating types (i.e. float, double, long double).
1560   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1561     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1562                                  ACK == ACK_CompAssign);
1563 
1564   // Handle GCC complex int extension.
1565   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1566     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1567                                       ACK == ACK_CompAssign);
1568 
1569   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1570     return handleFixedPointConversion(*this, LHSType, RHSType);
1571 
1572   // Finally, we have two differing integer types.
1573   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1574            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1575 }
1576 
1577 //===----------------------------------------------------------------------===//
1578 //  Semantic Analysis for various Expression Types
1579 //===----------------------------------------------------------------------===//
1580 
1581 
1582 ExprResult
1583 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1584                                 SourceLocation DefaultLoc,
1585                                 SourceLocation RParenLoc,
1586                                 Expr *ControllingExpr,
1587                                 ArrayRef<ParsedType> ArgTypes,
1588                                 ArrayRef<Expr *> ArgExprs) {
1589   unsigned NumAssocs = ArgTypes.size();
1590   assert(NumAssocs == ArgExprs.size());
1591 
1592   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1593   for (unsigned i = 0; i < NumAssocs; ++i) {
1594     if (ArgTypes[i])
1595       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1596     else
1597       Types[i] = nullptr;
1598   }
1599 
1600   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1601                                              ControllingExpr,
1602                                              llvm::makeArrayRef(Types, NumAssocs),
1603                                              ArgExprs);
1604   delete [] Types;
1605   return ER;
1606 }
1607 
1608 ExprResult
1609 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1610                                  SourceLocation DefaultLoc,
1611                                  SourceLocation RParenLoc,
1612                                  Expr *ControllingExpr,
1613                                  ArrayRef<TypeSourceInfo *> Types,
1614                                  ArrayRef<Expr *> Exprs) {
1615   unsigned NumAssocs = Types.size();
1616   assert(NumAssocs == Exprs.size());
1617 
1618   // Decay and strip qualifiers for the controlling expression type, and handle
1619   // placeholder type replacement. See committee discussion from WG14 DR423.
1620   {
1621     EnterExpressionEvaluationContext Unevaluated(
1622         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1623     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1624     if (R.isInvalid())
1625       return ExprError();
1626     ControllingExpr = R.get();
1627   }
1628 
1629   // The controlling expression is an unevaluated operand, so side effects are
1630   // likely unintended.
1631   if (!inTemplateInstantiation() &&
1632       ControllingExpr->HasSideEffects(Context, false))
1633     Diag(ControllingExpr->getExprLoc(),
1634          diag::warn_side_effects_unevaluated_context);
1635 
1636   bool TypeErrorFound = false,
1637        IsResultDependent = ControllingExpr->isTypeDependent(),
1638        ContainsUnexpandedParameterPack
1639          = ControllingExpr->containsUnexpandedParameterPack();
1640 
1641   for (unsigned i = 0; i < NumAssocs; ++i) {
1642     if (Exprs[i]->containsUnexpandedParameterPack())
1643       ContainsUnexpandedParameterPack = true;
1644 
1645     if (Types[i]) {
1646       if (Types[i]->getType()->containsUnexpandedParameterPack())
1647         ContainsUnexpandedParameterPack = true;
1648 
1649       if (Types[i]->getType()->isDependentType()) {
1650         IsResultDependent = true;
1651       } else {
1652         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1653         // complete object type other than a variably modified type."
1654         unsigned D = 0;
1655         if (Types[i]->getType()->isIncompleteType())
1656           D = diag::err_assoc_type_incomplete;
1657         else if (!Types[i]->getType()->isObjectType())
1658           D = diag::err_assoc_type_nonobject;
1659         else if (Types[i]->getType()->isVariablyModifiedType())
1660           D = diag::err_assoc_type_variably_modified;
1661 
1662         if (D != 0) {
1663           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1664             << Types[i]->getTypeLoc().getSourceRange()
1665             << Types[i]->getType();
1666           TypeErrorFound = true;
1667         }
1668 
1669         // C11 6.5.1.1p2 "No two generic associations in the same generic
1670         // selection shall specify compatible types."
1671         for (unsigned j = i+1; j < NumAssocs; ++j)
1672           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1673               Context.typesAreCompatible(Types[i]->getType(),
1674                                          Types[j]->getType())) {
1675             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1676                  diag::err_assoc_compatible_types)
1677               << Types[j]->getTypeLoc().getSourceRange()
1678               << Types[j]->getType()
1679               << Types[i]->getType();
1680             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1681                  diag::note_compat_assoc)
1682               << Types[i]->getTypeLoc().getSourceRange()
1683               << Types[i]->getType();
1684             TypeErrorFound = true;
1685           }
1686       }
1687     }
1688   }
1689   if (TypeErrorFound)
1690     return ExprError();
1691 
1692   // If we determined that the generic selection is result-dependent, don't
1693   // try to compute the result expression.
1694   if (IsResultDependent)
1695     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1696                                         Exprs, DefaultLoc, RParenLoc,
1697                                         ContainsUnexpandedParameterPack);
1698 
1699   SmallVector<unsigned, 1> CompatIndices;
1700   unsigned DefaultIndex = -1U;
1701   for (unsigned i = 0; i < NumAssocs; ++i) {
1702     if (!Types[i])
1703       DefaultIndex = i;
1704     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1705                                         Types[i]->getType()))
1706       CompatIndices.push_back(i);
1707   }
1708 
1709   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1710   // type compatible with at most one of the types named in its generic
1711   // association list."
1712   if (CompatIndices.size() > 1) {
1713     // We strip parens here because the controlling expression is typically
1714     // parenthesized in macro definitions.
1715     ControllingExpr = ControllingExpr->IgnoreParens();
1716     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1717         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1718         << (unsigned)CompatIndices.size();
1719     for (unsigned I : CompatIndices) {
1720       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1721            diag::note_compat_assoc)
1722         << Types[I]->getTypeLoc().getSourceRange()
1723         << Types[I]->getType();
1724     }
1725     return ExprError();
1726   }
1727 
1728   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1729   // its controlling expression shall have type compatible with exactly one of
1730   // the types named in its generic association list."
1731   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1732     // We strip parens here because the controlling expression is typically
1733     // parenthesized in macro definitions.
1734     ControllingExpr = ControllingExpr->IgnoreParens();
1735     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1736         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1737     return ExprError();
1738   }
1739 
1740   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1741   // type name that is compatible with the type of the controlling expression,
1742   // then the result expression of the generic selection is the expression
1743   // in that generic association. Otherwise, the result expression of the
1744   // generic selection is the expression in the default generic association."
1745   unsigned ResultIndex =
1746     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1747 
1748   return GenericSelectionExpr::Create(
1749       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1750       ContainsUnexpandedParameterPack, ResultIndex);
1751 }
1752 
1753 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1754 /// location of the token and the offset of the ud-suffix within it.
1755 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1756                                      unsigned Offset) {
1757   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1758                                         S.getLangOpts());
1759 }
1760 
1761 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1762 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1763 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1764                                                  IdentifierInfo *UDSuffix,
1765                                                  SourceLocation UDSuffixLoc,
1766                                                  ArrayRef<Expr*> Args,
1767                                                  SourceLocation LitEndLoc) {
1768   assert(Args.size() <= 2 && "too many arguments for literal operator");
1769 
1770   QualType ArgTy[2];
1771   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1772     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1773     if (ArgTy[ArgIdx]->isArrayType())
1774       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1775   }
1776 
1777   DeclarationName OpName =
1778     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1779   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1780   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1781 
1782   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1783   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1784                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1785                               /*AllowStringTemplatePack*/ false,
1786                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1787     return ExprError();
1788 
1789   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1790 }
1791 
1792 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1793 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1794 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1795 /// multiple tokens.  However, the common case is that StringToks points to one
1796 /// string.
1797 ///
1798 ExprResult
1799 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1800   assert(!StringToks.empty() && "Must have at least one string!");
1801 
1802   StringLiteralParser Literal(StringToks, PP);
1803   if (Literal.hadError)
1804     return ExprError();
1805 
1806   SmallVector<SourceLocation, 4> StringTokLocs;
1807   for (const Token &Tok : StringToks)
1808     StringTokLocs.push_back(Tok.getLocation());
1809 
1810   QualType CharTy = Context.CharTy;
1811   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1812   if (Literal.isWide()) {
1813     CharTy = Context.getWideCharType();
1814     Kind = StringLiteral::Wide;
1815   } else if (Literal.isUTF8()) {
1816     if (getLangOpts().Char8)
1817       CharTy = Context.Char8Ty;
1818     Kind = StringLiteral::UTF8;
1819   } else if (Literal.isUTF16()) {
1820     CharTy = Context.Char16Ty;
1821     Kind = StringLiteral::UTF16;
1822   } else if (Literal.isUTF32()) {
1823     CharTy = Context.Char32Ty;
1824     Kind = StringLiteral::UTF32;
1825   } else if (Literal.isPascal()) {
1826     CharTy = Context.UnsignedCharTy;
1827   }
1828 
1829   // Warn on initializing an array of char from a u8 string literal; this
1830   // becomes ill-formed in C++2a.
1831   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1832       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1833     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1834 
1835     // Create removals for all 'u8' prefixes in the string literal(s). This
1836     // ensures C++2a compatibility (but may change the program behavior when
1837     // built by non-Clang compilers for which the execution character set is
1838     // not always UTF-8).
1839     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1840     SourceLocation RemovalDiagLoc;
1841     for (const Token &Tok : StringToks) {
1842       if (Tok.getKind() == tok::utf8_string_literal) {
1843         if (RemovalDiagLoc.isInvalid())
1844           RemovalDiagLoc = Tok.getLocation();
1845         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1846             Tok.getLocation(),
1847             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1848                                            getSourceManager(), getLangOpts())));
1849       }
1850     }
1851     Diag(RemovalDiagLoc, RemovalDiag);
1852   }
1853 
1854   QualType StrTy =
1855       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1856 
1857   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1858   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1859                                              Kind, Literal.Pascal, StrTy,
1860                                              &StringTokLocs[0],
1861                                              StringTokLocs.size());
1862   if (Literal.getUDSuffix().empty())
1863     return Lit;
1864 
1865   // We're building a user-defined literal.
1866   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1867   SourceLocation UDSuffixLoc =
1868     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1869                    Literal.getUDSuffixOffset());
1870 
1871   // Make sure we're allowed user-defined literals here.
1872   if (!UDLScope)
1873     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1874 
1875   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1876   //   operator "" X (str, len)
1877   QualType SizeType = Context.getSizeType();
1878 
1879   DeclarationName OpName =
1880     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1881   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1882   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1883 
1884   QualType ArgTy[] = {
1885     Context.getArrayDecayedType(StrTy), SizeType
1886   };
1887 
1888   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1889   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1890                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1891                                 /*AllowStringTemplatePack*/ true,
1892                                 /*DiagnoseMissing*/ true, Lit)) {
1893 
1894   case LOLR_Cooked: {
1895     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1896     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1897                                                     StringTokLocs[0]);
1898     Expr *Args[] = { Lit, LenArg };
1899 
1900     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1901   }
1902 
1903   case LOLR_Template: {
1904     TemplateArgumentListInfo ExplicitArgs;
1905     TemplateArgument Arg(Lit);
1906     TemplateArgumentLocInfo ArgInfo(Lit);
1907     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1908     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1909                                     &ExplicitArgs);
1910   }
1911 
1912   case LOLR_StringTemplatePack: {
1913     TemplateArgumentListInfo ExplicitArgs;
1914 
1915     unsigned CharBits = Context.getIntWidth(CharTy);
1916     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1917     llvm::APSInt Value(CharBits, CharIsUnsigned);
1918 
1919     TemplateArgument TypeArg(CharTy);
1920     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1921     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1922 
1923     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1924       Value = Lit->getCodeUnit(I);
1925       TemplateArgument Arg(Context, Value, CharTy);
1926       TemplateArgumentLocInfo ArgInfo;
1927       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1928     }
1929     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1930                                     &ExplicitArgs);
1931   }
1932   case LOLR_Raw:
1933   case LOLR_ErrorNoDiagnostic:
1934     llvm_unreachable("unexpected literal operator lookup result");
1935   case LOLR_Error:
1936     return ExprError();
1937   }
1938   llvm_unreachable("unexpected literal operator lookup result");
1939 }
1940 
1941 DeclRefExpr *
1942 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943                        SourceLocation Loc,
1944                        const CXXScopeSpec *SS) {
1945   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1946   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1947 }
1948 
1949 DeclRefExpr *
1950 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1951                        const DeclarationNameInfo &NameInfo,
1952                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1953                        SourceLocation TemplateKWLoc,
1954                        const TemplateArgumentListInfo *TemplateArgs) {
1955   NestedNameSpecifierLoc NNS =
1956       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1957   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1958                           TemplateArgs);
1959 }
1960 
1961 // CUDA/HIP: Check whether a captured reference variable is referencing a
1962 // host variable in a device or host device lambda.
1963 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1964                                                             VarDecl *VD) {
1965   if (!S.getLangOpts().CUDA || !VD->hasInit())
1966     return false;
1967   assert(VD->getType()->isReferenceType());
1968 
1969   // Check whether the reference variable is referencing a host variable.
1970   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1971   if (!DRE)
1972     return false;
1973   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1974   if (!Referee || !Referee->hasGlobalStorage() ||
1975       Referee->hasAttr<CUDADeviceAttr>())
1976     return false;
1977 
1978   // Check whether the current function is a device or host device lambda.
1979   // Check whether the reference variable is a capture by getDeclContext()
1980   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1981   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1982   if (MD && MD->getParent()->isLambda() &&
1983       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1984       VD->getDeclContext() != MD)
1985     return true;
1986 
1987   return false;
1988 }
1989 
1990 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1991   // A declaration named in an unevaluated operand never constitutes an odr-use.
1992   if (isUnevaluatedContext())
1993     return NOUR_Unevaluated;
1994 
1995   // C++2a [basic.def.odr]p4:
1996   //   A variable x whose name appears as a potentially-evaluated expression e
1997   //   is odr-used by e unless [...] x is a reference that is usable in
1998   //   constant expressions.
1999   // CUDA/HIP:
2000   //   If a reference variable referencing a host variable is captured in a
2001   //   device or host device lambda, the value of the referee must be copied
2002   //   to the capture and the reference variable must be treated as odr-use
2003   //   since the value of the referee is not known at compile time and must
2004   //   be loaded from the captured.
2005   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2006     if (VD->getType()->isReferenceType() &&
2007         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2008         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2009         VD->isUsableInConstantExpressions(Context))
2010       return NOUR_Constant;
2011   }
2012 
2013   // All remaining non-variable cases constitute an odr-use. For variables, we
2014   // need to wait and see how the expression is used.
2015   return NOUR_None;
2016 }
2017 
2018 /// BuildDeclRefExpr - Build an expression that references a
2019 /// declaration that does not require a closure capture.
2020 DeclRefExpr *
2021 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2022                        const DeclarationNameInfo &NameInfo,
2023                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2024                        SourceLocation TemplateKWLoc,
2025                        const TemplateArgumentListInfo *TemplateArgs) {
2026   bool RefersToCapturedVariable =
2027       isa<VarDecl>(D) &&
2028       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2029 
2030   DeclRefExpr *E = DeclRefExpr::Create(
2031       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2032       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2033   MarkDeclRefReferenced(E);
2034 
2035   // C++ [except.spec]p17:
2036   //   An exception-specification is considered to be needed when:
2037   //   - in an expression, the function is the unique lookup result or
2038   //     the selected member of a set of overloaded functions.
2039   //
2040   // We delay doing this until after we've built the function reference and
2041   // marked it as used so that:
2042   //  a) if the function is defaulted, we get errors from defining it before /
2043   //     instead of errors from computing its exception specification, and
2044   //  b) if the function is a defaulted comparison, we can use the body we
2045   //     build when defining it as input to the exception specification
2046   //     computation rather than computing a new body.
2047   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2048     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2049       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2050         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2051     }
2052   }
2053 
2054   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2055       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2056       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2057     getCurFunction()->recordUseOfWeak(E);
2058 
2059   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2060   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2061     FD = IFD->getAnonField();
2062   if (FD) {
2063     UnusedPrivateFields.remove(FD);
2064     // Just in case we're building an illegal pointer-to-member.
2065     if (FD->isBitField())
2066       E->setObjectKind(OK_BitField);
2067   }
2068 
2069   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2070   // designates a bit-field.
2071   if (auto *BD = dyn_cast<BindingDecl>(D))
2072     if (auto *BE = BD->getBinding())
2073       E->setObjectKind(BE->getObjectKind());
2074 
2075   return E;
2076 }
2077 
2078 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2079 /// possibly a list of template arguments.
2080 ///
2081 /// If this produces template arguments, it is permitted to call
2082 /// DecomposeTemplateName.
2083 ///
2084 /// This actually loses a lot of source location information for
2085 /// non-standard name kinds; we should consider preserving that in
2086 /// some way.
2087 void
2088 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2089                              TemplateArgumentListInfo &Buffer,
2090                              DeclarationNameInfo &NameInfo,
2091                              const TemplateArgumentListInfo *&TemplateArgs) {
2092   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2093     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2094     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2095 
2096     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2097                                        Id.TemplateId->NumArgs);
2098     translateTemplateArguments(TemplateArgsPtr, Buffer);
2099 
2100     TemplateName TName = Id.TemplateId->Template.get();
2101     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2102     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2103     TemplateArgs = &Buffer;
2104   } else {
2105     NameInfo = GetNameFromUnqualifiedId(Id);
2106     TemplateArgs = nullptr;
2107   }
2108 }
2109 
2110 static void emitEmptyLookupTypoDiagnostic(
2111     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2112     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2113     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2114   DeclContext *Ctx =
2115       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2116   if (!TC) {
2117     // Emit a special diagnostic for failed member lookups.
2118     // FIXME: computing the declaration context might fail here (?)
2119     if (Ctx)
2120       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2121                                                  << SS.getRange();
2122     else
2123       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2124     return;
2125   }
2126 
2127   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2128   bool DroppedSpecifier =
2129       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2130   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2131                         ? diag::note_implicit_param_decl
2132                         : diag::note_previous_decl;
2133   if (!Ctx)
2134     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2135                          SemaRef.PDiag(NoteID));
2136   else
2137     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2138                                  << Typo << Ctx << DroppedSpecifier
2139                                  << SS.getRange(),
2140                          SemaRef.PDiag(NoteID));
2141 }
2142 
2143 /// Diagnose a lookup that found results in an enclosing class during error
2144 /// recovery. This usually indicates that the results were found in a dependent
2145 /// base class that could not be searched as part of a template definition.
2146 /// Always issues a diagnostic (though this may be only a warning in MS
2147 /// compatibility mode).
2148 ///
2149 /// Return \c true if the error is unrecoverable, or \c false if the caller
2150 /// should attempt to recover using these lookup results.
2151 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2152   // During a default argument instantiation the CurContext points
2153   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2154   // function parameter list, hence add an explicit check.
2155   bool isDefaultArgument =
2156       !CodeSynthesisContexts.empty() &&
2157       CodeSynthesisContexts.back().Kind ==
2158           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2159   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2160   bool isInstance = CurMethod && CurMethod->isInstance() &&
2161                     R.getNamingClass() == CurMethod->getParent() &&
2162                     !isDefaultArgument;
2163 
2164   // There are two ways we can find a class-scope declaration during template
2165   // instantiation that we did not find in the template definition: if it is a
2166   // member of a dependent base class, or if it is declared after the point of
2167   // use in the same class. Distinguish these by comparing the class in which
2168   // the member was found to the naming class of the lookup.
2169   unsigned DiagID = diag::err_found_in_dependent_base;
2170   unsigned NoteID = diag::note_member_declared_at;
2171   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2172     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2173                                       : diag::err_found_later_in_class;
2174   } else if (getLangOpts().MSVCCompat) {
2175     DiagID = diag::ext_found_in_dependent_base;
2176     NoteID = diag::note_dependent_member_use;
2177   }
2178 
2179   if (isInstance) {
2180     // Give a code modification hint to insert 'this->'.
2181     Diag(R.getNameLoc(), DiagID)
2182         << R.getLookupName()
2183         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2184     CheckCXXThisCapture(R.getNameLoc());
2185   } else {
2186     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2187     // they're not shadowed).
2188     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2189   }
2190 
2191   for (NamedDecl *D : R)
2192     Diag(D->getLocation(), NoteID);
2193 
2194   // Return true if we are inside a default argument instantiation
2195   // and the found name refers to an instance member function, otherwise
2196   // the caller will try to create an implicit member call and this is wrong
2197   // for default arguments.
2198   //
2199   // FIXME: Is this special case necessary? We could allow the caller to
2200   // diagnose this.
2201   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2202     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2203     return true;
2204   }
2205 
2206   // Tell the callee to try to recover.
2207   return false;
2208 }
2209 
2210 /// Diagnose an empty lookup.
2211 ///
2212 /// \return false if new lookup candidates were found
2213 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2214                                CorrectionCandidateCallback &CCC,
2215                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2216                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2217   DeclarationName Name = R.getLookupName();
2218 
2219   unsigned diagnostic = diag::err_undeclared_var_use;
2220   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2221   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2222       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2223       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2224     diagnostic = diag::err_undeclared_use;
2225     diagnostic_suggest = diag::err_undeclared_use_suggest;
2226   }
2227 
2228   // If the original lookup was an unqualified lookup, fake an
2229   // unqualified lookup.  This is useful when (for example) the
2230   // original lookup would not have found something because it was a
2231   // dependent name.
2232   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2233   while (DC) {
2234     if (isa<CXXRecordDecl>(DC)) {
2235       LookupQualifiedName(R, DC);
2236 
2237       if (!R.empty()) {
2238         // Don't give errors about ambiguities in this lookup.
2239         R.suppressDiagnostics();
2240 
2241         // If there's a best viable function among the results, only mention
2242         // that one in the notes.
2243         OverloadCandidateSet Candidates(R.getNameLoc(),
2244                                         OverloadCandidateSet::CSK_Normal);
2245         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2246         OverloadCandidateSet::iterator Best;
2247         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2248             OR_Success) {
2249           R.clear();
2250           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2251           R.resolveKind();
2252         }
2253 
2254         return DiagnoseDependentMemberLookup(R);
2255       }
2256 
2257       R.clear();
2258     }
2259 
2260     DC = DC->getLookupParent();
2261   }
2262 
2263   // We didn't find anything, so try to correct for a typo.
2264   TypoCorrection Corrected;
2265   if (S && Out) {
2266     SourceLocation TypoLoc = R.getNameLoc();
2267     assert(!ExplicitTemplateArgs &&
2268            "Diagnosing an empty lookup with explicit template args!");
2269     *Out = CorrectTypoDelayed(
2270         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2271         [=](const TypoCorrection &TC) {
2272           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2273                                         diagnostic, diagnostic_suggest);
2274         },
2275         nullptr, CTK_ErrorRecovery);
2276     if (*Out)
2277       return true;
2278   } else if (S &&
2279              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2280                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2281     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2282     bool DroppedSpecifier =
2283         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2284     R.setLookupName(Corrected.getCorrection());
2285 
2286     bool AcceptableWithRecovery = false;
2287     bool AcceptableWithoutRecovery = false;
2288     NamedDecl *ND = Corrected.getFoundDecl();
2289     if (ND) {
2290       if (Corrected.isOverloaded()) {
2291         OverloadCandidateSet OCS(R.getNameLoc(),
2292                                  OverloadCandidateSet::CSK_Normal);
2293         OverloadCandidateSet::iterator Best;
2294         for (NamedDecl *CD : Corrected) {
2295           if (FunctionTemplateDecl *FTD =
2296                    dyn_cast<FunctionTemplateDecl>(CD))
2297             AddTemplateOverloadCandidate(
2298                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2299                 Args, OCS);
2300           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2301             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2302               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2303                                    Args, OCS);
2304         }
2305         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2306         case OR_Success:
2307           ND = Best->FoundDecl;
2308           Corrected.setCorrectionDecl(ND);
2309           break;
2310         default:
2311           // FIXME: Arbitrarily pick the first declaration for the note.
2312           Corrected.setCorrectionDecl(ND);
2313           break;
2314         }
2315       }
2316       R.addDecl(ND);
2317       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2318         CXXRecordDecl *Record = nullptr;
2319         if (Corrected.getCorrectionSpecifier()) {
2320           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2321           Record = Ty->getAsCXXRecordDecl();
2322         }
2323         if (!Record)
2324           Record = cast<CXXRecordDecl>(
2325               ND->getDeclContext()->getRedeclContext());
2326         R.setNamingClass(Record);
2327       }
2328 
2329       auto *UnderlyingND = ND->getUnderlyingDecl();
2330       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2331                                isa<FunctionTemplateDecl>(UnderlyingND);
2332       // FIXME: If we ended up with a typo for a type name or
2333       // Objective-C class name, we're in trouble because the parser
2334       // is in the wrong place to recover. Suggest the typo
2335       // correction, but don't make it a fix-it since we're not going
2336       // to recover well anyway.
2337       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2338                                   getAsTypeTemplateDecl(UnderlyingND) ||
2339                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2340     } else {
2341       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2342       // because we aren't able to recover.
2343       AcceptableWithoutRecovery = true;
2344     }
2345 
2346     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2347       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2348                             ? diag::note_implicit_param_decl
2349                             : diag::note_previous_decl;
2350       if (SS.isEmpty())
2351         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2352                      PDiag(NoteID), AcceptableWithRecovery);
2353       else
2354         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2355                                   << Name << computeDeclContext(SS, false)
2356                                   << DroppedSpecifier << SS.getRange(),
2357                      PDiag(NoteID), AcceptableWithRecovery);
2358 
2359       // Tell the callee whether to try to recover.
2360       return !AcceptableWithRecovery;
2361     }
2362   }
2363   R.clear();
2364 
2365   // Emit a special diagnostic for failed member lookups.
2366   // FIXME: computing the declaration context might fail here (?)
2367   if (!SS.isEmpty()) {
2368     Diag(R.getNameLoc(), diag::err_no_member)
2369       << Name << computeDeclContext(SS, false)
2370       << SS.getRange();
2371     return true;
2372   }
2373 
2374   // Give up, we can't recover.
2375   Diag(R.getNameLoc(), diagnostic) << Name;
2376   return true;
2377 }
2378 
2379 /// In Microsoft mode, if we are inside a template class whose parent class has
2380 /// dependent base classes, and we can't resolve an unqualified identifier, then
2381 /// assume the identifier is a member of a dependent base class.  We can only
2382 /// recover successfully in static methods, instance methods, and other contexts
2383 /// where 'this' is available.  This doesn't precisely match MSVC's
2384 /// instantiation model, but it's close enough.
2385 static Expr *
2386 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2387                                DeclarationNameInfo &NameInfo,
2388                                SourceLocation TemplateKWLoc,
2389                                const TemplateArgumentListInfo *TemplateArgs) {
2390   // Only try to recover from lookup into dependent bases in static methods or
2391   // contexts where 'this' is available.
2392   QualType ThisType = S.getCurrentThisType();
2393   const CXXRecordDecl *RD = nullptr;
2394   if (!ThisType.isNull())
2395     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2396   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2397     RD = MD->getParent();
2398   if (!RD || !RD->hasAnyDependentBases())
2399     return nullptr;
2400 
2401   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2402   // is available, suggest inserting 'this->' as a fixit.
2403   SourceLocation Loc = NameInfo.getLoc();
2404   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2405   DB << NameInfo.getName() << RD;
2406 
2407   if (!ThisType.isNull()) {
2408     DB << FixItHint::CreateInsertion(Loc, "this->");
2409     return CXXDependentScopeMemberExpr::Create(
2410         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2411         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2412         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2413   }
2414 
2415   // Synthesize a fake NNS that points to the derived class.  This will
2416   // perform name lookup during template instantiation.
2417   CXXScopeSpec SS;
2418   auto *NNS =
2419       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2420   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2421   return DependentScopeDeclRefExpr::Create(
2422       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2423       TemplateArgs);
2424 }
2425 
2426 ExprResult
2427 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2428                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2429                         bool HasTrailingLParen, bool IsAddressOfOperand,
2430                         CorrectionCandidateCallback *CCC,
2431                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2432   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2433          "cannot be direct & operand and have a trailing lparen");
2434   if (SS.isInvalid())
2435     return ExprError();
2436 
2437   TemplateArgumentListInfo TemplateArgsBuffer;
2438 
2439   // Decompose the UnqualifiedId into the following data.
2440   DeclarationNameInfo NameInfo;
2441   const TemplateArgumentListInfo *TemplateArgs;
2442   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2443 
2444   DeclarationName Name = NameInfo.getName();
2445   IdentifierInfo *II = Name.getAsIdentifierInfo();
2446   SourceLocation NameLoc = NameInfo.getLoc();
2447 
2448   if (II && II->isEditorPlaceholder()) {
2449     // FIXME: When typed placeholders are supported we can create a typed
2450     // placeholder expression node.
2451     return ExprError();
2452   }
2453 
2454   // C++ [temp.dep.expr]p3:
2455   //   An id-expression is type-dependent if it contains:
2456   //     -- an identifier that was declared with a dependent type,
2457   //        (note: handled after lookup)
2458   //     -- a template-id that is dependent,
2459   //        (note: handled in BuildTemplateIdExpr)
2460   //     -- a conversion-function-id that specifies a dependent type,
2461   //     -- a nested-name-specifier that contains a class-name that
2462   //        names a dependent type.
2463   // Determine whether this is a member of an unknown specialization;
2464   // we need to handle these differently.
2465   bool DependentID = false;
2466   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2467       Name.getCXXNameType()->isDependentType()) {
2468     DependentID = true;
2469   } else if (SS.isSet()) {
2470     if (DeclContext *DC = computeDeclContext(SS, false)) {
2471       if (RequireCompleteDeclContext(SS, DC))
2472         return ExprError();
2473     } else {
2474       DependentID = true;
2475     }
2476   }
2477 
2478   if (DependentID)
2479     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2480                                       IsAddressOfOperand, TemplateArgs);
2481 
2482   // Perform the required lookup.
2483   LookupResult R(*this, NameInfo,
2484                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2485                      ? LookupObjCImplicitSelfParam
2486                      : LookupOrdinaryName);
2487   if (TemplateKWLoc.isValid() || TemplateArgs) {
2488     // Lookup the template name again to correctly establish the context in
2489     // which it was found. This is really unfortunate as we already did the
2490     // lookup to determine that it was a template name in the first place. If
2491     // this becomes a performance hit, we can work harder to preserve those
2492     // results until we get here but it's likely not worth it.
2493     bool MemberOfUnknownSpecialization;
2494     AssumedTemplateKind AssumedTemplate;
2495     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2496                            MemberOfUnknownSpecialization, TemplateKWLoc,
2497                            &AssumedTemplate))
2498       return ExprError();
2499 
2500     if (MemberOfUnknownSpecialization ||
2501         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2502       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2503                                         IsAddressOfOperand, TemplateArgs);
2504   } else {
2505     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2506     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2507 
2508     // If the result might be in a dependent base class, this is a dependent
2509     // id-expression.
2510     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2511       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2512                                         IsAddressOfOperand, TemplateArgs);
2513 
2514     // If this reference is in an Objective-C method, then we need to do
2515     // some special Objective-C lookup, too.
2516     if (IvarLookupFollowUp) {
2517       ExprResult E(LookupInObjCMethod(R, S, II, true));
2518       if (E.isInvalid())
2519         return ExprError();
2520 
2521       if (Expr *Ex = E.getAs<Expr>())
2522         return Ex;
2523     }
2524   }
2525 
2526   if (R.isAmbiguous())
2527     return ExprError();
2528 
2529   // This could be an implicitly declared function reference (legal in C90,
2530   // extension in C99, forbidden in C++).
2531   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2532     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2533     if (D) R.addDecl(D);
2534   }
2535 
2536   // Determine whether this name might be a candidate for
2537   // argument-dependent lookup.
2538   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2539 
2540   if (R.empty() && !ADL) {
2541     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2542       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2543                                                    TemplateKWLoc, TemplateArgs))
2544         return E;
2545     }
2546 
2547     // Don't diagnose an empty lookup for inline assembly.
2548     if (IsInlineAsmIdentifier)
2549       return ExprError();
2550 
2551     // If this name wasn't predeclared and if this is not a function
2552     // call, diagnose the problem.
2553     TypoExpr *TE = nullptr;
2554     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2555                                                        : nullptr);
2556     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2557     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2558            "Typo correction callback misconfigured");
2559     if (CCC) {
2560       // Make sure the callback knows what the typo being diagnosed is.
2561       CCC->setTypoName(II);
2562       if (SS.isValid())
2563         CCC->setTypoNNS(SS.getScopeRep());
2564     }
2565     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2566     // a template name, but we happen to have always already looked up the name
2567     // before we get here if it must be a template name.
2568     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2569                             None, &TE)) {
2570       if (TE && KeywordReplacement) {
2571         auto &State = getTypoExprState(TE);
2572         auto BestTC = State.Consumer->getNextCorrection();
2573         if (BestTC.isKeyword()) {
2574           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2575           if (State.DiagHandler)
2576             State.DiagHandler(BestTC);
2577           KeywordReplacement->startToken();
2578           KeywordReplacement->setKind(II->getTokenID());
2579           KeywordReplacement->setIdentifierInfo(II);
2580           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2581           // Clean up the state associated with the TypoExpr, since it has
2582           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2583           clearDelayedTypo(TE);
2584           // Signal that a correction to a keyword was performed by returning a
2585           // valid-but-null ExprResult.
2586           return (Expr*)nullptr;
2587         }
2588         State.Consumer->resetCorrectionStream();
2589       }
2590       return TE ? TE : ExprError();
2591     }
2592 
2593     assert(!R.empty() &&
2594            "DiagnoseEmptyLookup returned false but added no results");
2595 
2596     // If we found an Objective-C instance variable, let
2597     // LookupInObjCMethod build the appropriate expression to
2598     // reference the ivar.
2599     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2600       R.clear();
2601       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2602       // In a hopelessly buggy code, Objective-C instance variable
2603       // lookup fails and no expression will be built to reference it.
2604       if (!E.isInvalid() && !E.get())
2605         return ExprError();
2606       return E;
2607     }
2608   }
2609 
2610   // This is guaranteed from this point on.
2611   assert(!R.empty() || ADL);
2612 
2613   // Check whether this might be a C++ implicit instance member access.
2614   // C++ [class.mfct.non-static]p3:
2615   //   When an id-expression that is not part of a class member access
2616   //   syntax and not used to form a pointer to member is used in the
2617   //   body of a non-static member function of class X, if name lookup
2618   //   resolves the name in the id-expression to a non-static non-type
2619   //   member of some class C, the id-expression is transformed into a
2620   //   class member access expression using (*this) as the
2621   //   postfix-expression to the left of the . operator.
2622   //
2623   // But we don't actually need to do this for '&' operands if R
2624   // resolved to a function or overloaded function set, because the
2625   // expression is ill-formed if it actually works out to be a
2626   // non-static member function:
2627   //
2628   // C++ [expr.ref]p4:
2629   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2630   //   [t]he expression can be used only as the left-hand operand of a
2631   //   member function call.
2632   //
2633   // There are other safeguards against such uses, but it's important
2634   // to get this right here so that we don't end up making a
2635   // spuriously dependent expression if we're inside a dependent
2636   // instance method.
2637   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2638     bool MightBeImplicitMember;
2639     if (!IsAddressOfOperand)
2640       MightBeImplicitMember = true;
2641     else if (!SS.isEmpty())
2642       MightBeImplicitMember = false;
2643     else if (R.isOverloadedResult())
2644       MightBeImplicitMember = false;
2645     else if (R.isUnresolvableResult())
2646       MightBeImplicitMember = true;
2647     else
2648       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2649                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2650                               isa<MSPropertyDecl>(R.getFoundDecl());
2651 
2652     if (MightBeImplicitMember)
2653       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2654                                              R, TemplateArgs, S);
2655   }
2656 
2657   if (TemplateArgs || TemplateKWLoc.isValid()) {
2658 
2659     // In C++1y, if this is a variable template id, then check it
2660     // in BuildTemplateIdExpr().
2661     // The single lookup result must be a variable template declaration.
2662     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2663         Id.TemplateId->Kind == TNK_Var_template) {
2664       assert(R.getAsSingle<VarTemplateDecl>() &&
2665              "There should only be one declaration found.");
2666     }
2667 
2668     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2669   }
2670 
2671   return BuildDeclarationNameExpr(SS, R, ADL);
2672 }
2673 
2674 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2675 /// declaration name, generally during template instantiation.
2676 /// There's a large number of things which don't need to be done along
2677 /// this path.
2678 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2679     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2680     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2681   DeclContext *DC = computeDeclContext(SS, false);
2682   if (!DC)
2683     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2684                                      NameInfo, /*TemplateArgs=*/nullptr);
2685 
2686   if (RequireCompleteDeclContext(SS, DC))
2687     return ExprError();
2688 
2689   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2690   LookupQualifiedName(R, DC);
2691 
2692   if (R.isAmbiguous())
2693     return ExprError();
2694 
2695   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2696     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2697                                      NameInfo, /*TemplateArgs=*/nullptr);
2698 
2699   if (R.empty()) {
2700     // Don't diagnose problems with invalid record decl, the secondary no_member
2701     // diagnostic during template instantiation is likely bogus, e.g. if a class
2702     // is invalid because it's derived from an invalid base class, then missing
2703     // members were likely supposed to be inherited.
2704     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2705       if (CD->isInvalidDecl())
2706         return ExprError();
2707     Diag(NameInfo.getLoc(), diag::err_no_member)
2708       << NameInfo.getName() << DC << SS.getRange();
2709     return ExprError();
2710   }
2711 
2712   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2713     // Diagnose a missing typename if this resolved unambiguously to a type in
2714     // a dependent context.  If we can recover with a type, downgrade this to
2715     // a warning in Microsoft compatibility mode.
2716     unsigned DiagID = diag::err_typename_missing;
2717     if (RecoveryTSI && getLangOpts().MSVCCompat)
2718       DiagID = diag::ext_typename_missing;
2719     SourceLocation Loc = SS.getBeginLoc();
2720     auto D = Diag(Loc, DiagID);
2721     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2722       << SourceRange(Loc, NameInfo.getEndLoc());
2723 
2724     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2725     // context.
2726     if (!RecoveryTSI)
2727       return ExprError();
2728 
2729     // Only issue the fixit if we're prepared to recover.
2730     D << FixItHint::CreateInsertion(Loc, "typename ");
2731 
2732     // Recover by pretending this was an elaborated type.
2733     QualType Ty = Context.getTypeDeclType(TD);
2734     TypeLocBuilder TLB;
2735     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2736 
2737     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2738     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2739     QTL.setElaboratedKeywordLoc(SourceLocation());
2740     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2741 
2742     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2743 
2744     return ExprEmpty();
2745   }
2746 
2747   // Defend against this resolving to an implicit member access. We usually
2748   // won't get here if this might be a legitimate a class member (we end up in
2749   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2750   // a pointer-to-member or in an unevaluated context in C++11.
2751   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2752     return BuildPossibleImplicitMemberExpr(SS,
2753                                            /*TemplateKWLoc=*/SourceLocation(),
2754                                            R, /*TemplateArgs=*/nullptr, S);
2755 
2756   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2757 }
2758 
2759 /// The parser has read a name in, and Sema has detected that we're currently
2760 /// inside an ObjC method. Perform some additional checks and determine if we
2761 /// should form a reference to an ivar.
2762 ///
2763 /// Ideally, most of this would be done by lookup, but there's
2764 /// actually quite a lot of extra work involved.
2765 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2766                                         IdentifierInfo *II) {
2767   SourceLocation Loc = Lookup.getNameLoc();
2768   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2769 
2770   // Check for error condition which is already reported.
2771   if (!CurMethod)
2772     return DeclResult(true);
2773 
2774   // There are two cases to handle here.  1) scoped lookup could have failed,
2775   // in which case we should look for an ivar.  2) scoped lookup could have
2776   // found a decl, but that decl is outside the current instance method (i.e.
2777   // a global variable).  In these two cases, we do a lookup for an ivar with
2778   // this name, if the lookup sucedes, we replace it our current decl.
2779 
2780   // If we're in a class method, we don't normally want to look for
2781   // ivars.  But if we don't find anything else, and there's an
2782   // ivar, that's an error.
2783   bool IsClassMethod = CurMethod->isClassMethod();
2784 
2785   bool LookForIvars;
2786   if (Lookup.empty())
2787     LookForIvars = true;
2788   else if (IsClassMethod)
2789     LookForIvars = false;
2790   else
2791     LookForIvars = (Lookup.isSingleResult() &&
2792                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2793   ObjCInterfaceDecl *IFace = nullptr;
2794   if (LookForIvars) {
2795     IFace = CurMethod->getClassInterface();
2796     ObjCInterfaceDecl *ClassDeclared;
2797     ObjCIvarDecl *IV = nullptr;
2798     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2799       // Diagnose using an ivar in a class method.
2800       if (IsClassMethod) {
2801         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2802         return DeclResult(true);
2803       }
2804 
2805       // Diagnose the use of an ivar outside of the declaring class.
2806       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2807           !declaresSameEntity(ClassDeclared, IFace) &&
2808           !getLangOpts().DebuggerSupport)
2809         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2810 
2811       // Success.
2812       return IV;
2813     }
2814   } else if (CurMethod->isInstanceMethod()) {
2815     // We should warn if a local variable hides an ivar.
2816     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2817       ObjCInterfaceDecl *ClassDeclared;
2818       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2819         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2820             declaresSameEntity(IFace, ClassDeclared))
2821           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2822       }
2823     }
2824   } else if (Lookup.isSingleResult() &&
2825              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2826     // If accessing a stand-alone ivar in a class method, this is an error.
2827     if (const ObjCIvarDecl *IV =
2828             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2829       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2830       return DeclResult(true);
2831     }
2832   }
2833 
2834   // Didn't encounter an error, didn't find an ivar.
2835   return DeclResult(false);
2836 }
2837 
2838 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2839                                   ObjCIvarDecl *IV) {
2840   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2841   assert(CurMethod && CurMethod->isInstanceMethod() &&
2842          "should not reference ivar from this context");
2843 
2844   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2845   assert(IFace && "should not reference ivar from this context");
2846 
2847   // If we're referencing an invalid decl, just return this as a silent
2848   // error node.  The error diagnostic was already emitted on the decl.
2849   if (IV->isInvalidDecl())
2850     return ExprError();
2851 
2852   // Check if referencing a field with __attribute__((deprecated)).
2853   if (DiagnoseUseOfDecl(IV, Loc))
2854     return ExprError();
2855 
2856   // FIXME: This should use a new expr for a direct reference, don't
2857   // turn this into Self->ivar, just return a BareIVarExpr or something.
2858   IdentifierInfo &II = Context.Idents.get("self");
2859   UnqualifiedId SelfName;
2860   SelfName.setImplicitSelfParam(&II);
2861   CXXScopeSpec SelfScopeSpec;
2862   SourceLocation TemplateKWLoc;
2863   ExprResult SelfExpr =
2864       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2865                         /*HasTrailingLParen=*/false,
2866                         /*IsAddressOfOperand=*/false);
2867   if (SelfExpr.isInvalid())
2868     return ExprError();
2869 
2870   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2871   if (SelfExpr.isInvalid())
2872     return ExprError();
2873 
2874   MarkAnyDeclReferenced(Loc, IV, true);
2875 
2876   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2877   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2878       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2879     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2880 
2881   ObjCIvarRefExpr *Result = new (Context)
2882       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2883                       IV->getLocation(), SelfExpr.get(), true, true);
2884 
2885   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2886     if (!isUnevaluatedContext() &&
2887         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2888       getCurFunction()->recordUseOfWeak(Result);
2889   }
2890   if (getLangOpts().ObjCAutoRefCount)
2891     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2892       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2893 
2894   return Result;
2895 }
2896 
2897 /// The parser has read a name in, and Sema has detected that we're currently
2898 /// inside an ObjC method. Perform some additional checks and determine if we
2899 /// should form a reference to an ivar. If so, build an expression referencing
2900 /// that ivar.
2901 ExprResult
2902 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2903                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2904   // FIXME: Integrate this lookup step into LookupParsedName.
2905   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2906   if (Ivar.isInvalid())
2907     return ExprError();
2908   if (Ivar.isUsable())
2909     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2910                             cast<ObjCIvarDecl>(Ivar.get()));
2911 
2912   if (Lookup.empty() && II && AllowBuiltinCreation)
2913     LookupBuiltin(Lookup);
2914 
2915   // Sentinel value saying that we didn't do anything special.
2916   return ExprResult(false);
2917 }
2918 
2919 /// Cast a base object to a member's actual type.
2920 ///
2921 /// There are two relevant checks:
2922 ///
2923 /// C++ [class.access.base]p7:
2924 ///
2925 ///   If a class member access operator [...] is used to access a non-static
2926 ///   data member or non-static member function, the reference is ill-formed if
2927 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2928 ///   naming class of the right operand.
2929 ///
2930 /// C++ [expr.ref]p7:
2931 ///
2932 ///   If E2 is a non-static data member or a non-static member function, the
2933 ///   program is ill-formed if the class of which E2 is directly a member is an
2934 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2935 ///
2936 /// Note that the latter check does not consider access; the access of the
2937 /// "real" base class is checked as appropriate when checking the access of the
2938 /// member name.
2939 ExprResult
2940 Sema::PerformObjectMemberConversion(Expr *From,
2941                                     NestedNameSpecifier *Qualifier,
2942                                     NamedDecl *FoundDecl,
2943                                     NamedDecl *Member) {
2944   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2945   if (!RD)
2946     return From;
2947 
2948   QualType DestRecordType;
2949   QualType DestType;
2950   QualType FromRecordType;
2951   QualType FromType = From->getType();
2952   bool PointerConversions = false;
2953   if (isa<FieldDecl>(Member)) {
2954     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2955     auto FromPtrType = FromType->getAs<PointerType>();
2956     DestRecordType = Context.getAddrSpaceQualType(
2957         DestRecordType, FromPtrType
2958                             ? FromType->getPointeeType().getAddressSpace()
2959                             : FromType.getAddressSpace());
2960 
2961     if (FromPtrType) {
2962       DestType = Context.getPointerType(DestRecordType);
2963       FromRecordType = FromPtrType->getPointeeType();
2964       PointerConversions = true;
2965     } else {
2966       DestType = DestRecordType;
2967       FromRecordType = FromType;
2968     }
2969   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2970     if (Method->isStatic())
2971       return From;
2972 
2973     DestType = Method->getThisType();
2974     DestRecordType = DestType->getPointeeType();
2975 
2976     if (FromType->getAs<PointerType>()) {
2977       FromRecordType = FromType->getPointeeType();
2978       PointerConversions = true;
2979     } else {
2980       FromRecordType = FromType;
2981       DestType = DestRecordType;
2982     }
2983 
2984     LangAS FromAS = FromRecordType.getAddressSpace();
2985     LangAS DestAS = DestRecordType.getAddressSpace();
2986     if (FromAS != DestAS) {
2987       QualType FromRecordTypeWithoutAS =
2988           Context.removeAddrSpaceQualType(FromRecordType);
2989       QualType FromTypeWithDestAS =
2990           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2991       if (PointerConversions)
2992         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2993       From = ImpCastExprToType(From, FromTypeWithDestAS,
2994                                CK_AddressSpaceConversion, From->getValueKind())
2995                  .get();
2996     }
2997   } else {
2998     // No conversion necessary.
2999     return From;
3000   }
3001 
3002   if (DestType->isDependentType() || FromType->isDependentType())
3003     return From;
3004 
3005   // If the unqualified types are the same, no conversion is necessary.
3006   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3007     return From;
3008 
3009   SourceRange FromRange = From->getSourceRange();
3010   SourceLocation FromLoc = FromRange.getBegin();
3011 
3012   ExprValueKind VK = From->getValueKind();
3013 
3014   // C++ [class.member.lookup]p8:
3015   //   [...] Ambiguities can often be resolved by qualifying a name with its
3016   //   class name.
3017   //
3018   // If the member was a qualified name and the qualified referred to a
3019   // specific base subobject type, we'll cast to that intermediate type
3020   // first and then to the object in which the member is declared. That allows
3021   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3022   //
3023   //   class Base { public: int x; };
3024   //   class Derived1 : public Base { };
3025   //   class Derived2 : public Base { };
3026   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3027   //
3028   //   void VeryDerived::f() {
3029   //     x = 17; // error: ambiguous base subobjects
3030   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3031   //   }
3032   if (Qualifier && Qualifier->getAsType()) {
3033     QualType QType = QualType(Qualifier->getAsType(), 0);
3034     assert(QType->isRecordType() && "lookup done with non-record type");
3035 
3036     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3037 
3038     // In C++98, the qualifier type doesn't actually have to be a base
3039     // type of the object type, in which case we just ignore it.
3040     // Otherwise build the appropriate casts.
3041     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3042       CXXCastPath BasePath;
3043       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3044                                        FromLoc, FromRange, &BasePath))
3045         return ExprError();
3046 
3047       if (PointerConversions)
3048         QType = Context.getPointerType(QType);
3049       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3050                                VK, &BasePath).get();
3051 
3052       FromType = QType;
3053       FromRecordType = QRecordType;
3054 
3055       // If the qualifier type was the same as the destination type,
3056       // we're done.
3057       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3058         return From;
3059     }
3060   }
3061 
3062   CXXCastPath BasePath;
3063   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3064                                    FromLoc, FromRange, &BasePath,
3065                                    /*IgnoreAccess=*/true))
3066     return ExprError();
3067 
3068   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3069                            VK, &BasePath);
3070 }
3071 
3072 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3073                                       const LookupResult &R,
3074                                       bool HasTrailingLParen) {
3075   // Only when used directly as the postfix-expression of a call.
3076   if (!HasTrailingLParen)
3077     return false;
3078 
3079   // Never if a scope specifier was provided.
3080   if (SS.isSet())
3081     return false;
3082 
3083   // Only in C++ or ObjC++.
3084   if (!getLangOpts().CPlusPlus)
3085     return false;
3086 
3087   // Turn off ADL when we find certain kinds of declarations during
3088   // normal lookup:
3089   for (NamedDecl *D : R) {
3090     // C++0x [basic.lookup.argdep]p3:
3091     //     -- a declaration of a class member
3092     // Since using decls preserve this property, we check this on the
3093     // original decl.
3094     if (D->isCXXClassMember())
3095       return false;
3096 
3097     // C++0x [basic.lookup.argdep]p3:
3098     //     -- a block-scope function declaration that is not a
3099     //        using-declaration
3100     // NOTE: we also trigger this for function templates (in fact, we
3101     // don't check the decl type at all, since all other decl types
3102     // turn off ADL anyway).
3103     if (isa<UsingShadowDecl>(D))
3104       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3105     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3106       return false;
3107 
3108     // C++0x [basic.lookup.argdep]p3:
3109     //     -- a declaration that is neither a function or a function
3110     //        template
3111     // And also for builtin functions.
3112     if (isa<FunctionDecl>(D)) {
3113       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3114 
3115       // But also builtin functions.
3116       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3117         return false;
3118     } else if (!isa<FunctionTemplateDecl>(D))
3119       return false;
3120   }
3121 
3122   return true;
3123 }
3124 
3125 
3126 /// Diagnoses obvious problems with the use of the given declaration
3127 /// as an expression.  This is only actually called for lookups that
3128 /// were not overloaded, and it doesn't promise that the declaration
3129 /// will in fact be used.
3130 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3131   if (D->isInvalidDecl())
3132     return true;
3133 
3134   if (isa<TypedefNameDecl>(D)) {
3135     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3136     return true;
3137   }
3138 
3139   if (isa<ObjCInterfaceDecl>(D)) {
3140     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3141     return true;
3142   }
3143 
3144   if (isa<NamespaceDecl>(D)) {
3145     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3146     return true;
3147   }
3148 
3149   return false;
3150 }
3151 
3152 // Certain multiversion types should be treated as overloaded even when there is
3153 // only one result.
3154 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3155   assert(R.isSingleResult() && "Expected only a single result");
3156   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3157   return FD &&
3158          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3159 }
3160 
3161 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3162                                           LookupResult &R, bool NeedsADL,
3163                                           bool AcceptInvalidDecl) {
3164   // If this is a single, fully-resolved result and we don't need ADL,
3165   // just build an ordinary singleton decl ref.
3166   if (!NeedsADL && R.isSingleResult() &&
3167       !R.getAsSingle<FunctionTemplateDecl>() &&
3168       !ShouldLookupResultBeMultiVersionOverload(R))
3169     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3170                                     R.getRepresentativeDecl(), nullptr,
3171                                     AcceptInvalidDecl);
3172 
3173   // We only need to check the declaration if there's exactly one
3174   // result, because in the overloaded case the results can only be
3175   // functions and function templates.
3176   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3177       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3178     return ExprError();
3179 
3180   // Otherwise, just build an unresolved lookup expression.  Suppress
3181   // any lookup-related diagnostics; we'll hash these out later, when
3182   // we've picked a target.
3183   R.suppressDiagnostics();
3184 
3185   UnresolvedLookupExpr *ULE
3186     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3187                                    SS.getWithLocInContext(Context),
3188                                    R.getLookupNameInfo(),
3189                                    NeedsADL, R.isOverloadedResult(),
3190                                    R.begin(), R.end());
3191 
3192   return ULE;
3193 }
3194 
3195 static void
3196 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3197                                    ValueDecl *var, DeclContext *DC);
3198 
3199 /// Complete semantic analysis for a reference to the given declaration.
3200 ExprResult Sema::BuildDeclarationNameExpr(
3201     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3202     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3203     bool AcceptInvalidDecl) {
3204   assert(D && "Cannot refer to a NULL declaration");
3205   assert(!isa<FunctionTemplateDecl>(D) &&
3206          "Cannot refer unambiguously to a function template");
3207 
3208   SourceLocation Loc = NameInfo.getLoc();
3209   if (CheckDeclInExpr(*this, Loc, D))
3210     return ExprError();
3211 
3212   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3213     // Specifically diagnose references to class templates that are missing
3214     // a template argument list.
3215     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3216     return ExprError();
3217   }
3218 
3219   // Make sure that we're referring to a value.
3220   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3221     Diag(Loc, diag::err_ref_non_value)
3222       << D << SS.getRange();
3223     Diag(D->getLocation(), diag::note_declared_at);
3224     return ExprError();
3225   }
3226 
3227   // Check whether this declaration can be used. Note that we suppress
3228   // this check when we're going to perform argument-dependent lookup
3229   // on this function name, because this might not be the function
3230   // that overload resolution actually selects.
3231   if (DiagnoseUseOfDecl(D, Loc))
3232     return ExprError();
3233 
3234   auto *VD = cast<ValueDecl>(D);
3235 
3236   // Only create DeclRefExpr's for valid Decl's.
3237   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3238     return ExprError();
3239 
3240   // Handle members of anonymous structs and unions.  If we got here,
3241   // and the reference is to a class member indirect field, then this
3242   // must be the subject of a pointer-to-member expression.
3243   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3244     if (!indirectField->isCXXClassMember())
3245       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3246                                                       indirectField);
3247 
3248   {
3249     QualType type = VD->getType();
3250     if (type.isNull())
3251       return ExprError();
3252     ExprValueKind valueKind = VK_RValue;
3253 
3254     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3255     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3256     // is expanded by some outer '...' in the context of the use.
3257     type = type.getNonPackExpansionType();
3258 
3259     switch (D->getKind()) {
3260     // Ignore all the non-ValueDecl kinds.
3261 #define ABSTRACT_DECL(kind)
3262 #define VALUE(type, base)
3263 #define DECL(type, base) \
3264     case Decl::type:
3265 #include "clang/AST/DeclNodes.inc"
3266       llvm_unreachable("invalid value decl kind");
3267 
3268     // These shouldn't make it here.
3269     case Decl::ObjCAtDefsField:
3270       llvm_unreachable("forming non-member reference to ivar?");
3271 
3272     // Enum constants are always r-values and never references.
3273     // Unresolved using declarations are dependent.
3274     case Decl::EnumConstant:
3275     case Decl::UnresolvedUsingValue:
3276     case Decl::OMPDeclareReduction:
3277     case Decl::OMPDeclareMapper:
3278       valueKind = VK_RValue;
3279       break;
3280 
3281     // Fields and indirect fields that got here must be for
3282     // pointer-to-member expressions; we just call them l-values for
3283     // internal consistency, because this subexpression doesn't really
3284     // exist in the high-level semantics.
3285     case Decl::Field:
3286     case Decl::IndirectField:
3287     case Decl::ObjCIvar:
3288       assert(getLangOpts().CPlusPlus &&
3289              "building reference to field in C?");
3290 
3291       // These can't have reference type in well-formed programs, but
3292       // for internal consistency we do this anyway.
3293       type = type.getNonReferenceType();
3294       valueKind = VK_LValue;
3295       break;
3296 
3297     // Non-type template parameters are either l-values or r-values
3298     // depending on the type.
3299     case Decl::NonTypeTemplateParm: {
3300       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3301         type = reftype->getPointeeType();
3302         valueKind = VK_LValue; // even if the parameter is an r-value reference
3303         break;
3304       }
3305 
3306       // [expr.prim.id.unqual]p2:
3307       //   If the entity is a template parameter object for a template
3308       //   parameter of type T, the type of the expression is const T.
3309       //   [...] The expression is an lvalue if the entity is a [...] template
3310       //   parameter object.
3311       if (type->isRecordType()) {
3312         type = type.getUnqualifiedType().withConst();
3313         valueKind = VK_LValue;
3314         break;
3315       }
3316 
3317       // For non-references, we need to strip qualifiers just in case
3318       // the template parameter was declared as 'const int' or whatever.
3319       valueKind = VK_RValue;
3320       type = type.getUnqualifiedType();
3321       break;
3322     }
3323 
3324     case Decl::Var:
3325     case Decl::VarTemplateSpecialization:
3326     case Decl::VarTemplatePartialSpecialization:
3327     case Decl::Decomposition:
3328     case Decl::OMPCapturedExpr:
3329       // In C, "extern void blah;" is valid and is an r-value.
3330       if (!getLangOpts().CPlusPlus &&
3331           !type.hasQualifiers() &&
3332           type->isVoidType()) {
3333         valueKind = VK_RValue;
3334         break;
3335       }
3336       LLVM_FALLTHROUGH;
3337 
3338     case Decl::ImplicitParam:
3339     case Decl::ParmVar: {
3340       // These are always l-values.
3341       valueKind = VK_LValue;
3342       type = type.getNonReferenceType();
3343 
3344       // FIXME: Does the addition of const really only apply in
3345       // potentially-evaluated contexts? Since the variable isn't actually
3346       // captured in an unevaluated context, it seems that the answer is no.
3347       if (!isUnevaluatedContext()) {
3348         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3349         if (!CapturedType.isNull())
3350           type = CapturedType;
3351       }
3352 
3353       break;
3354     }
3355 
3356     case Decl::Binding: {
3357       // These are always lvalues.
3358       valueKind = VK_LValue;
3359       type = type.getNonReferenceType();
3360       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3361       // decides how that's supposed to work.
3362       auto *BD = cast<BindingDecl>(VD);
3363       if (BD->getDeclContext() != CurContext) {
3364         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3365         if (DD && DD->hasLocalStorage())
3366           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3367       }
3368       break;
3369     }
3370 
3371     case Decl::Function: {
3372       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3373         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3374           type = Context.BuiltinFnTy;
3375           valueKind = VK_RValue;
3376           break;
3377         }
3378       }
3379 
3380       const FunctionType *fty = type->castAs<FunctionType>();
3381 
3382       // If we're referring to a function with an __unknown_anytype
3383       // result type, make the entire expression __unknown_anytype.
3384       if (fty->getReturnType() == Context.UnknownAnyTy) {
3385         type = Context.UnknownAnyTy;
3386         valueKind = VK_RValue;
3387         break;
3388       }
3389 
3390       // Functions are l-values in C++.
3391       if (getLangOpts().CPlusPlus) {
3392         valueKind = VK_LValue;
3393         break;
3394       }
3395 
3396       // C99 DR 316 says that, if a function type comes from a
3397       // function definition (without a prototype), that type is only
3398       // used for checking compatibility. Therefore, when referencing
3399       // the function, we pretend that we don't have the full function
3400       // type.
3401       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3402           isa<FunctionProtoType>(fty))
3403         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3404                                               fty->getExtInfo());
3405 
3406       // Functions are r-values in C.
3407       valueKind = VK_RValue;
3408       break;
3409     }
3410 
3411     case Decl::CXXDeductionGuide:
3412       llvm_unreachable("building reference to deduction guide");
3413 
3414     case Decl::MSProperty:
3415     case Decl::MSGuid:
3416     case Decl::TemplateParamObject:
3417       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3418       // capture in OpenMP, or duplicated between host and device?
3419       valueKind = VK_LValue;
3420       break;
3421 
3422     case Decl::CXXMethod:
3423       // If we're referring to a method with an __unknown_anytype
3424       // result type, make the entire expression __unknown_anytype.
3425       // This should only be possible with a type written directly.
3426       if (const FunctionProtoType *proto
3427             = dyn_cast<FunctionProtoType>(VD->getType()))
3428         if (proto->getReturnType() == Context.UnknownAnyTy) {
3429           type = Context.UnknownAnyTy;
3430           valueKind = VK_RValue;
3431           break;
3432         }
3433 
3434       // C++ methods are l-values if static, r-values if non-static.
3435       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3436         valueKind = VK_LValue;
3437         break;
3438       }
3439       LLVM_FALLTHROUGH;
3440 
3441     case Decl::CXXConversion:
3442     case Decl::CXXDestructor:
3443     case Decl::CXXConstructor:
3444       valueKind = VK_RValue;
3445       break;
3446     }
3447 
3448     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3449                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3450                             TemplateArgs);
3451   }
3452 }
3453 
3454 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3455                                     SmallString<32> &Target) {
3456   Target.resize(CharByteWidth * (Source.size() + 1));
3457   char *ResultPtr = &Target[0];
3458   const llvm::UTF8 *ErrorPtr;
3459   bool success =
3460       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3461   (void)success;
3462   assert(success);
3463   Target.resize(ResultPtr - &Target[0]);
3464 }
3465 
3466 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3467                                      PredefinedExpr::IdentKind IK) {
3468   // Pick the current block, lambda, captured statement or function.
3469   Decl *currentDecl = nullptr;
3470   if (const BlockScopeInfo *BSI = getCurBlock())
3471     currentDecl = BSI->TheDecl;
3472   else if (const LambdaScopeInfo *LSI = getCurLambda())
3473     currentDecl = LSI->CallOperator;
3474   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3475     currentDecl = CSI->TheCapturedDecl;
3476   else
3477     currentDecl = getCurFunctionOrMethodDecl();
3478 
3479   if (!currentDecl) {
3480     Diag(Loc, diag::ext_predef_outside_function);
3481     currentDecl = Context.getTranslationUnitDecl();
3482   }
3483 
3484   QualType ResTy;
3485   StringLiteral *SL = nullptr;
3486   if (cast<DeclContext>(currentDecl)->isDependentContext())
3487     ResTy = Context.DependentTy;
3488   else {
3489     // Pre-defined identifiers are of type char[x], where x is the length of
3490     // the string.
3491     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3492     unsigned Length = Str.length();
3493 
3494     llvm::APInt LengthI(32, Length + 1);
3495     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3496       ResTy =
3497           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3498       SmallString<32> RawChars;
3499       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3500                               Str, RawChars);
3501       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3502                                            ArrayType::Normal,
3503                                            /*IndexTypeQuals*/ 0);
3504       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3505                                  /*Pascal*/ false, ResTy, Loc);
3506     } else {
3507       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3508       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3509                                            ArrayType::Normal,
3510                                            /*IndexTypeQuals*/ 0);
3511       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3512                                  /*Pascal*/ false, ResTy, Loc);
3513     }
3514   }
3515 
3516   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3517 }
3518 
3519 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3520                                                SourceLocation LParen,
3521                                                SourceLocation RParen,
3522                                                TypeSourceInfo *TSI) {
3523   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3524 }
3525 
3526 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3527                                                SourceLocation LParen,
3528                                                SourceLocation RParen,
3529                                                ParsedType ParsedTy) {
3530   TypeSourceInfo *TSI = nullptr;
3531   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3532 
3533   if (Ty.isNull())
3534     return ExprError();
3535   if (!TSI)
3536     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3537 
3538   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3539 }
3540 
3541 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3542   PredefinedExpr::IdentKind IK;
3543 
3544   switch (Kind) {
3545   default: llvm_unreachable("Unknown simple primary expr!");
3546   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3547   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3548   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3549   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3550   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3551   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3552   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3553   }
3554 
3555   return BuildPredefinedExpr(Loc, IK);
3556 }
3557 
3558 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3559   SmallString<16> CharBuffer;
3560   bool Invalid = false;
3561   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3562   if (Invalid)
3563     return ExprError();
3564 
3565   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3566                             PP, Tok.getKind());
3567   if (Literal.hadError())
3568     return ExprError();
3569 
3570   QualType Ty;
3571   if (Literal.isWide())
3572     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3573   else if (Literal.isUTF8() && getLangOpts().Char8)
3574     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3575   else if (Literal.isUTF16())
3576     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3577   else if (Literal.isUTF32())
3578     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3579   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3580     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3581   else
3582     Ty = Context.CharTy;  // 'x' -> char in C++
3583 
3584   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3585   if (Literal.isWide())
3586     Kind = CharacterLiteral::Wide;
3587   else if (Literal.isUTF16())
3588     Kind = CharacterLiteral::UTF16;
3589   else if (Literal.isUTF32())
3590     Kind = CharacterLiteral::UTF32;
3591   else if (Literal.isUTF8())
3592     Kind = CharacterLiteral::UTF8;
3593 
3594   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3595                                              Tok.getLocation());
3596 
3597   if (Literal.getUDSuffix().empty())
3598     return Lit;
3599 
3600   // We're building a user-defined literal.
3601   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3602   SourceLocation UDSuffixLoc =
3603     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3604 
3605   // Make sure we're allowed user-defined literals here.
3606   if (!UDLScope)
3607     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3608 
3609   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3610   //   operator "" X (ch)
3611   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3612                                         Lit, Tok.getLocation());
3613 }
3614 
3615 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3616   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3617   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3618                                 Context.IntTy, Loc);
3619 }
3620 
3621 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3622                                   QualType Ty, SourceLocation Loc) {
3623   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3624 
3625   using llvm::APFloat;
3626   APFloat Val(Format);
3627 
3628   APFloat::opStatus result = Literal.GetFloatValue(Val);
3629 
3630   // Overflow is always an error, but underflow is only an error if
3631   // we underflowed to zero (APFloat reports denormals as underflow).
3632   if ((result & APFloat::opOverflow) ||
3633       ((result & APFloat::opUnderflow) && Val.isZero())) {
3634     unsigned diagnostic;
3635     SmallString<20> buffer;
3636     if (result & APFloat::opOverflow) {
3637       diagnostic = diag::warn_float_overflow;
3638       APFloat::getLargest(Format).toString(buffer);
3639     } else {
3640       diagnostic = diag::warn_float_underflow;
3641       APFloat::getSmallest(Format).toString(buffer);
3642     }
3643 
3644     S.Diag(Loc, diagnostic)
3645       << Ty
3646       << StringRef(buffer.data(), buffer.size());
3647   }
3648 
3649   bool isExact = (result == APFloat::opOK);
3650   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3651 }
3652 
3653 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3654   assert(E && "Invalid expression");
3655 
3656   if (E->isValueDependent())
3657     return false;
3658 
3659   QualType QT = E->getType();
3660   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3661     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3662     return true;
3663   }
3664 
3665   llvm::APSInt ValueAPS;
3666   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3667 
3668   if (R.isInvalid())
3669     return true;
3670 
3671   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3672   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3673     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3674         << ValueAPS.toString(10) << ValueIsPositive;
3675     return true;
3676   }
3677 
3678   return false;
3679 }
3680 
3681 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3682   // Fast path for a single digit (which is quite common).  A single digit
3683   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3684   if (Tok.getLength() == 1) {
3685     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3686     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3687   }
3688 
3689   SmallString<128> SpellingBuffer;
3690   // NumericLiteralParser wants to overread by one character.  Add padding to
3691   // the buffer in case the token is copied to the buffer.  If getSpelling()
3692   // returns a StringRef to the memory buffer, it should have a null char at
3693   // the EOF, so it is also safe.
3694   SpellingBuffer.resize(Tok.getLength() + 1);
3695 
3696   // Get the spelling of the token, which eliminates trigraphs, etc.
3697   bool Invalid = false;
3698   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3699   if (Invalid)
3700     return ExprError();
3701 
3702   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3703                                PP.getSourceManager(), PP.getLangOpts(),
3704                                PP.getTargetInfo(), PP.getDiagnostics());
3705   if (Literal.hadError)
3706     return ExprError();
3707 
3708   if (Literal.hasUDSuffix()) {
3709     // We're building a user-defined literal.
3710     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3711     SourceLocation UDSuffixLoc =
3712       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3713 
3714     // Make sure we're allowed user-defined literals here.
3715     if (!UDLScope)
3716       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3717 
3718     QualType CookedTy;
3719     if (Literal.isFloatingLiteral()) {
3720       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3721       // long double, the literal is treated as a call of the form
3722       //   operator "" X (f L)
3723       CookedTy = Context.LongDoubleTy;
3724     } else {
3725       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3726       // unsigned long long, the literal is treated as a call of the form
3727       //   operator "" X (n ULL)
3728       CookedTy = Context.UnsignedLongLongTy;
3729     }
3730 
3731     DeclarationName OpName =
3732       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3733     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3734     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3735 
3736     SourceLocation TokLoc = Tok.getLocation();
3737 
3738     // Perform literal operator lookup to determine if we're building a raw
3739     // literal or a cooked one.
3740     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3741     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3742                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3743                                   /*AllowStringTemplatePack*/ false,
3744                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3745     case LOLR_ErrorNoDiagnostic:
3746       // Lookup failure for imaginary constants isn't fatal, there's still the
3747       // GNU extension producing _Complex types.
3748       break;
3749     case LOLR_Error:
3750       return ExprError();
3751     case LOLR_Cooked: {
3752       Expr *Lit;
3753       if (Literal.isFloatingLiteral()) {
3754         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3755       } else {
3756         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3757         if (Literal.GetIntegerValue(ResultVal))
3758           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3759               << /* Unsigned */ 1;
3760         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3761                                      Tok.getLocation());
3762       }
3763       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3764     }
3765 
3766     case LOLR_Raw: {
3767       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3768       // literal is treated as a call of the form
3769       //   operator "" X ("n")
3770       unsigned Length = Literal.getUDSuffixOffset();
3771       QualType StrTy = Context.getConstantArrayType(
3772           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3773           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3774       Expr *Lit = StringLiteral::Create(
3775           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3776           /*Pascal*/false, StrTy, &TokLoc, 1);
3777       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3778     }
3779 
3780     case LOLR_Template: {
3781       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3782       // template), L is treated as a call fo the form
3783       //   operator "" X <'c1', 'c2', ... 'ck'>()
3784       // where n is the source character sequence c1 c2 ... ck.
3785       TemplateArgumentListInfo ExplicitArgs;
3786       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3787       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3788       llvm::APSInt Value(CharBits, CharIsUnsigned);
3789       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3790         Value = TokSpelling[I];
3791         TemplateArgument Arg(Context, Value, Context.CharTy);
3792         TemplateArgumentLocInfo ArgInfo;
3793         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3794       }
3795       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3796                                       &ExplicitArgs);
3797     }
3798     case LOLR_StringTemplatePack:
3799       llvm_unreachable("unexpected literal operator lookup result");
3800     }
3801   }
3802 
3803   Expr *Res;
3804 
3805   if (Literal.isFixedPointLiteral()) {
3806     QualType Ty;
3807 
3808     if (Literal.isAccum) {
3809       if (Literal.isHalf) {
3810         Ty = Context.ShortAccumTy;
3811       } else if (Literal.isLong) {
3812         Ty = Context.LongAccumTy;
3813       } else {
3814         Ty = Context.AccumTy;
3815       }
3816     } else if (Literal.isFract) {
3817       if (Literal.isHalf) {
3818         Ty = Context.ShortFractTy;
3819       } else if (Literal.isLong) {
3820         Ty = Context.LongFractTy;
3821       } else {
3822         Ty = Context.FractTy;
3823       }
3824     }
3825 
3826     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3827 
3828     bool isSigned = !Literal.isUnsigned;
3829     unsigned scale = Context.getFixedPointScale(Ty);
3830     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3831 
3832     llvm::APInt Val(bit_width, 0, isSigned);
3833     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3834     bool ValIsZero = Val.isNullValue() && !Overflowed;
3835 
3836     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3837     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3838       // Clause 6.4.4 - The value of a constant shall be in the range of
3839       // representable values for its type, with exception for constants of a
3840       // fract type with a value of exactly 1; such a constant shall denote
3841       // the maximal value for the type.
3842       --Val;
3843     else if (Val.ugt(MaxVal) || Overflowed)
3844       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3845 
3846     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3847                                               Tok.getLocation(), scale);
3848   } else if (Literal.isFloatingLiteral()) {
3849     QualType Ty;
3850     if (Literal.isHalf){
3851       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3852         Ty = Context.HalfTy;
3853       else {
3854         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3855         return ExprError();
3856       }
3857     } else if (Literal.isFloat)
3858       Ty = Context.FloatTy;
3859     else if (Literal.isLong)
3860       Ty = Context.LongDoubleTy;
3861     else if (Literal.isFloat16)
3862       Ty = Context.Float16Ty;
3863     else if (Literal.isFloat128)
3864       Ty = Context.Float128Ty;
3865     else
3866       Ty = Context.DoubleTy;
3867 
3868     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3869 
3870     if (Ty == Context.DoubleTy) {
3871       if (getLangOpts().SinglePrecisionConstants) {
3872         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3873           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3874         }
3875       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3876                                              "cl_khr_fp64", getLangOpts())) {
3877         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3878         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3879             << (getLangOpts().OpenCLVersion >= 300);
3880         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3881       }
3882     }
3883   } else if (!Literal.isIntegerLiteral()) {
3884     return ExprError();
3885   } else {
3886     QualType Ty;
3887 
3888     // 'long long' is a C99 or C++11 feature.
3889     if (!getLangOpts().C99 && Literal.isLongLong) {
3890       if (getLangOpts().CPlusPlus)
3891         Diag(Tok.getLocation(),
3892              getLangOpts().CPlusPlus11 ?
3893              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3894       else
3895         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3896     }
3897 
3898     // 'z/uz' literals are a C++2b feature.
3899     if (Literal.isSizeT)
3900       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3901                                   ? getLangOpts().CPlusPlus2b
3902                                         ? diag::warn_cxx20_compat_size_t_suffix
3903                                         : diag::ext_cxx2b_size_t_suffix
3904                                   : diag::err_cxx2b_size_t_suffix);
3905 
3906     // Get the value in the widest-possible width.
3907     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3908     llvm::APInt ResultVal(MaxWidth, 0);
3909 
3910     if (Literal.GetIntegerValue(ResultVal)) {
3911       // If this value didn't fit into uintmax_t, error and force to ull.
3912       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3913           << /* Unsigned */ 1;
3914       Ty = Context.UnsignedLongLongTy;
3915       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3916              "long long is not intmax_t?");
3917     } else {
3918       // If this value fits into a ULL, try to figure out what else it fits into
3919       // according to the rules of C99 6.4.4.1p5.
3920 
3921       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3922       // be an unsigned int.
3923       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3924 
3925       // Check from smallest to largest, picking the smallest type we can.
3926       unsigned Width = 0;
3927 
3928       // Microsoft specific integer suffixes are explicitly sized.
3929       if (Literal.MicrosoftInteger) {
3930         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3931           Width = 8;
3932           Ty = Context.CharTy;
3933         } else {
3934           Width = Literal.MicrosoftInteger;
3935           Ty = Context.getIntTypeForBitwidth(Width,
3936                                              /*Signed=*/!Literal.isUnsigned);
3937         }
3938       }
3939 
3940       // Check C++2b size_t literals.
3941       if (Literal.isSizeT) {
3942         assert(!Literal.MicrosoftInteger &&
3943                "size_t literals can't be Microsoft literals");
3944         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3945             Context.getTargetInfo().getSizeType());
3946 
3947         // Does it fit in size_t?
3948         if (ResultVal.isIntN(SizeTSize)) {
3949           // Does it fit in ssize_t?
3950           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3951             Ty = Context.getSignedSizeType();
3952           else if (AllowUnsigned)
3953             Ty = Context.getSizeType();
3954           Width = SizeTSize;
3955         }
3956       }
3957 
3958       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3959           !Literal.isSizeT) {
3960         // Are int/unsigned possibilities?
3961         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3962 
3963         // Does it fit in a unsigned int?
3964         if (ResultVal.isIntN(IntSize)) {
3965           // Does it fit in a signed int?
3966           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3967             Ty = Context.IntTy;
3968           else if (AllowUnsigned)
3969             Ty = Context.UnsignedIntTy;
3970           Width = IntSize;
3971         }
3972       }
3973 
3974       // Are long/unsigned long possibilities?
3975       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3976         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3977 
3978         // Does it fit in a unsigned long?
3979         if (ResultVal.isIntN(LongSize)) {
3980           // Does it fit in a signed long?
3981           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3982             Ty = Context.LongTy;
3983           else if (AllowUnsigned)
3984             Ty = Context.UnsignedLongTy;
3985           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3986           // is compatible.
3987           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3988             const unsigned LongLongSize =
3989                 Context.getTargetInfo().getLongLongWidth();
3990             Diag(Tok.getLocation(),
3991                  getLangOpts().CPlusPlus
3992                      ? Literal.isLong
3993                            ? diag::warn_old_implicitly_unsigned_long_cxx
3994                            : /*C++98 UB*/ diag::
3995                                  ext_old_implicitly_unsigned_long_cxx
3996                      : diag::warn_old_implicitly_unsigned_long)
3997                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3998                                             : /*will be ill-formed*/ 1);
3999             Ty = Context.UnsignedLongTy;
4000           }
4001           Width = LongSize;
4002         }
4003       }
4004 
4005       // Check long long if needed.
4006       if (Ty.isNull() && !Literal.isSizeT) {
4007         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4008 
4009         // Does it fit in a unsigned long long?
4010         if (ResultVal.isIntN(LongLongSize)) {
4011           // Does it fit in a signed long long?
4012           // To be compatible with MSVC, hex integer literals ending with the
4013           // LL or i64 suffix are always signed in Microsoft mode.
4014           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4015               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4016             Ty = Context.LongLongTy;
4017           else if (AllowUnsigned)
4018             Ty = Context.UnsignedLongLongTy;
4019           Width = LongLongSize;
4020         }
4021       }
4022 
4023       // If we still couldn't decide a type, we either have 'size_t' literal
4024       // that is out of range, or a decimal literal that does not fit in a
4025       // signed long long and has no U suffix.
4026       if (Ty.isNull()) {
4027         if (Literal.isSizeT)
4028           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4029               << Literal.isUnsigned;
4030         else
4031           Diag(Tok.getLocation(),
4032                diag::ext_integer_literal_too_large_for_signed);
4033         Ty = Context.UnsignedLongLongTy;
4034         Width = Context.getTargetInfo().getLongLongWidth();
4035       }
4036 
4037       if (ResultVal.getBitWidth() != Width)
4038         ResultVal = ResultVal.trunc(Width);
4039     }
4040     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4041   }
4042 
4043   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4044   if (Literal.isImaginary) {
4045     Res = new (Context) ImaginaryLiteral(Res,
4046                                         Context.getComplexType(Res->getType()));
4047 
4048     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4049   }
4050   return Res;
4051 }
4052 
4053 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4054   assert(E && "ActOnParenExpr() missing expr");
4055   return new (Context) ParenExpr(L, R, E);
4056 }
4057 
4058 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4059                                          SourceLocation Loc,
4060                                          SourceRange ArgRange) {
4061   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4062   // scalar or vector data type argument..."
4063   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4064   // type (C99 6.2.5p18) or void.
4065   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4066     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4067       << T << ArgRange;
4068     return true;
4069   }
4070 
4071   assert((T->isVoidType() || !T->isIncompleteType()) &&
4072          "Scalar types should always be complete");
4073   return false;
4074 }
4075 
4076 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4077                                            SourceLocation Loc,
4078                                            SourceRange ArgRange,
4079                                            UnaryExprOrTypeTrait TraitKind) {
4080   // Invalid types must be hard errors for SFINAE in C++.
4081   if (S.LangOpts.CPlusPlus)
4082     return true;
4083 
4084   // C99 6.5.3.4p1:
4085   if (T->isFunctionType() &&
4086       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4087        TraitKind == UETT_PreferredAlignOf)) {
4088     // sizeof(function)/alignof(function) is allowed as an extension.
4089     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4090         << getTraitSpelling(TraitKind) << ArgRange;
4091     return false;
4092   }
4093 
4094   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4095   // this is an error (OpenCL v1.1 s6.3.k)
4096   if (T->isVoidType()) {
4097     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4098                                         : diag::ext_sizeof_alignof_void_type;
4099     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4100     return false;
4101   }
4102 
4103   return true;
4104 }
4105 
4106 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4107                                              SourceLocation Loc,
4108                                              SourceRange ArgRange,
4109                                              UnaryExprOrTypeTrait TraitKind) {
4110   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4111   // runtime doesn't allow it.
4112   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4113     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4114       << T << (TraitKind == UETT_SizeOf)
4115       << ArgRange;
4116     return true;
4117   }
4118 
4119   return false;
4120 }
4121 
4122 /// Check whether E is a pointer from a decayed array type (the decayed
4123 /// pointer type is equal to T) and emit a warning if it is.
4124 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4125                                      Expr *E) {
4126   // Don't warn if the operation changed the type.
4127   if (T != E->getType())
4128     return;
4129 
4130   // Now look for array decays.
4131   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4132   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4133     return;
4134 
4135   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4136                                              << ICE->getType()
4137                                              << ICE->getSubExpr()->getType();
4138 }
4139 
4140 /// Check the constraints on expression operands to unary type expression
4141 /// and type traits.
4142 ///
4143 /// Completes any types necessary and validates the constraints on the operand
4144 /// expression. The logic mostly mirrors the type-based overload, but may modify
4145 /// the expression as it completes the type for that expression through template
4146 /// instantiation, etc.
4147 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4148                                             UnaryExprOrTypeTrait ExprKind) {
4149   QualType ExprTy = E->getType();
4150   assert(!ExprTy->isReferenceType());
4151 
4152   bool IsUnevaluatedOperand =
4153       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4154        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4155   if (IsUnevaluatedOperand) {
4156     ExprResult Result = CheckUnevaluatedOperand(E);
4157     if (Result.isInvalid())
4158       return true;
4159     E = Result.get();
4160   }
4161 
4162   // The operand for sizeof and alignof is in an unevaluated expression context,
4163   // so side effects could result in unintended consequences.
4164   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4165   // used to build SFINAE gadgets.
4166   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4167   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4168       !E->isInstantiationDependent() &&
4169       E->HasSideEffects(Context, false))
4170     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4171 
4172   if (ExprKind == UETT_VecStep)
4173     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4174                                         E->getSourceRange());
4175 
4176   // Explicitly list some types as extensions.
4177   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4178                                       E->getSourceRange(), ExprKind))
4179     return false;
4180 
4181   // 'alignof' applied to an expression only requires the base element type of
4182   // the expression to be complete. 'sizeof' requires the expression's type to
4183   // be complete (and will attempt to complete it if it's an array of unknown
4184   // bound).
4185   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4186     if (RequireCompleteSizedType(
4187             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4188             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4189             getTraitSpelling(ExprKind), E->getSourceRange()))
4190       return true;
4191   } else {
4192     if (RequireCompleteSizedExprType(
4193             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4194             getTraitSpelling(ExprKind), E->getSourceRange()))
4195       return true;
4196   }
4197 
4198   // Completing the expression's type may have changed it.
4199   ExprTy = E->getType();
4200   assert(!ExprTy->isReferenceType());
4201 
4202   if (ExprTy->isFunctionType()) {
4203     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4204         << getTraitSpelling(ExprKind) << E->getSourceRange();
4205     return true;
4206   }
4207 
4208   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4209                                        E->getSourceRange(), ExprKind))
4210     return true;
4211 
4212   if (ExprKind == UETT_SizeOf) {
4213     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4214       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4215         QualType OType = PVD->getOriginalType();
4216         QualType Type = PVD->getType();
4217         if (Type->isPointerType() && OType->isArrayType()) {
4218           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4219             << Type << OType;
4220           Diag(PVD->getLocation(), diag::note_declared_at);
4221         }
4222       }
4223     }
4224 
4225     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4226     // decays into a pointer and returns an unintended result. This is most
4227     // likely a typo for "sizeof(array) op x".
4228     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4229       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4230                                BO->getLHS());
4231       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4232                                BO->getRHS());
4233     }
4234   }
4235 
4236   return false;
4237 }
4238 
4239 /// Check the constraints on operands to unary expression and type
4240 /// traits.
4241 ///
4242 /// This will complete any types necessary, and validate the various constraints
4243 /// on those operands.
4244 ///
4245 /// The UsualUnaryConversions() function is *not* called by this routine.
4246 /// C99 6.3.2.1p[2-4] all state:
4247 ///   Except when it is the operand of the sizeof operator ...
4248 ///
4249 /// C++ [expr.sizeof]p4
4250 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4251 ///   standard conversions are not applied to the operand of sizeof.
4252 ///
4253 /// This policy is followed for all of the unary trait expressions.
4254 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4255                                             SourceLocation OpLoc,
4256                                             SourceRange ExprRange,
4257                                             UnaryExprOrTypeTrait ExprKind) {
4258   if (ExprType->isDependentType())
4259     return false;
4260 
4261   // C++ [expr.sizeof]p2:
4262   //     When applied to a reference or a reference type, the result
4263   //     is the size of the referenced type.
4264   // C++11 [expr.alignof]p3:
4265   //     When alignof is applied to a reference type, the result
4266   //     shall be the alignment of the referenced type.
4267   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4268     ExprType = Ref->getPointeeType();
4269 
4270   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4271   //   When alignof or _Alignof is applied to an array type, the result
4272   //   is the alignment of the element type.
4273   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4274       ExprKind == UETT_OpenMPRequiredSimdAlign)
4275     ExprType = Context.getBaseElementType(ExprType);
4276 
4277   if (ExprKind == UETT_VecStep)
4278     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4279 
4280   // Explicitly list some types as extensions.
4281   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4282                                       ExprKind))
4283     return false;
4284 
4285   if (RequireCompleteSizedType(
4286           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4287           getTraitSpelling(ExprKind), ExprRange))
4288     return true;
4289 
4290   if (ExprType->isFunctionType()) {
4291     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4292         << getTraitSpelling(ExprKind) << ExprRange;
4293     return true;
4294   }
4295 
4296   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4297                                        ExprKind))
4298     return true;
4299 
4300   return false;
4301 }
4302 
4303 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4304   // Cannot know anything else if the expression is dependent.
4305   if (E->isTypeDependent())
4306     return false;
4307 
4308   if (E->getObjectKind() == OK_BitField) {
4309     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4310        << 1 << E->getSourceRange();
4311     return true;
4312   }
4313 
4314   ValueDecl *D = nullptr;
4315   Expr *Inner = E->IgnoreParens();
4316   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4317     D = DRE->getDecl();
4318   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4319     D = ME->getMemberDecl();
4320   }
4321 
4322   // If it's a field, require the containing struct to have a
4323   // complete definition so that we can compute the layout.
4324   //
4325   // This can happen in C++11 onwards, either by naming the member
4326   // in a way that is not transformed into a member access expression
4327   // (in an unevaluated operand, for instance), or by naming the member
4328   // in a trailing-return-type.
4329   //
4330   // For the record, since __alignof__ on expressions is a GCC
4331   // extension, GCC seems to permit this but always gives the
4332   // nonsensical answer 0.
4333   //
4334   // We don't really need the layout here --- we could instead just
4335   // directly check for all the appropriate alignment-lowing
4336   // attributes --- but that would require duplicating a lot of
4337   // logic that just isn't worth duplicating for such a marginal
4338   // use-case.
4339   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4340     // Fast path this check, since we at least know the record has a
4341     // definition if we can find a member of it.
4342     if (!FD->getParent()->isCompleteDefinition()) {
4343       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4344         << E->getSourceRange();
4345       return true;
4346     }
4347 
4348     // Otherwise, if it's a field, and the field doesn't have
4349     // reference type, then it must have a complete type (or be a
4350     // flexible array member, which we explicitly want to
4351     // white-list anyway), which makes the following checks trivial.
4352     if (!FD->getType()->isReferenceType())
4353       return false;
4354   }
4355 
4356   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4357 }
4358 
4359 bool Sema::CheckVecStepExpr(Expr *E) {
4360   E = E->IgnoreParens();
4361 
4362   // Cannot know anything else if the expression is dependent.
4363   if (E->isTypeDependent())
4364     return false;
4365 
4366   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4367 }
4368 
4369 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4370                                         CapturingScopeInfo *CSI) {
4371   assert(T->isVariablyModifiedType());
4372   assert(CSI != nullptr);
4373 
4374   // We're going to walk down into the type and look for VLA expressions.
4375   do {
4376     const Type *Ty = T.getTypePtr();
4377     switch (Ty->getTypeClass()) {
4378 #define TYPE(Class, Base)
4379 #define ABSTRACT_TYPE(Class, Base)
4380 #define NON_CANONICAL_TYPE(Class, Base)
4381 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4382 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4383 #include "clang/AST/TypeNodes.inc"
4384       T = QualType();
4385       break;
4386     // These types are never variably-modified.
4387     case Type::Builtin:
4388     case Type::Complex:
4389     case Type::Vector:
4390     case Type::ExtVector:
4391     case Type::ConstantMatrix:
4392     case Type::Record:
4393     case Type::Enum:
4394     case Type::Elaborated:
4395     case Type::TemplateSpecialization:
4396     case Type::ObjCObject:
4397     case Type::ObjCInterface:
4398     case Type::ObjCObjectPointer:
4399     case Type::ObjCTypeParam:
4400     case Type::Pipe:
4401     case Type::ExtInt:
4402       llvm_unreachable("type class is never variably-modified!");
4403     case Type::Adjusted:
4404       T = cast<AdjustedType>(Ty)->getOriginalType();
4405       break;
4406     case Type::Decayed:
4407       T = cast<DecayedType>(Ty)->getPointeeType();
4408       break;
4409     case Type::Pointer:
4410       T = cast<PointerType>(Ty)->getPointeeType();
4411       break;
4412     case Type::BlockPointer:
4413       T = cast<BlockPointerType>(Ty)->getPointeeType();
4414       break;
4415     case Type::LValueReference:
4416     case Type::RValueReference:
4417       T = cast<ReferenceType>(Ty)->getPointeeType();
4418       break;
4419     case Type::MemberPointer:
4420       T = cast<MemberPointerType>(Ty)->getPointeeType();
4421       break;
4422     case Type::ConstantArray:
4423     case Type::IncompleteArray:
4424       // Losing element qualification here is fine.
4425       T = cast<ArrayType>(Ty)->getElementType();
4426       break;
4427     case Type::VariableArray: {
4428       // Losing element qualification here is fine.
4429       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4430 
4431       // Unknown size indication requires no size computation.
4432       // Otherwise, evaluate and record it.
4433       auto Size = VAT->getSizeExpr();
4434       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4435           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4436         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4437 
4438       T = VAT->getElementType();
4439       break;
4440     }
4441     case Type::FunctionProto:
4442     case Type::FunctionNoProto:
4443       T = cast<FunctionType>(Ty)->getReturnType();
4444       break;
4445     case Type::Paren:
4446     case Type::TypeOf:
4447     case Type::UnaryTransform:
4448     case Type::Attributed:
4449     case Type::SubstTemplateTypeParm:
4450     case Type::MacroQualified:
4451       // Keep walking after single level desugaring.
4452       T = T.getSingleStepDesugaredType(Context);
4453       break;
4454     case Type::Typedef:
4455       T = cast<TypedefType>(Ty)->desugar();
4456       break;
4457     case Type::Decltype:
4458       T = cast<DecltypeType>(Ty)->desugar();
4459       break;
4460     case Type::Auto:
4461     case Type::DeducedTemplateSpecialization:
4462       T = cast<DeducedType>(Ty)->getDeducedType();
4463       break;
4464     case Type::TypeOfExpr:
4465       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4466       break;
4467     case Type::Atomic:
4468       T = cast<AtomicType>(Ty)->getValueType();
4469       break;
4470     }
4471   } while (!T.isNull() && T->isVariablyModifiedType());
4472 }
4473 
4474 /// Build a sizeof or alignof expression given a type operand.
4475 ExprResult
4476 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4477                                      SourceLocation OpLoc,
4478                                      UnaryExprOrTypeTrait ExprKind,
4479                                      SourceRange R) {
4480   if (!TInfo)
4481     return ExprError();
4482 
4483   QualType T = TInfo->getType();
4484 
4485   if (!T->isDependentType() &&
4486       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4487     return ExprError();
4488 
4489   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4490     if (auto *TT = T->getAs<TypedefType>()) {
4491       for (auto I = FunctionScopes.rbegin(),
4492                 E = std::prev(FunctionScopes.rend());
4493            I != E; ++I) {
4494         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4495         if (CSI == nullptr)
4496           break;
4497         DeclContext *DC = nullptr;
4498         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4499           DC = LSI->CallOperator;
4500         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4501           DC = CRSI->TheCapturedDecl;
4502         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4503           DC = BSI->TheDecl;
4504         if (DC) {
4505           if (DC->containsDecl(TT->getDecl()))
4506             break;
4507           captureVariablyModifiedType(Context, T, CSI);
4508         }
4509       }
4510     }
4511   }
4512 
4513   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4514   return new (Context) UnaryExprOrTypeTraitExpr(
4515       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4516 }
4517 
4518 /// Build a sizeof or alignof expression given an expression
4519 /// operand.
4520 ExprResult
4521 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4522                                      UnaryExprOrTypeTrait ExprKind) {
4523   ExprResult PE = CheckPlaceholderExpr(E);
4524   if (PE.isInvalid())
4525     return ExprError();
4526 
4527   E = PE.get();
4528 
4529   // Verify that the operand is valid.
4530   bool isInvalid = false;
4531   if (E->isTypeDependent()) {
4532     // Delay type-checking for type-dependent expressions.
4533   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4534     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4535   } else if (ExprKind == UETT_VecStep) {
4536     isInvalid = CheckVecStepExpr(E);
4537   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4538       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4539       isInvalid = true;
4540   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4541     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4542     isInvalid = true;
4543   } else {
4544     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4545   }
4546 
4547   if (isInvalid)
4548     return ExprError();
4549 
4550   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4551     PE = TransformToPotentiallyEvaluated(E);
4552     if (PE.isInvalid()) return ExprError();
4553     E = PE.get();
4554   }
4555 
4556   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4557   return new (Context) UnaryExprOrTypeTraitExpr(
4558       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4559 }
4560 
4561 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4562 /// expr and the same for @c alignof and @c __alignof
4563 /// Note that the ArgRange is invalid if isType is false.
4564 ExprResult
4565 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4566                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4567                                     void *TyOrEx, SourceRange ArgRange) {
4568   // If error parsing type, ignore.
4569   if (!TyOrEx) return ExprError();
4570 
4571   if (IsType) {
4572     TypeSourceInfo *TInfo;
4573     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4574     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4575   }
4576 
4577   Expr *ArgEx = (Expr *)TyOrEx;
4578   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4579   return Result;
4580 }
4581 
4582 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4583                                      bool IsReal) {
4584   if (V.get()->isTypeDependent())
4585     return S.Context.DependentTy;
4586 
4587   // _Real and _Imag are only l-values for normal l-values.
4588   if (V.get()->getObjectKind() != OK_Ordinary) {
4589     V = S.DefaultLvalueConversion(V.get());
4590     if (V.isInvalid())
4591       return QualType();
4592   }
4593 
4594   // These operators return the element type of a complex type.
4595   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4596     return CT->getElementType();
4597 
4598   // Otherwise they pass through real integer and floating point types here.
4599   if (V.get()->getType()->isArithmeticType())
4600     return V.get()->getType();
4601 
4602   // Test for placeholders.
4603   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4604   if (PR.isInvalid()) return QualType();
4605   if (PR.get() != V.get()) {
4606     V = PR;
4607     return CheckRealImagOperand(S, V, Loc, IsReal);
4608   }
4609 
4610   // Reject anything else.
4611   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4612     << (IsReal ? "__real" : "__imag");
4613   return QualType();
4614 }
4615 
4616 
4617 
4618 ExprResult
4619 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4620                           tok::TokenKind Kind, Expr *Input) {
4621   UnaryOperatorKind Opc;
4622   switch (Kind) {
4623   default: llvm_unreachable("Unknown unary op!");
4624   case tok::plusplus:   Opc = UO_PostInc; break;
4625   case tok::minusminus: Opc = UO_PostDec; break;
4626   }
4627 
4628   // Since this might is a postfix expression, get rid of ParenListExprs.
4629   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4630   if (Result.isInvalid()) return ExprError();
4631   Input = Result.get();
4632 
4633   return BuildUnaryOp(S, OpLoc, Opc, Input);
4634 }
4635 
4636 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4637 ///
4638 /// \return true on error
4639 static bool checkArithmeticOnObjCPointer(Sema &S,
4640                                          SourceLocation opLoc,
4641                                          Expr *op) {
4642   assert(op->getType()->isObjCObjectPointerType());
4643   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4644       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4645     return false;
4646 
4647   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4648     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4649     << op->getSourceRange();
4650   return true;
4651 }
4652 
4653 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4654   auto *BaseNoParens = Base->IgnoreParens();
4655   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4656     return MSProp->getPropertyDecl()->getType()->isArrayType();
4657   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4658 }
4659 
4660 ExprResult
4661 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4662                               Expr *idx, SourceLocation rbLoc) {
4663   if (base && !base->getType().isNull() &&
4664       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4665     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4666                                     SourceLocation(), /*Length*/ nullptr,
4667                                     /*Stride=*/nullptr, rbLoc);
4668 
4669   // Since this might be a postfix expression, get rid of ParenListExprs.
4670   if (isa<ParenListExpr>(base)) {
4671     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4672     if (result.isInvalid()) return ExprError();
4673     base = result.get();
4674   }
4675 
4676   // Check if base and idx form a MatrixSubscriptExpr.
4677   //
4678   // Helper to check for comma expressions, which are not allowed as indices for
4679   // matrix subscript expressions.
4680   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4681     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4682       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4683           << SourceRange(base->getBeginLoc(), rbLoc);
4684       return true;
4685     }
4686     return false;
4687   };
4688   // The matrix subscript operator ([][])is considered a single operator.
4689   // Separating the index expressions by parenthesis is not allowed.
4690   if (base->getType()->isSpecificPlaceholderType(
4691           BuiltinType::IncompleteMatrixIdx) &&
4692       !isa<MatrixSubscriptExpr>(base)) {
4693     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4694         << SourceRange(base->getBeginLoc(), rbLoc);
4695     return ExprError();
4696   }
4697   // If the base is a MatrixSubscriptExpr, try to create a new
4698   // MatrixSubscriptExpr.
4699   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4700   if (matSubscriptE) {
4701     if (CheckAndReportCommaError(idx))
4702       return ExprError();
4703 
4704     assert(matSubscriptE->isIncomplete() &&
4705            "base has to be an incomplete matrix subscript");
4706     return CreateBuiltinMatrixSubscriptExpr(
4707         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4708   }
4709 
4710   // Handle any non-overload placeholder types in the base and index
4711   // expressions.  We can't handle overloads here because the other
4712   // operand might be an overloadable type, in which case the overload
4713   // resolution for the operator overload should get the first crack
4714   // at the overload.
4715   bool IsMSPropertySubscript = false;
4716   if (base->getType()->isNonOverloadPlaceholderType()) {
4717     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4718     if (!IsMSPropertySubscript) {
4719       ExprResult result = CheckPlaceholderExpr(base);
4720       if (result.isInvalid())
4721         return ExprError();
4722       base = result.get();
4723     }
4724   }
4725 
4726   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4727   if (base->getType()->isMatrixType()) {
4728     if (CheckAndReportCommaError(idx))
4729       return ExprError();
4730 
4731     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4732   }
4733 
4734   // A comma-expression as the index is deprecated in C++2a onwards.
4735   if (getLangOpts().CPlusPlus20 &&
4736       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4737        (isa<CXXOperatorCallExpr>(idx) &&
4738         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4739     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4740         << SourceRange(base->getBeginLoc(), rbLoc);
4741   }
4742 
4743   if (idx->getType()->isNonOverloadPlaceholderType()) {
4744     ExprResult result = CheckPlaceholderExpr(idx);
4745     if (result.isInvalid()) return ExprError();
4746     idx = result.get();
4747   }
4748 
4749   // Build an unanalyzed expression if either operand is type-dependent.
4750   if (getLangOpts().CPlusPlus &&
4751       (base->isTypeDependent() || idx->isTypeDependent())) {
4752     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4753                                             VK_LValue, OK_Ordinary, rbLoc);
4754   }
4755 
4756   // MSDN, property (C++)
4757   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4758   // This attribute can also be used in the declaration of an empty array in a
4759   // class or structure definition. For example:
4760   // __declspec(property(get=GetX, put=PutX)) int x[];
4761   // The above statement indicates that x[] can be used with one or more array
4762   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4763   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4764   if (IsMSPropertySubscript) {
4765     // Build MS property subscript expression if base is MS property reference
4766     // or MS property subscript.
4767     return new (Context) MSPropertySubscriptExpr(
4768         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4769   }
4770 
4771   // Use C++ overloaded-operator rules if either operand has record
4772   // type.  The spec says to do this if either type is *overloadable*,
4773   // but enum types can't declare subscript operators or conversion
4774   // operators, so there's nothing interesting for overload resolution
4775   // to do if there aren't any record types involved.
4776   //
4777   // ObjC pointers have their own subscripting logic that is not tied
4778   // to overload resolution and so should not take this path.
4779   if (getLangOpts().CPlusPlus &&
4780       (base->getType()->isRecordType() ||
4781        (!base->getType()->isObjCObjectPointerType() &&
4782         idx->getType()->isRecordType()))) {
4783     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4784   }
4785 
4786   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4787 
4788   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4789     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4790 
4791   return Res;
4792 }
4793 
4794 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4795   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4796   InitializationKind Kind =
4797       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4798   InitializationSequence InitSeq(*this, Entity, Kind, E);
4799   return InitSeq.Perform(*this, Entity, Kind, E);
4800 }
4801 
4802 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4803                                                   Expr *ColumnIdx,
4804                                                   SourceLocation RBLoc) {
4805   ExprResult BaseR = CheckPlaceholderExpr(Base);
4806   if (BaseR.isInvalid())
4807     return BaseR;
4808   Base = BaseR.get();
4809 
4810   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4811   if (RowR.isInvalid())
4812     return RowR;
4813   RowIdx = RowR.get();
4814 
4815   if (!ColumnIdx)
4816     return new (Context) MatrixSubscriptExpr(
4817         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4818 
4819   // Build an unanalyzed expression if any of the operands is type-dependent.
4820   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4821       ColumnIdx->isTypeDependent())
4822     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4823                                              Context.DependentTy, RBLoc);
4824 
4825   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4826   if (ColumnR.isInvalid())
4827     return ColumnR;
4828   ColumnIdx = ColumnR.get();
4829 
4830   // Check that IndexExpr is an integer expression. If it is a constant
4831   // expression, check that it is less than Dim (= the number of elements in the
4832   // corresponding dimension).
4833   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4834                           bool IsColumnIdx) -> Expr * {
4835     if (!IndexExpr->getType()->isIntegerType() &&
4836         !IndexExpr->isTypeDependent()) {
4837       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4838           << IsColumnIdx;
4839       return nullptr;
4840     }
4841 
4842     if (Optional<llvm::APSInt> Idx =
4843             IndexExpr->getIntegerConstantExpr(Context)) {
4844       if ((*Idx < 0 || *Idx >= Dim)) {
4845         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4846             << IsColumnIdx << Dim;
4847         return nullptr;
4848       }
4849     }
4850 
4851     ExprResult ConvExpr =
4852         tryConvertExprToType(IndexExpr, Context.getSizeType());
4853     assert(!ConvExpr.isInvalid() &&
4854            "should be able to convert any integer type to size type");
4855     return ConvExpr.get();
4856   };
4857 
4858   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4859   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4860   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4861   if (!RowIdx || !ColumnIdx)
4862     return ExprError();
4863 
4864   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4865                                            MTy->getElementType(), RBLoc);
4866 }
4867 
4868 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4869   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4870   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4871 
4872   // For expressions like `&(*s).b`, the base is recorded and what should be
4873   // checked.
4874   const MemberExpr *Member = nullptr;
4875   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4876     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4877 
4878   LastRecord.PossibleDerefs.erase(StrippedExpr);
4879 }
4880 
4881 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4882   if (isUnevaluatedContext())
4883     return;
4884 
4885   QualType ResultTy = E->getType();
4886   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4887 
4888   // Bail if the element is an array since it is not memory access.
4889   if (isa<ArrayType>(ResultTy))
4890     return;
4891 
4892   if (ResultTy->hasAttr(attr::NoDeref)) {
4893     LastRecord.PossibleDerefs.insert(E);
4894     return;
4895   }
4896 
4897   // Check if the base type is a pointer to a member access of a struct
4898   // marked with noderef.
4899   const Expr *Base = E->getBase();
4900   QualType BaseTy = Base->getType();
4901   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4902     // Not a pointer access
4903     return;
4904 
4905   const MemberExpr *Member = nullptr;
4906   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4907          Member->isArrow())
4908     Base = Member->getBase();
4909 
4910   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4911     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4912       LastRecord.PossibleDerefs.insert(E);
4913   }
4914 }
4915 
4916 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4917                                           Expr *LowerBound,
4918                                           SourceLocation ColonLocFirst,
4919                                           SourceLocation ColonLocSecond,
4920                                           Expr *Length, Expr *Stride,
4921                                           SourceLocation RBLoc) {
4922   if (Base->getType()->isPlaceholderType() &&
4923       !Base->getType()->isSpecificPlaceholderType(
4924           BuiltinType::OMPArraySection)) {
4925     ExprResult Result = CheckPlaceholderExpr(Base);
4926     if (Result.isInvalid())
4927       return ExprError();
4928     Base = Result.get();
4929   }
4930   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4931     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4932     if (Result.isInvalid())
4933       return ExprError();
4934     Result = DefaultLvalueConversion(Result.get());
4935     if (Result.isInvalid())
4936       return ExprError();
4937     LowerBound = Result.get();
4938   }
4939   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4940     ExprResult Result = CheckPlaceholderExpr(Length);
4941     if (Result.isInvalid())
4942       return ExprError();
4943     Result = DefaultLvalueConversion(Result.get());
4944     if (Result.isInvalid())
4945       return ExprError();
4946     Length = Result.get();
4947   }
4948   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4949     ExprResult Result = CheckPlaceholderExpr(Stride);
4950     if (Result.isInvalid())
4951       return ExprError();
4952     Result = DefaultLvalueConversion(Result.get());
4953     if (Result.isInvalid())
4954       return ExprError();
4955     Stride = Result.get();
4956   }
4957 
4958   // Build an unanalyzed expression if either operand is type-dependent.
4959   if (Base->isTypeDependent() ||
4960       (LowerBound &&
4961        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4962       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4963       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4964     return new (Context) OMPArraySectionExpr(
4965         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4966         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4967   }
4968 
4969   // Perform default conversions.
4970   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4971   QualType ResultTy;
4972   if (OriginalTy->isAnyPointerType()) {
4973     ResultTy = OriginalTy->getPointeeType();
4974   } else if (OriginalTy->isArrayType()) {
4975     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4976   } else {
4977     return ExprError(
4978         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4979         << Base->getSourceRange());
4980   }
4981   // C99 6.5.2.1p1
4982   if (LowerBound) {
4983     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4984                                                       LowerBound);
4985     if (Res.isInvalid())
4986       return ExprError(Diag(LowerBound->getExprLoc(),
4987                             diag::err_omp_typecheck_section_not_integer)
4988                        << 0 << LowerBound->getSourceRange());
4989     LowerBound = Res.get();
4990 
4991     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4992         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4993       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4994           << 0 << LowerBound->getSourceRange();
4995   }
4996   if (Length) {
4997     auto Res =
4998         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4999     if (Res.isInvalid())
5000       return ExprError(Diag(Length->getExprLoc(),
5001                             diag::err_omp_typecheck_section_not_integer)
5002                        << 1 << Length->getSourceRange());
5003     Length = Res.get();
5004 
5005     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5006         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5007       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5008           << 1 << Length->getSourceRange();
5009   }
5010   if (Stride) {
5011     ExprResult Res =
5012         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5013     if (Res.isInvalid())
5014       return ExprError(Diag(Stride->getExprLoc(),
5015                             diag::err_omp_typecheck_section_not_integer)
5016                        << 1 << Stride->getSourceRange());
5017     Stride = Res.get();
5018 
5019     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5020         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5021       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5022           << 1 << Stride->getSourceRange();
5023   }
5024 
5025   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5026   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5027   // type. Note that functions are not objects, and that (in C99 parlance)
5028   // incomplete types are not object types.
5029   if (ResultTy->isFunctionType()) {
5030     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5031         << ResultTy << Base->getSourceRange();
5032     return ExprError();
5033   }
5034 
5035   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5036                           diag::err_omp_section_incomplete_type, Base))
5037     return ExprError();
5038 
5039   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5040     Expr::EvalResult Result;
5041     if (LowerBound->EvaluateAsInt(Result, Context)) {
5042       // OpenMP 5.0, [2.1.5 Array Sections]
5043       // The array section must be a subset of the original array.
5044       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5045       if (LowerBoundValue.isNegative()) {
5046         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5047             << LowerBound->getSourceRange();
5048         return ExprError();
5049       }
5050     }
5051   }
5052 
5053   if (Length) {
5054     Expr::EvalResult Result;
5055     if (Length->EvaluateAsInt(Result, Context)) {
5056       // OpenMP 5.0, [2.1.5 Array Sections]
5057       // The length must evaluate to non-negative integers.
5058       llvm::APSInt LengthValue = Result.Val.getInt();
5059       if (LengthValue.isNegative()) {
5060         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5061             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
5062             << Length->getSourceRange();
5063         return ExprError();
5064       }
5065     }
5066   } else if (ColonLocFirst.isValid() &&
5067              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5068                                       !OriginalTy->isVariableArrayType()))) {
5069     // OpenMP 5.0, [2.1.5 Array Sections]
5070     // When the size of the array dimension is not known, the length must be
5071     // specified explicitly.
5072     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5073         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5074     return ExprError();
5075   }
5076 
5077   if (Stride) {
5078     Expr::EvalResult Result;
5079     if (Stride->EvaluateAsInt(Result, Context)) {
5080       // OpenMP 5.0, [2.1.5 Array Sections]
5081       // The stride must evaluate to a positive integer.
5082       llvm::APSInt StrideValue = Result.Val.getInt();
5083       if (!StrideValue.isStrictlyPositive()) {
5084         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5085             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5086             << Stride->getSourceRange();
5087         return ExprError();
5088       }
5089     }
5090   }
5091 
5092   if (!Base->getType()->isSpecificPlaceholderType(
5093           BuiltinType::OMPArraySection)) {
5094     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5095     if (Result.isInvalid())
5096       return ExprError();
5097     Base = Result.get();
5098   }
5099   return new (Context) OMPArraySectionExpr(
5100       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5101       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5102 }
5103 
5104 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5105                                           SourceLocation RParenLoc,
5106                                           ArrayRef<Expr *> Dims,
5107                                           ArrayRef<SourceRange> Brackets) {
5108   if (Base->getType()->isPlaceholderType()) {
5109     ExprResult Result = CheckPlaceholderExpr(Base);
5110     if (Result.isInvalid())
5111       return ExprError();
5112     Result = DefaultLvalueConversion(Result.get());
5113     if (Result.isInvalid())
5114       return ExprError();
5115     Base = Result.get();
5116   }
5117   QualType BaseTy = Base->getType();
5118   // Delay analysis of the types/expressions if instantiation/specialization is
5119   // required.
5120   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5121     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5122                                        LParenLoc, RParenLoc, Dims, Brackets);
5123   if (!BaseTy->isPointerType() ||
5124       (!Base->isTypeDependent() &&
5125        BaseTy->getPointeeType()->isIncompleteType()))
5126     return ExprError(Diag(Base->getExprLoc(),
5127                           diag::err_omp_non_pointer_type_array_shaping_base)
5128                      << Base->getSourceRange());
5129 
5130   SmallVector<Expr *, 4> NewDims;
5131   bool ErrorFound = false;
5132   for (Expr *Dim : Dims) {
5133     if (Dim->getType()->isPlaceholderType()) {
5134       ExprResult Result = CheckPlaceholderExpr(Dim);
5135       if (Result.isInvalid()) {
5136         ErrorFound = true;
5137         continue;
5138       }
5139       Result = DefaultLvalueConversion(Result.get());
5140       if (Result.isInvalid()) {
5141         ErrorFound = true;
5142         continue;
5143       }
5144       Dim = Result.get();
5145     }
5146     if (!Dim->isTypeDependent()) {
5147       ExprResult Result =
5148           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5149       if (Result.isInvalid()) {
5150         ErrorFound = true;
5151         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5152             << Dim->getSourceRange();
5153         continue;
5154       }
5155       Dim = Result.get();
5156       Expr::EvalResult EvResult;
5157       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5158         // OpenMP 5.0, [2.1.4 Array Shaping]
5159         // Each si is an integral type expression that must evaluate to a
5160         // positive integer.
5161         llvm::APSInt Value = EvResult.Val.getInt();
5162         if (!Value.isStrictlyPositive()) {
5163           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5164               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5165               << Dim->getSourceRange();
5166           ErrorFound = true;
5167           continue;
5168         }
5169       }
5170     }
5171     NewDims.push_back(Dim);
5172   }
5173   if (ErrorFound)
5174     return ExprError();
5175   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5176                                      LParenLoc, RParenLoc, NewDims, Brackets);
5177 }
5178 
5179 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5180                                       SourceLocation LLoc, SourceLocation RLoc,
5181                                       ArrayRef<OMPIteratorData> Data) {
5182   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5183   bool IsCorrect = true;
5184   for (const OMPIteratorData &D : Data) {
5185     TypeSourceInfo *TInfo = nullptr;
5186     SourceLocation StartLoc;
5187     QualType DeclTy;
5188     if (!D.Type.getAsOpaquePtr()) {
5189       // OpenMP 5.0, 2.1.6 Iterators
5190       // In an iterator-specifier, if the iterator-type is not specified then
5191       // the type of that iterator is of int type.
5192       DeclTy = Context.IntTy;
5193       StartLoc = D.DeclIdentLoc;
5194     } else {
5195       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5196       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5197     }
5198 
5199     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5200                              DeclTy->containsUnexpandedParameterPack() ||
5201                              DeclTy->isInstantiationDependentType();
5202     if (!IsDeclTyDependent) {
5203       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5204         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5205         // The iterator-type must be an integral or pointer type.
5206         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5207             << DeclTy;
5208         IsCorrect = false;
5209         continue;
5210       }
5211       if (DeclTy.isConstant(Context)) {
5212         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5213         // The iterator-type must not be const qualified.
5214         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5215             << DeclTy;
5216         IsCorrect = false;
5217         continue;
5218       }
5219     }
5220 
5221     // Iterator declaration.
5222     assert(D.DeclIdent && "Identifier expected.");
5223     // Always try to create iterator declarator to avoid extra error messages
5224     // about unknown declarations use.
5225     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5226                                D.DeclIdent, DeclTy, TInfo, SC_None);
5227     VD->setImplicit();
5228     if (S) {
5229       // Check for conflicting previous declaration.
5230       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5231       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5232                             ForVisibleRedeclaration);
5233       Previous.suppressDiagnostics();
5234       LookupName(Previous, S);
5235 
5236       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5237                            /*AllowInlineNamespace=*/false);
5238       if (!Previous.empty()) {
5239         NamedDecl *Old = Previous.getRepresentativeDecl();
5240         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5241         Diag(Old->getLocation(), diag::note_previous_definition);
5242       } else {
5243         PushOnScopeChains(VD, S);
5244       }
5245     } else {
5246       CurContext->addDecl(VD);
5247     }
5248     Expr *Begin = D.Range.Begin;
5249     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5250       ExprResult BeginRes =
5251           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5252       Begin = BeginRes.get();
5253     }
5254     Expr *End = D.Range.End;
5255     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5256       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5257       End = EndRes.get();
5258     }
5259     Expr *Step = D.Range.Step;
5260     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5261       if (!Step->getType()->isIntegralType(Context)) {
5262         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5263             << Step << Step->getSourceRange();
5264         IsCorrect = false;
5265         continue;
5266       }
5267       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5268       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5269       // If the step expression of a range-specification equals zero, the
5270       // behavior is unspecified.
5271       if (Result && Result->isNullValue()) {
5272         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5273             << Step << Step->getSourceRange();
5274         IsCorrect = false;
5275         continue;
5276       }
5277     }
5278     if (!Begin || !End || !IsCorrect) {
5279       IsCorrect = false;
5280       continue;
5281     }
5282     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5283     IDElem.IteratorDecl = VD;
5284     IDElem.AssignmentLoc = D.AssignLoc;
5285     IDElem.Range.Begin = Begin;
5286     IDElem.Range.End = End;
5287     IDElem.Range.Step = Step;
5288     IDElem.ColonLoc = D.ColonLoc;
5289     IDElem.SecondColonLoc = D.SecColonLoc;
5290   }
5291   if (!IsCorrect) {
5292     // Invalidate all created iterator declarations if error is found.
5293     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5294       if (Decl *ID = D.IteratorDecl)
5295         ID->setInvalidDecl();
5296     }
5297     return ExprError();
5298   }
5299   SmallVector<OMPIteratorHelperData, 4> Helpers;
5300   if (!CurContext->isDependentContext()) {
5301     // Build number of ityeration for each iteration range.
5302     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5303     // ((Begini-Stepi-1-Endi) / -Stepi);
5304     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5305       // (Endi - Begini)
5306       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5307                                           D.Range.Begin);
5308       if(!Res.isUsable()) {
5309         IsCorrect = false;
5310         continue;
5311       }
5312       ExprResult St, St1;
5313       if (D.Range.Step) {
5314         St = D.Range.Step;
5315         // (Endi - Begini) + Stepi
5316         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5317         if (!Res.isUsable()) {
5318           IsCorrect = false;
5319           continue;
5320         }
5321         // (Endi - Begini) + Stepi - 1
5322         Res =
5323             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5324                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5325         if (!Res.isUsable()) {
5326           IsCorrect = false;
5327           continue;
5328         }
5329         // ((Endi - Begini) + Stepi - 1) / Stepi
5330         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5331         if (!Res.isUsable()) {
5332           IsCorrect = false;
5333           continue;
5334         }
5335         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5336         // (Begini - Endi)
5337         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5338                                              D.Range.Begin, D.Range.End);
5339         if (!Res1.isUsable()) {
5340           IsCorrect = false;
5341           continue;
5342         }
5343         // (Begini - Endi) - Stepi
5344         Res1 =
5345             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5346         if (!Res1.isUsable()) {
5347           IsCorrect = false;
5348           continue;
5349         }
5350         // (Begini - Endi) - Stepi - 1
5351         Res1 =
5352             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5353                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5354         if (!Res1.isUsable()) {
5355           IsCorrect = false;
5356           continue;
5357         }
5358         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5359         Res1 =
5360             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5361         if (!Res1.isUsable()) {
5362           IsCorrect = false;
5363           continue;
5364         }
5365         // Stepi > 0.
5366         ExprResult CmpRes =
5367             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5368                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5369         if (!CmpRes.isUsable()) {
5370           IsCorrect = false;
5371           continue;
5372         }
5373         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5374                                  Res.get(), Res1.get());
5375         if (!Res.isUsable()) {
5376           IsCorrect = false;
5377           continue;
5378         }
5379       }
5380       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5381       if (!Res.isUsable()) {
5382         IsCorrect = false;
5383         continue;
5384       }
5385 
5386       // Build counter update.
5387       // Build counter.
5388       auto *CounterVD =
5389           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5390                           D.IteratorDecl->getBeginLoc(), nullptr,
5391                           Res.get()->getType(), nullptr, SC_None);
5392       CounterVD->setImplicit();
5393       ExprResult RefRes =
5394           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5395                            D.IteratorDecl->getBeginLoc());
5396       // Build counter update.
5397       // I = Begini + counter * Stepi;
5398       ExprResult UpdateRes;
5399       if (D.Range.Step) {
5400         UpdateRes = CreateBuiltinBinOp(
5401             D.AssignmentLoc, BO_Mul,
5402             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5403       } else {
5404         UpdateRes = DefaultLvalueConversion(RefRes.get());
5405       }
5406       if (!UpdateRes.isUsable()) {
5407         IsCorrect = false;
5408         continue;
5409       }
5410       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5411                                      UpdateRes.get());
5412       if (!UpdateRes.isUsable()) {
5413         IsCorrect = false;
5414         continue;
5415       }
5416       ExprResult VDRes =
5417           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5418                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5419                            D.IteratorDecl->getBeginLoc());
5420       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5421                                      UpdateRes.get());
5422       if (!UpdateRes.isUsable()) {
5423         IsCorrect = false;
5424         continue;
5425       }
5426       UpdateRes =
5427           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5428       if (!UpdateRes.isUsable()) {
5429         IsCorrect = false;
5430         continue;
5431       }
5432       ExprResult CounterUpdateRes =
5433           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5434       if (!CounterUpdateRes.isUsable()) {
5435         IsCorrect = false;
5436         continue;
5437       }
5438       CounterUpdateRes =
5439           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5440       if (!CounterUpdateRes.isUsable()) {
5441         IsCorrect = false;
5442         continue;
5443       }
5444       OMPIteratorHelperData &HD = Helpers.emplace_back();
5445       HD.CounterVD = CounterVD;
5446       HD.Upper = Res.get();
5447       HD.Update = UpdateRes.get();
5448       HD.CounterUpdate = CounterUpdateRes.get();
5449     }
5450   } else {
5451     Helpers.assign(ID.size(), {});
5452   }
5453   if (!IsCorrect) {
5454     // Invalidate all created iterator declarations if error is found.
5455     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5456       if (Decl *ID = D.IteratorDecl)
5457         ID->setInvalidDecl();
5458     }
5459     return ExprError();
5460   }
5461   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5462                                  LLoc, RLoc, ID, Helpers);
5463 }
5464 
5465 ExprResult
5466 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5467                                       Expr *Idx, SourceLocation RLoc) {
5468   Expr *LHSExp = Base;
5469   Expr *RHSExp = Idx;
5470 
5471   ExprValueKind VK = VK_LValue;
5472   ExprObjectKind OK = OK_Ordinary;
5473 
5474   // Per C++ core issue 1213, the result is an xvalue if either operand is
5475   // a non-lvalue array, and an lvalue otherwise.
5476   if (getLangOpts().CPlusPlus11) {
5477     for (auto *Op : {LHSExp, RHSExp}) {
5478       Op = Op->IgnoreImplicit();
5479       if (Op->getType()->isArrayType() && !Op->isLValue())
5480         VK = VK_XValue;
5481     }
5482   }
5483 
5484   // Perform default conversions.
5485   if (!LHSExp->getType()->getAs<VectorType>()) {
5486     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5487     if (Result.isInvalid())
5488       return ExprError();
5489     LHSExp = Result.get();
5490   }
5491   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5492   if (Result.isInvalid())
5493     return ExprError();
5494   RHSExp = Result.get();
5495 
5496   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5497 
5498   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5499   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5500   // in the subscript position. As a result, we need to derive the array base
5501   // and index from the expression types.
5502   Expr *BaseExpr, *IndexExpr;
5503   QualType ResultType;
5504   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5505     BaseExpr = LHSExp;
5506     IndexExpr = RHSExp;
5507     ResultType = Context.DependentTy;
5508   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5509     BaseExpr = LHSExp;
5510     IndexExpr = RHSExp;
5511     ResultType = PTy->getPointeeType();
5512   } else if (const ObjCObjectPointerType *PTy =
5513                LHSTy->getAs<ObjCObjectPointerType>()) {
5514     BaseExpr = LHSExp;
5515     IndexExpr = RHSExp;
5516 
5517     // Use custom logic if this should be the pseudo-object subscript
5518     // expression.
5519     if (!LangOpts.isSubscriptPointerArithmetic())
5520       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5521                                           nullptr);
5522 
5523     ResultType = PTy->getPointeeType();
5524   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5525      // Handle the uncommon case of "123[Ptr]".
5526     BaseExpr = RHSExp;
5527     IndexExpr = LHSExp;
5528     ResultType = PTy->getPointeeType();
5529   } else if (const ObjCObjectPointerType *PTy =
5530                RHSTy->getAs<ObjCObjectPointerType>()) {
5531      // Handle the uncommon case of "123[Ptr]".
5532     BaseExpr = RHSExp;
5533     IndexExpr = LHSExp;
5534     ResultType = PTy->getPointeeType();
5535     if (!LangOpts.isSubscriptPointerArithmetic()) {
5536       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5537         << ResultType << BaseExpr->getSourceRange();
5538       return ExprError();
5539     }
5540   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5541     BaseExpr = LHSExp;    // vectors: V[123]
5542     IndexExpr = RHSExp;
5543     // We apply C++ DR1213 to vector subscripting too.
5544     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5545       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5546       if (Materialized.isInvalid())
5547         return ExprError();
5548       LHSExp = Materialized.get();
5549     }
5550     VK = LHSExp->getValueKind();
5551     if (VK != VK_RValue)
5552       OK = OK_VectorComponent;
5553 
5554     ResultType = VTy->getElementType();
5555     QualType BaseType = BaseExpr->getType();
5556     Qualifiers BaseQuals = BaseType.getQualifiers();
5557     Qualifiers MemberQuals = ResultType.getQualifiers();
5558     Qualifiers Combined = BaseQuals + MemberQuals;
5559     if (Combined != MemberQuals)
5560       ResultType = Context.getQualifiedType(ResultType, Combined);
5561   } else if (LHSTy->isArrayType()) {
5562     // If we see an array that wasn't promoted by
5563     // DefaultFunctionArrayLvalueConversion, it must be an array that
5564     // wasn't promoted because of the C90 rule that doesn't
5565     // allow promoting non-lvalue arrays.  Warn, then
5566     // force the promotion here.
5567     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5568         << LHSExp->getSourceRange();
5569     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5570                                CK_ArrayToPointerDecay).get();
5571     LHSTy = LHSExp->getType();
5572 
5573     BaseExpr = LHSExp;
5574     IndexExpr = RHSExp;
5575     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5576   } else if (RHSTy->isArrayType()) {
5577     // Same as previous, except for 123[f().a] case
5578     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5579         << RHSExp->getSourceRange();
5580     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5581                                CK_ArrayToPointerDecay).get();
5582     RHSTy = RHSExp->getType();
5583 
5584     BaseExpr = RHSExp;
5585     IndexExpr = LHSExp;
5586     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5587   } else {
5588     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5589        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5590   }
5591   // C99 6.5.2.1p1
5592   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5593     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5594                      << IndexExpr->getSourceRange());
5595 
5596   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5597        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5598          && !IndexExpr->isTypeDependent())
5599     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5600 
5601   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5602   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5603   // type. Note that Functions are not objects, and that (in C99 parlance)
5604   // incomplete types are not object types.
5605   if (ResultType->isFunctionType()) {
5606     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5607         << ResultType << BaseExpr->getSourceRange();
5608     return ExprError();
5609   }
5610 
5611   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5612     // GNU extension: subscripting on pointer to void
5613     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5614       << BaseExpr->getSourceRange();
5615 
5616     // C forbids expressions of unqualified void type from being l-values.
5617     // See IsCForbiddenLValueType.
5618     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5619   } else if (!ResultType->isDependentType() &&
5620              RequireCompleteSizedType(
5621                  LLoc, ResultType,
5622                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5623     return ExprError();
5624 
5625   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5626          !ResultType.isCForbiddenLValueType());
5627 
5628   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5629       FunctionScopes.size() > 1) {
5630     if (auto *TT =
5631             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5632       for (auto I = FunctionScopes.rbegin(),
5633                 E = std::prev(FunctionScopes.rend());
5634            I != E; ++I) {
5635         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5636         if (CSI == nullptr)
5637           break;
5638         DeclContext *DC = nullptr;
5639         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5640           DC = LSI->CallOperator;
5641         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5642           DC = CRSI->TheCapturedDecl;
5643         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5644           DC = BSI->TheDecl;
5645         if (DC) {
5646           if (DC->containsDecl(TT->getDecl()))
5647             break;
5648           captureVariablyModifiedType(
5649               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5650         }
5651       }
5652     }
5653   }
5654 
5655   return new (Context)
5656       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5657 }
5658 
5659 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5660                                   ParmVarDecl *Param) {
5661   if (Param->hasUnparsedDefaultArg()) {
5662     // If we've already cleared out the location for the default argument,
5663     // that means we're parsing it right now.
5664     if (!UnparsedDefaultArgLocs.count(Param)) {
5665       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5666       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5667       Param->setInvalidDecl();
5668       return true;
5669     }
5670 
5671     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5672         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5673     Diag(UnparsedDefaultArgLocs[Param],
5674          diag::note_default_argument_declared_here);
5675     return true;
5676   }
5677 
5678   if (Param->hasUninstantiatedDefaultArg() &&
5679       InstantiateDefaultArgument(CallLoc, FD, Param))
5680     return true;
5681 
5682   assert(Param->hasInit() && "default argument but no initializer?");
5683 
5684   // If the default expression creates temporaries, we need to
5685   // push them to the current stack of expression temporaries so they'll
5686   // be properly destroyed.
5687   // FIXME: We should really be rebuilding the default argument with new
5688   // bound temporaries; see the comment in PR5810.
5689   // We don't need to do that with block decls, though, because
5690   // blocks in default argument expression can never capture anything.
5691   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5692     // Set the "needs cleanups" bit regardless of whether there are
5693     // any explicit objects.
5694     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5695 
5696     // Append all the objects to the cleanup list.  Right now, this
5697     // should always be a no-op, because blocks in default argument
5698     // expressions should never be able to capture anything.
5699     assert(!Init->getNumObjects() &&
5700            "default argument expression has capturing blocks?");
5701   }
5702 
5703   // We already type-checked the argument, so we know it works.
5704   // Just mark all of the declarations in this potentially-evaluated expression
5705   // as being "referenced".
5706   EnterExpressionEvaluationContext EvalContext(
5707       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5708   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5709                                    /*SkipLocalVariables=*/true);
5710   return false;
5711 }
5712 
5713 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5714                                         FunctionDecl *FD, ParmVarDecl *Param) {
5715   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5716   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5717     return ExprError();
5718   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5719 }
5720 
5721 Sema::VariadicCallType
5722 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5723                           Expr *Fn) {
5724   if (Proto && Proto->isVariadic()) {
5725     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5726       return VariadicConstructor;
5727     else if (Fn && Fn->getType()->isBlockPointerType())
5728       return VariadicBlock;
5729     else if (FDecl) {
5730       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5731         if (Method->isInstance())
5732           return VariadicMethod;
5733     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5734       return VariadicMethod;
5735     return VariadicFunction;
5736   }
5737   return VariadicDoesNotApply;
5738 }
5739 
5740 namespace {
5741 class FunctionCallCCC final : public FunctionCallFilterCCC {
5742 public:
5743   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5744                   unsigned NumArgs, MemberExpr *ME)
5745       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5746         FunctionName(FuncName) {}
5747 
5748   bool ValidateCandidate(const TypoCorrection &candidate) override {
5749     if (!candidate.getCorrectionSpecifier() ||
5750         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5751       return false;
5752     }
5753 
5754     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5755   }
5756 
5757   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5758     return std::make_unique<FunctionCallCCC>(*this);
5759   }
5760 
5761 private:
5762   const IdentifierInfo *const FunctionName;
5763 };
5764 }
5765 
5766 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5767                                                FunctionDecl *FDecl,
5768                                                ArrayRef<Expr *> Args) {
5769   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5770   DeclarationName FuncName = FDecl->getDeclName();
5771   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5772 
5773   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5774   if (TypoCorrection Corrected = S.CorrectTypo(
5775           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5776           S.getScopeForContext(S.CurContext), nullptr, CCC,
5777           Sema::CTK_ErrorRecovery)) {
5778     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5779       if (Corrected.isOverloaded()) {
5780         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5781         OverloadCandidateSet::iterator Best;
5782         for (NamedDecl *CD : Corrected) {
5783           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5784             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5785                                    OCS);
5786         }
5787         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5788         case OR_Success:
5789           ND = Best->FoundDecl;
5790           Corrected.setCorrectionDecl(ND);
5791           break;
5792         default:
5793           break;
5794         }
5795       }
5796       ND = ND->getUnderlyingDecl();
5797       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5798         return Corrected;
5799     }
5800   }
5801   return TypoCorrection();
5802 }
5803 
5804 /// ConvertArgumentsForCall - Converts the arguments specified in
5805 /// Args/NumArgs to the parameter types of the function FDecl with
5806 /// function prototype Proto. Call is the call expression itself, and
5807 /// Fn is the function expression. For a C++ member function, this
5808 /// routine does not attempt to convert the object argument. Returns
5809 /// true if the call is ill-formed.
5810 bool
5811 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5812                               FunctionDecl *FDecl,
5813                               const FunctionProtoType *Proto,
5814                               ArrayRef<Expr *> Args,
5815                               SourceLocation RParenLoc,
5816                               bool IsExecConfig) {
5817   // Bail out early if calling a builtin with custom typechecking.
5818   if (FDecl)
5819     if (unsigned ID = FDecl->getBuiltinID())
5820       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5821         return false;
5822 
5823   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5824   // assignment, to the types of the corresponding parameter, ...
5825   unsigned NumParams = Proto->getNumParams();
5826   bool Invalid = false;
5827   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5828   unsigned FnKind = Fn->getType()->isBlockPointerType()
5829                        ? 1 /* block */
5830                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5831                                        : 0 /* function */);
5832 
5833   // If too few arguments are available (and we don't have default
5834   // arguments for the remaining parameters), don't make the call.
5835   if (Args.size() < NumParams) {
5836     if (Args.size() < MinArgs) {
5837       TypoCorrection TC;
5838       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5839         unsigned diag_id =
5840             MinArgs == NumParams && !Proto->isVariadic()
5841                 ? diag::err_typecheck_call_too_few_args_suggest
5842                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5843         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5844                                         << static_cast<unsigned>(Args.size())
5845                                         << TC.getCorrectionRange());
5846       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5847         Diag(RParenLoc,
5848              MinArgs == NumParams && !Proto->isVariadic()
5849                  ? diag::err_typecheck_call_too_few_args_one
5850                  : diag::err_typecheck_call_too_few_args_at_least_one)
5851             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5852       else
5853         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5854                             ? diag::err_typecheck_call_too_few_args
5855                             : diag::err_typecheck_call_too_few_args_at_least)
5856             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5857             << Fn->getSourceRange();
5858 
5859       // Emit the location of the prototype.
5860       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5861         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5862 
5863       return true;
5864     }
5865     // We reserve space for the default arguments when we create
5866     // the call expression, before calling ConvertArgumentsForCall.
5867     assert((Call->getNumArgs() == NumParams) &&
5868            "We should have reserved space for the default arguments before!");
5869   }
5870 
5871   // If too many are passed and not variadic, error on the extras and drop
5872   // them.
5873   if (Args.size() > NumParams) {
5874     if (!Proto->isVariadic()) {
5875       TypoCorrection TC;
5876       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5877         unsigned diag_id =
5878             MinArgs == NumParams && !Proto->isVariadic()
5879                 ? diag::err_typecheck_call_too_many_args_suggest
5880                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5881         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5882                                         << static_cast<unsigned>(Args.size())
5883                                         << TC.getCorrectionRange());
5884       } else if (NumParams == 1 && FDecl &&
5885                  FDecl->getParamDecl(0)->getDeclName())
5886         Diag(Args[NumParams]->getBeginLoc(),
5887              MinArgs == NumParams
5888                  ? diag::err_typecheck_call_too_many_args_one
5889                  : diag::err_typecheck_call_too_many_args_at_most_one)
5890             << FnKind << FDecl->getParamDecl(0)
5891             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5892             << SourceRange(Args[NumParams]->getBeginLoc(),
5893                            Args.back()->getEndLoc());
5894       else
5895         Diag(Args[NumParams]->getBeginLoc(),
5896              MinArgs == NumParams
5897                  ? diag::err_typecheck_call_too_many_args
5898                  : diag::err_typecheck_call_too_many_args_at_most)
5899             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5900             << Fn->getSourceRange()
5901             << SourceRange(Args[NumParams]->getBeginLoc(),
5902                            Args.back()->getEndLoc());
5903 
5904       // Emit the location of the prototype.
5905       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5906         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5907 
5908       // This deletes the extra arguments.
5909       Call->shrinkNumArgs(NumParams);
5910       return true;
5911     }
5912   }
5913   SmallVector<Expr *, 8> AllArgs;
5914   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5915 
5916   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5917                                    AllArgs, CallType);
5918   if (Invalid)
5919     return true;
5920   unsigned TotalNumArgs = AllArgs.size();
5921   for (unsigned i = 0; i < TotalNumArgs; ++i)
5922     Call->setArg(i, AllArgs[i]);
5923 
5924   return false;
5925 }
5926 
5927 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5928                                   const FunctionProtoType *Proto,
5929                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5930                                   SmallVectorImpl<Expr *> &AllArgs,
5931                                   VariadicCallType CallType, bool AllowExplicit,
5932                                   bool IsListInitialization) {
5933   unsigned NumParams = Proto->getNumParams();
5934   bool Invalid = false;
5935   size_t ArgIx = 0;
5936   // Continue to check argument types (even if we have too few/many args).
5937   for (unsigned i = FirstParam; i < NumParams; i++) {
5938     QualType ProtoArgType = Proto->getParamType(i);
5939 
5940     Expr *Arg;
5941     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5942     if (ArgIx < Args.size()) {
5943       Arg = Args[ArgIx++];
5944 
5945       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5946                               diag::err_call_incomplete_argument, Arg))
5947         return true;
5948 
5949       // Strip the unbridged-cast placeholder expression off, if applicable.
5950       bool CFAudited = false;
5951       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5952           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5953           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5954         Arg = stripARCUnbridgedCast(Arg);
5955       else if (getLangOpts().ObjCAutoRefCount &&
5956                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5957                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5958         CFAudited = true;
5959 
5960       if (Proto->getExtParameterInfo(i).isNoEscape() &&
5961           ProtoArgType->isBlockPointerType())
5962         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5963           BE->getBlockDecl()->setDoesNotEscape();
5964 
5965       InitializedEntity Entity =
5966           Param ? InitializedEntity::InitializeParameter(Context, Param,
5967                                                          ProtoArgType)
5968                 : InitializedEntity::InitializeParameter(
5969                       Context, ProtoArgType, Proto->isParamConsumed(i));
5970 
5971       // Remember that parameter belongs to a CF audited API.
5972       if (CFAudited)
5973         Entity.setParameterCFAudited();
5974 
5975       ExprResult ArgE = PerformCopyInitialization(
5976           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5977       if (ArgE.isInvalid())
5978         return true;
5979 
5980       Arg = ArgE.getAs<Expr>();
5981     } else {
5982       assert(Param && "can't use default arguments without a known callee");
5983 
5984       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5985       if (ArgExpr.isInvalid())
5986         return true;
5987 
5988       Arg = ArgExpr.getAs<Expr>();
5989     }
5990 
5991     // Check for array bounds violations for each argument to the call. This
5992     // check only triggers warnings when the argument isn't a more complex Expr
5993     // with its own checking, such as a BinaryOperator.
5994     CheckArrayAccess(Arg);
5995 
5996     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5997     CheckStaticArrayArgument(CallLoc, Param, Arg);
5998 
5999     AllArgs.push_back(Arg);
6000   }
6001 
6002   // If this is a variadic call, handle args passed through "...".
6003   if (CallType != VariadicDoesNotApply) {
6004     // Assume that extern "C" functions with variadic arguments that
6005     // return __unknown_anytype aren't *really* variadic.
6006     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6007         FDecl->isExternC()) {
6008       for (Expr *A : Args.slice(ArgIx)) {
6009         QualType paramType; // ignored
6010         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6011         Invalid |= arg.isInvalid();
6012         AllArgs.push_back(arg.get());
6013       }
6014 
6015     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6016     } else {
6017       for (Expr *A : Args.slice(ArgIx)) {
6018         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6019         Invalid |= Arg.isInvalid();
6020         AllArgs.push_back(Arg.get());
6021       }
6022     }
6023 
6024     // Check for array bounds violations.
6025     for (Expr *A : Args.slice(ArgIx))
6026       CheckArrayAccess(A);
6027   }
6028   return Invalid;
6029 }
6030 
6031 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6032   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6033   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6034     TL = DTL.getOriginalLoc();
6035   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6036     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6037       << ATL.getLocalSourceRange();
6038 }
6039 
6040 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6041 /// array parameter, check that it is non-null, and that if it is formed by
6042 /// array-to-pointer decay, the underlying array is sufficiently large.
6043 ///
6044 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6045 /// array type derivation, then for each call to the function, the value of the
6046 /// corresponding actual argument shall provide access to the first element of
6047 /// an array with at least as many elements as specified by the size expression.
6048 void
6049 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6050                                ParmVarDecl *Param,
6051                                const Expr *ArgExpr) {
6052   // Static array parameters are not supported in C++.
6053   if (!Param || getLangOpts().CPlusPlus)
6054     return;
6055 
6056   QualType OrigTy = Param->getOriginalType();
6057 
6058   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6059   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6060     return;
6061 
6062   if (ArgExpr->isNullPointerConstant(Context,
6063                                      Expr::NPC_NeverValueDependent)) {
6064     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6065     DiagnoseCalleeStaticArrayParam(*this, Param);
6066     return;
6067   }
6068 
6069   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6070   if (!CAT)
6071     return;
6072 
6073   const ConstantArrayType *ArgCAT =
6074     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6075   if (!ArgCAT)
6076     return;
6077 
6078   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6079                                              ArgCAT->getElementType())) {
6080     if (ArgCAT->getSize().ult(CAT->getSize())) {
6081       Diag(CallLoc, diag::warn_static_array_too_small)
6082           << ArgExpr->getSourceRange()
6083           << (unsigned)ArgCAT->getSize().getZExtValue()
6084           << (unsigned)CAT->getSize().getZExtValue() << 0;
6085       DiagnoseCalleeStaticArrayParam(*this, Param);
6086     }
6087     return;
6088   }
6089 
6090   Optional<CharUnits> ArgSize =
6091       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6092   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6093   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6094     Diag(CallLoc, diag::warn_static_array_too_small)
6095         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6096         << (unsigned)ParmSize->getQuantity() << 1;
6097     DiagnoseCalleeStaticArrayParam(*this, Param);
6098   }
6099 }
6100 
6101 /// Given a function expression of unknown-any type, try to rebuild it
6102 /// to have a function type.
6103 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6104 
6105 /// Is the given type a placeholder that we need to lower out
6106 /// immediately during argument processing?
6107 static bool isPlaceholderToRemoveAsArg(QualType type) {
6108   // Placeholders are never sugared.
6109   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6110   if (!placeholder) return false;
6111 
6112   switch (placeholder->getKind()) {
6113   // Ignore all the non-placeholder types.
6114 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6115   case BuiltinType::Id:
6116 #include "clang/Basic/OpenCLImageTypes.def"
6117 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6118   case BuiltinType::Id:
6119 #include "clang/Basic/OpenCLExtensionTypes.def"
6120   // In practice we'll never use this, since all SVE types are sugared
6121   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6122 #define SVE_TYPE(Name, Id, SingletonId) \
6123   case BuiltinType::Id:
6124 #include "clang/Basic/AArch64SVEACLETypes.def"
6125 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6126   case BuiltinType::Id:
6127 #include "clang/Basic/PPCTypes.def"
6128 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6129 #include "clang/Basic/RISCVVTypes.def"
6130 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6131 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6132 #include "clang/AST/BuiltinTypes.def"
6133     return false;
6134 
6135   // We cannot lower out overload sets; they might validly be resolved
6136   // by the call machinery.
6137   case BuiltinType::Overload:
6138     return false;
6139 
6140   // Unbridged casts in ARC can be handled in some call positions and
6141   // should be left in place.
6142   case BuiltinType::ARCUnbridgedCast:
6143     return false;
6144 
6145   // Pseudo-objects should be converted as soon as possible.
6146   case BuiltinType::PseudoObject:
6147     return true;
6148 
6149   // The debugger mode could theoretically but currently does not try
6150   // to resolve unknown-typed arguments based on known parameter types.
6151   case BuiltinType::UnknownAny:
6152     return true;
6153 
6154   // These are always invalid as call arguments and should be reported.
6155   case BuiltinType::BoundMember:
6156   case BuiltinType::BuiltinFn:
6157   case BuiltinType::IncompleteMatrixIdx:
6158   case BuiltinType::OMPArraySection:
6159   case BuiltinType::OMPArrayShaping:
6160   case BuiltinType::OMPIterator:
6161     return true;
6162 
6163   }
6164   llvm_unreachable("bad builtin type kind");
6165 }
6166 
6167 /// Check an argument list for placeholders that we won't try to
6168 /// handle later.
6169 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6170   // Apply this processing to all the arguments at once instead of
6171   // dying at the first failure.
6172   bool hasInvalid = false;
6173   for (size_t i = 0, e = args.size(); i != e; i++) {
6174     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6175       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6176       if (result.isInvalid()) hasInvalid = true;
6177       else args[i] = result.get();
6178     }
6179   }
6180   return hasInvalid;
6181 }
6182 
6183 /// If a builtin function has a pointer argument with no explicit address
6184 /// space, then it should be able to accept a pointer to any address
6185 /// space as input.  In order to do this, we need to replace the
6186 /// standard builtin declaration with one that uses the same address space
6187 /// as the call.
6188 ///
6189 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6190 ///                  it does not contain any pointer arguments without
6191 ///                  an address space qualifer.  Otherwise the rewritten
6192 ///                  FunctionDecl is returned.
6193 /// TODO: Handle pointer return types.
6194 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6195                                                 FunctionDecl *FDecl,
6196                                                 MultiExprArg ArgExprs) {
6197 
6198   QualType DeclType = FDecl->getType();
6199   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6200 
6201   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6202       ArgExprs.size() < FT->getNumParams())
6203     return nullptr;
6204 
6205   bool NeedsNewDecl = false;
6206   unsigned i = 0;
6207   SmallVector<QualType, 8> OverloadParams;
6208 
6209   for (QualType ParamType : FT->param_types()) {
6210 
6211     // Convert array arguments to pointer to simplify type lookup.
6212     ExprResult ArgRes =
6213         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6214     if (ArgRes.isInvalid())
6215       return nullptr;
6216     Expr *Arg = ArgRes.get();
6217     QualType ArgType = Arg->getType();
6218     if (!ParamType->isPointerType() ||
6219         ParamType.hasAddressSpace() ||
6220         !ArgType->isPointerType() ||
6221         !ArgType->getPointeeType().hasAddressSpace()) {
6222       OverloadParams.push_back(ParamType);
6223       continue;
6224     }
6225 
6226     QualType PointeeType = ParamType->getPointeeType();
6227     if (PointeeType.hasAddressSpace())
6228       continue;
6229 
6230     NeedsNewDecl = true;
6231     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6232 
6233     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6234     OverloadParams.push_back(Context.getPointerType(PointeeType));
6235   }
6236 
6237   if (!NeedsNewDecl)
6238     return nullptr;
6239 
6240   FunctionProtoType::ExtProtoInfo EPI;
6241   EPI.Variadic = FT->isVariadic();
6242   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6243                                                 OverloadParams, EPI);
6244   DeclContext *Parent = FDecl->getParent();
6245   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6246                                                     FDecl->getLocation(),
6247                                                     FDecl->getLocation(),
6248                                                     FDecl->getIdentifier(),
6249                                                     OverloadTy,
6250                                                     /*TInfo=*/nullptr,
6251                                                     SC_Extern, false,
6252                                                     /*hasPrototype=*/true);
6253   SmallVector<ParmVarDecl*, 16> Params;
6254   FT = cast<FunctionProtoType>(OverloadTy);
6255   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6256     QualType ParamType = FT->getParamType(i);
6257     ParmVarDecl *Parm =
6258         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6259                                 SourceLocation(), nullptr, ParamType,
6260                                 /*TInfo=*/nullptr, SC_None, nullptr);
6261     Parm->setScopeInfo(0, i);
6262     Params.push_back(Parm);
6263   }
6264   OverloadDecl->setParams(Params);
6265   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6266   return OverloadDecl;
6267 }
6268 
6269 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6270                                     FunctionDecl *Callee,
6271                                     MultiExprArg ArgExprs) {
6272   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6273   // similar attributes) really don't like it when functions are called with an
6274   // invalid number of args.
6275   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6276                          /*PartialOverloading=*/false) &&
6277       !Callee->isVariadic())
6278     return;
6279   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6280     return;
6281 
6282   if (const EnableIfAttr *Attr =
6283           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6284     S.Diag(Fn->getBeginLoc(),
6285            isa<CXXMethodDecl>(Callee)
6286                ? diag::err_ovl_no_viable_member_function_in_call
6287                : diag::err_ovl_no_viable_function_in_call)
6288         << Callee << Callee->getSourceRange();
6289     S.Diag(Callee->getLocation(),
6290            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6291         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6292     return;
6293   }
6294 }
6295 
6296 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6297     const UnresolvedMemberExpr *const UME, Sema &S) {
6298 
6299   const auto GetFunctionLevelDCIfCXXClass =
6300       [](Sema &S) -> const CXXRecordDecl * {
6301     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6302     if (!DC || !DC->getParent())
6303       return nullptr;
6304 
6305     // If the call to some member function was made from within a member
6306     // function body 'M' return return 'M's parent.
6307     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6308       return MD->getParent()->getCanonicalDecl();
6309     // else the call was made from within a default member initializer of a
6310     // class, so return the class.
6311     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6312       return RD->getCanonicalDecl();
6313     return nullptr;
6314   };
6315   // If our DeclContext is neither a member function nor a class (in the
6316   // case of a lambda in a default member initializer), we can't have an
6317   // enclosing 'this'.
6318 
6319   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6320   if (!CurParentClass)
6321     return false;
6322 
6323   // The naming class for implicit member functions call is the class in which
6324   // name lookup starts.
6325   const CXXRecordDecl *const NamingClass =
6326       UME->getNamingClass()->getCanonicalDecl();
6327   assert(NamingClass && "Must have naming class even for implicit access");
6328 
6329   // If the unresolved member functions were found in a 'naming class' that is
6330   // related (either the same or derived from) to the class that contains the
6331   // member function that itself contained the implicit member access.
6332 
6333   return CurParentClass == NamingClass ||
6334          CurParentClass->isDerivedFrom(NamingClass);
6335 }
6336 
6337 static void
6338 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6339     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6340 
6341   if (!UME)
6342     return;
6343 
6344   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6345   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6346   // already been captured, or if this is an implicit member function call (if
6347   // it isn't, an attempt to capture 'this' should already have been made).
6348   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6349       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6350     return;
6351 
6352   // Check if the naming class in which the unresolved members were found is
6353   // related (same as or is a base of) to the enclosing class.
6354 
6355   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6356     return;
6357 
6358 
6359   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6360   // If the enclosing function is not dependent, then this lambda is
6361   // capture ready, so if we can capture this, do so.
6362   if (!EnclosingFunctionCtx->isDependentContext()) {
6363     // If the current lambda and all enclosing lambdas can capture 'this' -
6364     // then go ahead and capture 'this' (since our unresolved overload set
6365     // contains at least one non-static member function).
6366     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6367       S.CheckCXXThisCapture(CallLoc);
6368   } else if (S.CurContext->isDependentContext()) {
6369     // ... since this is an implicit member reference, that might potentially
6370     // involve a 'this' capture, mark 'this' for potential capture in
6371     // enclosing lambdas.
6372     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6373       CurLSI->addPotentialThisCapture(CallLoc);
6374   }
6375 }
6376 
6377 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6378                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6379                                Expr *ExecConfig) {
6380   ExprResult Call =
6381       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6382                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6383   if (Call.isInvalid())
6384     return Call;
6385 
6386   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6387   // language modes.
6388   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6389     if (ULE->hasExplicitTemplateArgs() &&
6390         ULE->decls_begin() == ULE->decls_end()) {
6391       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6392                                  ? diag::warn_cxx17_compat_adl_only_template_id
6393                                  : diag::ext_adl_only_template_id)
6394           << ULE->getName();
6395     }
6396   }
6397 
6398   if (LangOpts.OpenMP)
6399     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6400                            ExecConfig);
6401 
6402   return Call;
6403 }
6404 
6405 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6406 /// This provides the location of the left/right parens and a list of comma
6407 /// locations.
6408 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6409                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6410                                Expr *ExecConfig, bool IsExecConfig,
6411                                bool AllowRecovery) {
6412   // Since this might be a postfix expression, get rid of ParenListExprs.
6413   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6414   if (Result.isInvalid()) return ExprError();
6415   Fn = Result.get();
6416 
6417   if (checkArgsForPlaceholders(*this, ArgExprs))
6418     return ExprError();
6419 
6420   if (getLangOpts().CPlusPlus) {
6421     // If this is a pseudo-destructor expression, build the call immediately.
6422     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6423       if (!ArgExprs.empty()) {
6424         // Pseudo-destructor calls should not have any arguments.
6425         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6426             << FixItHint::CreateRemoval(
6427                    SourceRange(ArgExprs.front()->getBeginLoc(),
6428                                ArgExprs.back()->getEndLoc()));
6429       }
6430 
6431       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6432                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6433     }
6434     if (Fn->getType() == Context.PseudoObjectTy) {
6435       ExprResult result = CheckPlaceholderExpr(Fn);
6436       if (result.isInvalid()) return ExprError();
6437       Fn = result.get();
6438     }
6439 
6440     // Determine whether this is a dependent call inside a C++ template,
6441     // in which case we won't do any semantic analysis now.
6442     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6443       if (ExecConfig) {
6444         return CUDAKernelCallExpr::Create(
6445             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6446             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6447       } else {
6448 
6449         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6450             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6451             Fn->getBeginLoc());
6452 
6453         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6454                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6455       }
6456     }
6457 
6458     // Determine whether this is a call to an object (C++ [over.call.object]).
6459     if (Fn->getType()->isRecordType())
6460       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6461                                           RParenLoc);
6462 
6463     if (Fn->getType() == Context.UnknownAnyTy) {
6464       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6465       if (result.isInvalid()) return ExprError();
6466       Fn = result.get();
6467     }
6468 
6469     if (Fn->getType() == Context.BoundMemberTy) {
6470       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6471                                        RParenLoc, AllowRecovery);
6472     }
6473   }
6474 
6475   // Check for overloaded calls.  This can happen even in C due to extensions.
6476   if (Fn->getType() == Context.OverloadTy) {
6477     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6478 
6479     // We aren't supposed to apply this logic if there's an '&' involved.
6480     if (!find.HasFormOfMemberPointer) {
6481       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6482         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6483                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6484       OverloadExpr *ovl = find.Expression;
6485       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6486         return BuildOverloadedCallExpr(
6487             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6488             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6489       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6490                                        RParenLoc, AllowRecovery);
6491     }
6492   }
6493 
6494   // If we're directly calling a function, get the appropriate declaration.
6495   if (Fn->getType() == Context.UnknownAnyTy) {
6496     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6497     if (result.isInvalid()) return ExprError();
6498     Fn = result.get();
6499   }
6500 
6501   Expr *NakedFn = Fn->IgnoreParens();
6502 
6503   bool CallingNDeclIndirectly = false;
6504   NamedDecl *NDecl = nullptr;
6505   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6506     if (UnOp->getOpcode() == UO_AddrOf) {
6507       CallingNDeclIndirectly = true;
6508       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6509     }
6510   }
6511 
6512   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6513     NDecl = DRE->getDecl();
6514 
6515     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6516     if (FDecl && FDecl->getBuiltinID()) {
6517       // Rewrite the function decl for this builtin by replacing parameters
6518       // with no explicit address space with the address space of the arguments
6519       // in ArgExprs.
6520       if ((FDecl =
6521                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6522         NDecl = FDecl;
6523         Fn = DeclRefExpr::Create(
6524             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6525             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6526             nullptr, DRE->isNonOdrUse());
6527       }
6528     }
6529   } else if (isa<MemberExpr>(NakedFn))
6530     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6531 
6532   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6533     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6534                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6535       return ExprError();
6536 
6537     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6538   }
6539 
6540   if (Context.isDependenceAllowed() &&
6541       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6542     assert(!getLangOpts().CPlusPlus);
6543     assert((Fn->containsErrors() ||
6544             llvm::any_of(ArgExprs,
6545                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6546            "should only occur in error-recovery path.");
6547     QualType ReturnType =
6548         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6549             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6550             : Context.DependentTy;
6551     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6552                             Expr::getValueKindForType(ReturnType), RParenLoc,
6553                             CurFPFeatureOverrides());
6554   }
6555   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6556                                ExecConfig, IsExecConfig);
6557 }
6558 
6559 /// Parse a __builtin_astype expression.
6560 ///
6561 /// __builtin_astype( value, dst type )
6562 ///
6563 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6564                                  SourceLocation BuiltinLoc,
6565                                  SourceLocation RParenLoc) {
6566   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6567   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6568 }
6569 
6570 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6571 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6572                                  SourceLocation BuiltinLoc,
6573                                  SourceLocation RParenLoc) {
6574   ExprValueKind VK = VK_RValue;
6575   ExprObjectKind OK = OK_Ordinary;
6576   QualType SrcTy = E->getType();
6577   if (!SrcTy->isDependentType() &&
6578       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6579     return ExprError(
6580         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6581         << DestTy << SrcTy << E->getSourceRange());
6582   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6583 }
6584 
6585 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6586 /// provided arguments.
6587 ///
6588 /// __builtin_convertvector( value, dst type )
6589 ///
6590 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6591                                         SourceLocation BuiltinLoc,
6592                                         SourceLocation RParenLoc) {
6593   TypeSourceInfo *TInfo;
6594   GetTypeFromParser(ParsedDestTy, &TInfo);
6595   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6596 }
6597 
6598 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6599 /// i.e. an expression not of \p OverloadTy.  The expression should
6600 /// unary-convert to an expression of function-pointer or
6601 /// block-pointer type.
6602 ///
6603 /// \param NDecl the declaration being called, if available
6604 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6605                                        SourceLocation LParenLoc,
6606                                        ArrayRef<Expr *> Args,
6607                                        SourceLocation RParenLoc, Expr *Config,
6608                                        bool IsExecConfig, ADLCallKind UsesADL) {
6609   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6610   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6611 
6612   // Functions with 'interrupt' attribute cannot be called directly.
6613   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6614     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6615     return ExprError();
6616   }
6617 
6618   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6619   // so there's some risk when calling out to non-interrupt handler functions
6620   // that the callee might not preserve them. This is easy to diagnose here,
6621   // but can be very challenging to debug.
6622   // Likewise, X86 interrupt handlers may only call routines with attribute
6623   // no_caller_saved_registers since there is no efficient way to
6624   // save and restore the non-GPR state.
6625   if (auto *Caller = getCurFunctionDecl()) {
6626     if (Caller->hasAttr<ARMInterruptAttr>()) {
6627       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6628       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6629         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6630         if (FDecl)
6631           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6632       }
6633     }
6634     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6635         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6636       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6637       if (FDecl)
6638         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6639     }
6640   }
6641 
6642   // Promote the function operand.
6643   // We special-case function promotion here because we only allow promoting
6644   // builtin functions to function pointers in the callee of a call.
6645   ExprResult Result;
6646   QualType ResultTy;
6647   if (BuiltinID &&
6648       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6649     // Extract the return type from the (builtin) function pointer type.
6650     // FIXME Several builtins still have setType in
6651     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6652     // Builtins.def to ensure they are correct before removing setType calls.
6653     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6654     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6655     ResultTy = FDecl->getCallResultType();
6656   } else {
6657     Result = CallExprUnaryConversions(Fn);
6658     ResultTy = Context.BoolTy;
6659   }
6660   if (Result.isInvalid())
6661     return ExprError();
6662   Fn = Result.get();
6663 
6664   // Check for a valid function type, but only if it is not a builtin which
6665   // requires custom type checking. These will be handled by
6666   // CheckBuiltinFunctionCall below just after creation of the call expression.
6667   const FunctionType *FuncT = nullptr;
6668   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6669   retry:
6670     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6671       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6672       // have type pointer to function".
6673       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6674       if (!FuncT)
6675         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6676                          << Fn->getType() << Fn->getSourceRange());
6677     } else if (const BlockPointerType *BPT =
6678                    Fn->getType()->getAs<BlockPointerType>()) {
6679       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6680     } else {
6681       // Handle calls to expressions of unknown-any type.
6682       if (Fn->getType() == Context.UnknownAnyTy) {
6683         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6684         if (rewrite.isInvalid())
6685           return ExprError();
6686         Fn = rewrite.get();
6687         goto retry;
6688       }
6689 
6690       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6691                        << Fn->getType() << Fn->getSourceRange());
6692     }
6693   }
6694 
6695   // Get the number of parameters in the function prototype, if any.
6696   // We will allocate space for max(Args.size(), NumParams) arguments
6697   // in the call expression.
6698   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6699   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6700 
6701   CallExpr *TheCall;
6702   if (Config) {
6703     assert(UsesADL == ADLCallKind::NotADL &&
6704            "CUDAKernelCallExpr should not use ADL");
6705     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6706                                          Args, ResultTy, VK_RValue, RParenLoc,
6707                                          CurFPFeatureOverrides(), NumParams);
6708   } else {
6709     TheCall =
6710         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6711                          CurFPFeatureOverrides(), NumParams, UsesADL);
6712   }
6713 
6714   if (!Context.isDependenceAllowed()) {
6715     // Forget about the nulled arguments since typo correction
6716     // do not handle them well.
6717     TheCall->shrinkNumArgs(Args.size());
6718     // C cannot always handle TypoExpr nodes in builtin calls and direct
6719     // function calls as their argument checking don't necessarily handle
6720     // dependent types properly, so make sure any TypoExprs have been
6721     // dealt with.
6722     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6723     if (!Result.isUsable()) return ExprError();
6724     CallExpr *TheOldCall = TheCall;
6725     TheCall = dyn_cast<CallExpr>(Result.get());
6726     bool CorrectedTypos = TheCall != TheOldCall;
6727     if (!TheCall) return Result;
6728     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6729 
6730     // A new call expression node was created if some typos were corrected.
6731     // However it may not have been constructed with enough storage. In this
6732     // case, rebuild the node with enough storage. The waste of space is
6733     // immaterial since this only happens when some typos were corrected.
6734     if (CorrectedTypos && Args.size() < NumParams) {
6735       if (Config)
6736         TheCall = CUDAKernelCallExpr::Create(
6737             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6738             RParenLoc, CurFPFeatureOverrides(), NumParams);
6739       else
6740         TheCall =
6741             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6742                              CurFPFeatureOverrides(), NumParams, UsesADL);
6743     }
6744     // We can now handle the nulled arguments for the default arguments.
6745     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6746   }
6747 
6748   // Bail out early if calling a builtin with custom type checking.
6749   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6750     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6751 
6752   if (getLangOpts().CUDA) {
6753     if (Config) {
6754       // CUDA: Kernel calls must be to global functions
6755       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6756         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6757             << FDecl << Fn->getSourceRange());
6758 
6759       // CUDA: Kernel function must have 'void' return type
6760       if (!FuncT->getReturnType()->isVoidType() &&
6761           !FuncT->getReturnType()->getAs<AutoType>() &&
6762           !FuncT->getReturnType()->isInstantiationDependentType())
6763         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6764             << Fn->getType() << Fn->getSourceRange());
6765     } else {
6766       // CUDA: Calls to global functions must be configured
6767       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6768         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6769             << FDecl << Fn->getSourceRange());
6770     }
6771   }
6772 
6773   // Check for a valid return type
6774   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6775                           FDecl))
6776     return ExprError();
6777 
6778   // We know the result type of the call, set it.
6779   TheCall->setType(FuncT->getCallResultType(Context));
6780   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6781 
6782   if (Proto) {
6783     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6784                                 IsExecConfig))
6785       return ExprError();
6786   } else {
6787     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6788 
6789     if (FDecl) {
6790       // Check if we have too few/too many template arguments, based
6791       // on our knowledge of the function definition.
6792       const FunctionDecl *Def = nullptr;
6793       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6794         Proto = Def->getType()->getAs<FunctionProtoType>();
6795        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6796           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6797           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6798       }
6799 
6800       // If the function we're calling isn't a function prototype, but we have
6801       // a function prototype from a prior declaratiom, use that prototype.
6802       if (!FDecl->hasPrototype())
6803         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6804     }
6805 
6806     // Promote the arguments (C99 6.5.2.2p6).
6807     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6808       Expr *Arg = Args[i];
6809 
6810       if (Proto && i < Proto->getNumParams()) {
6811         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6812             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6813         ExprResult ArgE =
6814             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6815         if (ArgE.isInvalid())
6816           return true;
6817 
6818         Arg = ArgE.getAs<Expr>();
6819 
6820       } else {
6821         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6822 
6823         if (ArgE.isInvalid())
6824           return true;
6825 
6826         Arg = ArgE.getAs<Expr>();
6827       }
6828 
6829       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6830                               diag::err_call_incomplete_argument, Arg))
6831         return ExprError();
6832 
6833       TheCall->setArg(i, Arg);
6834     }
6835   }
6836 
6837   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6838     if (!Method->isStatic())
6839       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6840         << Fn->getSourceRange());
6841 
6842   // Check for sentinels
6843   if (NDecl)
6844     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6845 
6846   // Warn for unions passing across security boundary (CMSE).
6847   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6848     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6849       if (const auto *RT =
6850               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6851         if (RT->getDecl()->isOrContainsUnion())
6852           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6853               << 0 << i;
6854       }
6855     }
6856   }
6857 
6858   // Do special checking on direct calls to functions.
6859   if (FDecl) {
6860     if (CheckFunctionCall(FDecl, TheCall, Proto))
6861       return ExprError();
6862 
6863     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6864 
6865     if (BuiltinID)
6866       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6867   } else if (NDecl) {
6868     if (CheckPointerCall(NDecl, TheCall, Proto))
6869       return ExprError();
6870   } else {
6871     if (CheckOtherCall(TheCall, Proto))
6872       return ExprError();
6873   }
6874 
6875   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6876 }
6877 
6878 ExprResult
6879 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6880                            SourceLocation RParenLoc, Expr *InitExpr) {
6881   assert(Ty && "ActOnCompoundLiteral(): missing type");
6882   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6883 
6884   TypeSourceInfo *TInfo;
6885   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6886   if (!TInfo)
6887     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6888 
6889   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6890 }
6891 
6892 ExprResult
6893 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6894                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6895   QualType literalType = TInfo->getType();
6896 
6897   if (literalType->isArrayType()) {
6898     if (RequireCompleteSizedType(
6899             LParenLoc, Context.getBaseElementType(literalType),
6900             diag::err_array_incomplete_or_sizeless_type,
6901             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6902       return ExprError();
6903     if (literalType->isVariableArrayType()) {
6904       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6905                                            diag::err_variable_object_no_init)) {
6906         return ExprError();
6907       }
6908     }
6909   } else if (!literalType->isDependentType() &&
6910              RequireCompleteType(LParenLoc, literalType,
6911                diag::err_typecheck_decl_incomplete_type,
6912                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6913     return ExprError();
6914 
6915   InitializedEntity Entity
6916     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6917   InitializationKind Kind
6918     = InitializationKind::CreateCStyleCast(LParenLoc,
6919                                            SourceRange(LParenLoc, RParenLoc),
6920                                            /*InitList=*/true);
6921   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6922   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6923                                       &literalType);
6924   if (Result.isInvalid())
6925     return ExprError();
6926   LiteralExpr = Result.get();
6927 
6928   bool isFileScope = !CurContext->isFunctionOrMethod();
6929 
6930   // In C, compound literals are l-values for some reason.
6931   // For GCC compatibility, in C++, file-scope array compound literals with
6932   // constant initializers are also l-values, and compound literals are
6933   // otherwise prvalues.
6934   //
6935   // (GCC also treats C++ list-initialized file-scope array prvalues with
6936   // constant initializers as l-values, but that's non-conforming, so we don't
6937   // follow it there.)
6938   //
6939   // FIXME: It would be better to handle the lvalue cases as materializing and
6940   // lifetime-extending a temporary object, but our materialized temporaries
6941   // representation only supports lifetime extension from a variable, not "out
6942   // of thin air".
6943   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6944   // is bound to the result of applying array-to-pointer decay to the compound
6945   // literal.
6946   // FIXME: GCC supports compound literals of reference type, which should
6947   // obviously have a value kind derived from the kind of reference involved.
6948   ExprValueKind VK =
6949       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6950           ? VK_RValue
6951           : VK_LValue;
6952 
6953   if (isFileScope)
6954     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6955       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6956         Expr *Init = ILE->getInit(i);
6957         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6958       }
6959 
6960   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6961                                               VK, LiteralExpr, isFileScope);
6962   if (isFileScope) {
6963     if (!LiteralExpr->isTypeDependent() &&
6964         !LiteralExpr->isValueDependent() &&
6965         !literalType->isDependentType()) // C99 6.5.2.5p3
6966       if (CheckForConstantInitializer(LiteralExpr, literalType))
6967         return ExprError();
6968   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6969              literalType.getAddressSpace() != LangAS::Default) {
6970     // Embedded-C extensions to C99 6.5.2.5:
6971     //   "If the compound literal occurs inside the body of a function, the
6972     //   type name shall not be qualified by an address-space qualifier."
6973     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6974       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6975     return ExprError();
6976   }
6977 
6978   if (!isFileScope && !getLangOpts().CPlusPlus) {
6979     // Compound literals that have automatic storage duration are destroyed at
6980     // the end of the scope in C; in C++, they're just temporaries.
6981 
6982     // Emit diagnostics if it is or contains a C union type that is non-trivial
6983     // to destruct.
6984     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6985       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6986                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6987 
6988     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6989     if (literalType.isDestructedType()) {
6990       Cleanup.setExprNeedsCleanups(true);
6991       ExprCleanupObjects.push_back(E);
6992       getCurFunction()->setHasBranchProtectedScope();
6993     }
6994   }
6995 
6996   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6997       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6998     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6999                                        E->getInitializer()->getExprLoc());
7000 
7001   return MaybeBindToTemporary(E);
7002 }
7003 
7004 ExprResult
7005 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7006                     SourceLocation RBraceLoc) {
7007   // Only produce each kind of designated initialization diagnostic once.
7008   SourceLocation FirstDesignator;
7009   bool DiagnosedArrayDesignator = false;
7010   bool DiagnosedNestedDesignator = false;
7011   bool DiagnosedMixedDesignator = false;
7012 
7013   // Check that any designated initializers are syntactically valid in the
7014   // current language mode.
7015   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7016     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7017       if (FirstDesignator.isInvalid())
7018         FirstDesignator = DIE->getBeginLoc();
7019 
7020       if (!getLangOpts().CPlusPlus)
7021         break;
7022 
7023       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7024         DiagnosedNestedDesignator = true;
7025         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7026           << DIE->getDesignatorsSourceRange();
7027       }
7028 
7029       for (auto &Desig : DIE->designators()) {
7030         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7031           DiagnosedArrayDesignator = true;
7032           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7033             << Desig.getSourceRange();
7034         }
7035       }
7036 
7037       if (!DiagnosedMixedDesignator &&
7038           !isa<DesignatedInitExpr>(InitArgList[0])) {
7039         DiagnosedMixedDesignator = true;
7040         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7041           << DIE->getSourceRange();
7042         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7043           << InitArgList[0]->getSourceRange();
7044       }
7045     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7046                isa<DesignatedInitExpr>(InitArgList[0])) {
7047       DiagnosedMixedDesignator = true;
7048       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7049       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7050         << DIE->getSourceRange();
7051       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7052         << InitArgList[I]->getSourceRange();
7053     }
7054   }
7055 
7056   if (FirstDesignator.isValid()) {
7057     // Only diagnose designated initiaization as a C++20 extension if we didn't
7058     // already diagnose use of (non-C++20) C99 designator syntax.
7059     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7060         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7061       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7062                                 ? diag::warn_cxx17_compat_designated_init
7063                                 : diag::ext_cxx_designated_init);
7064     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7065       Diag(FirstDesignator, diag::ext_designated_init);
7066     }
7067   }
7068 
7069   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7070 }
7071 
7072 ExprResult
7073 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7074                     SourceLocation RBraceLoc) {
7075   // Semantic analysis for initializers is done by ActOnDeclarator() and
7076   // CheckInitializer() - it requires knowledge of the object being initialized.
7077 
7078   // Immediately handle non-overload placeholders.  Overloads can be
7079   // resolved contextually, but everything else here can't.
7080   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7081     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7082       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7083 
7084       // Ignore failures; dropping the entire initializer list because
7085       // of one failure would be terrible for indexing/etc.
7086       if (result.isInvalid()) continue;
7087 
7088       InitArgList[I] = result.get();
7089     }
7090   }
7091 
7092   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7093                                                RBraceLoc);
7094   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7095   return E;
7096 }
7097 
7098 /// Do an explicit extend of the given block pointer if we're in ARC.
7099 void Sema::maybeExtendBlockObject(ExprResult &E) {
7100   assert(E.get()->getType()->isBlockPointerType());
7101   assert(E.get()->isRValue());
7102 
7103   // Only do this in an r-value context.
7104   if (!getLangOpts().ObjCAutoRefCount) return;
7105 
7106   E = ImplicitCastExpr::Create(
7107       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7108       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7109   Cleanup.setExprNeedsCleanups(true);
7110 }
7111 
7112 /// Prepare a conversion of the given expression to an ObjC object
7113 /// pointer type.
7114 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7115   QualType type = E.get()->getType();
7116   if (type->isObjCObjectPointerType()) {
7117     return CK_BitCast;
7118   } else if (type->isBlockPointerType()) {
7119     maybeExtendBlockObject(E);
7120     return CK_BlockPointerToObjCPointerCast;
7121   } else {
7122     assert(type->isPointerType());
7123     return CK_CPointerToObjCPointerCast;
7124   }
7125 }
7126 
7127 /// Prepares for a scalar cast, performing all the necessary stages
7128 /// except the final cast and returning the kind required.
7129 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7130   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7131   // Also, callers should have filtered out the invalid cases with
7132   // pointers.  Everything else should be possible.
7133 
7134   QualType SrcTy = Src.get()->getType();
7135   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7136     return CK_NoOp;
7137 
7138   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7139   case Type::STK_MemberPointer:
7140     llvm_unreachable("member pointer type in C");
7141 
7142   case Type::STK_CPointer:
7143   case Type::STK_BlockPointer:
7144   case Type::STK_ObjCObjectPointer:
7145     switch (DestTy->getScalarTypeKind()) {
7146     case Type::STK_CPointer: {
7147       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7148       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7149       if (SrcAS != DestAS)
7150         return CK_AddressSpaceConversion;
7151       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7152         return CK_NoOp;
7153       return CK_BitCast;
7154     }
7155     case Type::STK_BlockPointer:
7156       return (SrcKind == Type::STK_BlockPointer
7157                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7158     case Type::STK_ObjCObjectPointer:
7159       if (SrcKind == Type::STK_ObjCObjectPointer)
7160         return CK_BitCast;
7161       if (SrcKind == Type::STK_CPointer)
7162         return CK_CPointerToObjCPointerCast;
7163       maybeExtendBlockObject(Src);
7164       return CK_BlockPointerToObjCPointerCast;
7165     case Type::STK_Bool:
7166       return CK_PointerToBoolean;
7167     case Type::STK_Integral:
7168       return CK_PointerToIntegral;
7169     case Type::STK_Floating:
7170     case Type::STK_FloatingComplex:
7171     case Type::STK_IntegralComplex:
7172     case Type::STK_MemberPointer:
7173     case Type::STK_FixedPoint:
7174       llvm_unreachable("illegal cast from pointer");
7175     }
7176     llvm_unreachable("Should have returned before this");
7177 
7178   case Type::STK_FixedPoint:
7179     switch (DestTy->getScalarTypeKind()) {
7180     case Type::STK_FixedPoint:
7181       return CK_FixedPointCast;
7182     case Type::STK_Bool:
7183       return CK_FixedPointToBoolean;
7184     case Type::STK_Integral:
7185       return CK_FixedPointToIntegral;
7186     case Type::STK_Floating:
7187       return CK_FixedPointToFloating;
7188     case Type::STK_IntegralComplex:
7189     case Type::STK_FloatingComplex:
7190       Diag(Src.get()->getExprLoc(),
7191            diag::err_unimplemented_conversion_with_fixed_point_type)
7192           << DestTy;
7193       return CK_IntegralCast;
7194     case Type::STK_CPointer:
7195     case Type::STK_ObjCObjectPointer:
7196     case Type::STK_BlockPointer:
7197     case Type::STK_MemberPointer:
7198       llvm_unreachable("illegal cast to pointer type");
7199     }
7200     llvm_unreachable("Should have returned before this");
7201 
7202   case Type::STK_Bool: // casting from bool is like casting from an integer
7203   case Type::STK_Integral:
7204     switch (DestTy->getScalarTypeKind()) {
7205     case Type::STK_CPointer:
7206     case Type::STK_ObjCObjectPointer:
7207     case Type::STK_BlockPointer:
7208       if (Src.get()->isNullPointerConstant(Context,
7209                                            Expr::NPC_ValueDependentIsNull))
7210         return CK_NullToPointer;
7211       return CK_IntegralToPointer;
7212     case Type::STK_Bool:
7213       return CK_IntegralToBoolean;
7214     case Type::STK_Integral:
7215       return CK_IntegralCast;
7216     case Type::STK_Floating:
7217       return CK_IntegralToFloating;
7218     case Type::STK_IntegralComplex:
7219       Src = ImpCastExprToType(Src.get(),
7220                       DestTy->castAs<ComplexType>()->getElementType(),
7221                       CK_IntegralCast);
7222       return CK_IntegralRealToComplex;
7223     case Type::STK_FloatingComplex:
7224       Src = ImpCastExprToType(Src.get(),
7225                       DestTy->castAs<ComplexType>()->getElementType(),
7226                       CK_IntegralToFloating);
7227       return CK_FloatingRealToComplex;
7228     case Type::STK_MemberPointer:
7229       llvm_unreachable("member pointer type in C");
7230     case Type::STK_FixedPoint:
7231       return CK_IntegralToFixedPoint;
7232     }
7233     llvm_unreachable("Should have returned before this");
7234 
7235   case Type::STK_Floating:
7236     switch (DestTy->getScalarTypeKind()) {
7237     case Type::STK_Floating:
7238       return CK_FloatingCast;
7239     case Type::STK_Bool:
7240       return CK_FloatingToBoolean;
7241     case Type::STK_Integral:
7242       return CK_FloatingToIntegral;
7243     case Type::STK_FloatingComplex:
7244       Src = ImpCastExprToType(Src.get(),
7245                               DestTy->castAs<ComplexType>()->getElementType(),
7246                               CK_FloatingCast);
7247       return CK_FloatingRealToComplex;
7248     case Type::STK_IntegralComplex:
7249       Src = ImpCastExprToType(Src.get(),
7250                               DestTy->castAs<ComplexType>()->getElementType(),
7251                               CK_FloatingToIntegral);
7252       return CK_IntegralRealToComplex;
7253     case Type::STK_CPointer:
7254     case Type::STK_ObjCObjectPointer:
7255     case Type::STK_BlockPointer:
7256       llvm_unreachable("valid float->pointer cast?");
7257     case Type::STK_MemberPointer:
7258       llvm_unreachable("member pointer type in C");
7259     case Type::STK_FixedPoint:
7260       return CK_FloatingToFixedPoint;
7261     }
7262     llvm_unreachable("Should have returned before this");
7263 
7264   case Type::STK_FloatingComplex:
7265     switch (DestTy->getScalarTypeKind()) {
7266     case Type::STK_FloatingComplex:
7267       return CK_FloatingComplexCast;
7268     case Type::STK_IntegralComplex:
7269       return CK_FloatingComplexToIntegralComplex;
7270     case Type::STK_Floating: {
7271       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7272       if (Context.hasSameType(ET, DestTy))
7273         return CK_FloatingComplexToReal;
7274       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7275       return CK_FloatingCast;
7276     }
7277     case Type::STK_Bool:
7278       return CK_FloatingComplexToBoolean;
7279     case Type::STK_Integral:
7280       Src = ImpCastExprToType(Src.get(),
7281                               SrcTy->castAs<ComplexType>()->getElementType(),
7282                               CK_FloatingComplexToReal);
7283       return CK_FloatingToIntegral;
7284     case Type::STK_CPointer:
7285     case Type::STK_ObjCObjectPointer:
7286     case Type::STK_BlockPointer:
7287       llvm_unreachable("valid complex float->pointer cast?");
7288     case Type::STK_MemberPointer:
7289       llvm_unreachable("member pointer type in C");
7290     case Type::STK_FixedPoint:
7291       Diag(Src.get()->getExprLoc(),
7292            diag::err_unimplemented_conversion_with_fixed_point_type)
7293           << SrcTy;
7294       return CK_IntegralCast;
7295     }
7296     llvm_unreachable("Should have returned before this");
7297 
7298   case Type::STK_IntegralComplex:
7299     switch (DestTy->getScalarTypeKind()) {
7300     case Type::STK_FloatingComplex:
7301       return CK_IntegralComplexToFloatingComplex;
7302     case Type::STK_IntegralComplex:
7303       return CK_IntegralComplexCast;
7304     case Type::STK_Integral: {
7305       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7306       if (Context.hasSameType(ET, DestTy))
7307         return CK_IntegralComplexToReal;
7308       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7309       return CK_IntegralCast;
7310     }
7311     case Type::STK_Bool:
7312       return CK_IntegralComplexToBoolean;
7313     case Type::STK_Floating:
7314       Src = ImpCastExprToType(Src.get(),
7315                               SrcTy->castAs<ComplexType>()->getElementType(),
7316                               CK_IntegralComplexToReal);
7317       return CK_IntegralToFloating;
7318     case Type::STK_CPointer:
7319     case Type::STK_ObjCObjectPointer:
7320     case Type::STK_BlockPointer:
7321       llvm_unreachable("valid complex int->pointer cast?");
7322     case Type::STK_MemberPointer:
7323       llvm_unreachable("member pointer type in C");
7324     case Type::STK_FixedPoint:
7325       Diag(Src.get()->getExprLoc(),
7326            diag::err_unimplemented_conversion_with_fixed_point_type)
7327           << SrcTy;
7328       return CK_IntegralCast;
7329     }
7330     llvm_unreachable("Should have returned before this");
7331   }
7332 
7333   llvm_unreachable("Unhandled scalar cast");
7334 }
7335 
7336 static bool breakDownVectorType(QualType type, uint64_t &len,
7337                                 QualType &eltType) {
7338   // Vectors are simple.
7339   if (const VectorType *vecType = type->getAs<VectorType>()) {
7340     len = vecType->getNumElements();
7341     eltType = vecType->getElementType();
7342     assert(eltType->isScalarType());
7343     return true;
7344   }
7345 
7346   // We allow lax conversion to and from non-vector types, but only if
7347   // they're real types (i.e. non-complex, non-pointer scalar types).
7348   if (!type->isRealType()) return false;
7349 
7350   len = 1;
7351   eltType = type;
7352   return true;
7353 }
7354 
7355 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7356 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7357 /// allowed?
7358 ///
7359 /// This will also return false if the two given types do not make sense from
7360 /// the perspective of SVE bitcasts.
7361 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7362   assert(srcTy->isVectorType() || destTy->isVectorType());
7363 
7364   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7365     if (!FirstType->isSizelessBuiltinType())
7366       return false;
7367 
7368     const auto *VecTy = SecondType->getAs<VectorType>();
7369     return VecTy &&
7370            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7371   };
7372 
7373   return ValidScalableConversion(srcTy, destTy) ||
7374          ValidScalableConversion(destTy, srcTy);
7375 }
7376 
7377 /// Are the two types matrix types and do they have the same dimensions i.e.
7378 /// do they have the same number of rows and the same number of columns?
7379 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7380   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7381     return false;
7382 
7383   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7384   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7385 
7386   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7387          matSrcType->getNumColumns() == matDestType->getNumColumns();
7388 }
7389 
7390 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7391   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7392 
7393   uint64_t SrcLen, DestLen;
7394   QualType SrcEltTy, DestEltTy;
7395   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7396     return false;
7397   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7398     return false;
7399 
7400   // ASTContext::getTypeSize will return the size rounded up to a
7401   // power of 2, so instead of using that, we need to use the raw
7402   // element size multiplied by the element count.
7403   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7404   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7405 
7406   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7407 }
7408 
7409 /// Are the two types lax-compatible vector types?  That is, given
7410 /// that one of them is a vector, do they have equal storage sizes,
7411 /// where the storage size is the number of elements times the element
7412 /// size?
7413 ///
7414 /// This will also return false if either of the types is neither a
7415 /// vector nor a real type.
7416 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7417   assert(destTy->isVectorType() || srcTy->isVectorType());
7418 
7419   // Disallow lax conversions between scalars and ExtVectors (these
7420   // conversions are allowed for other vector types because common headers
7421   // depend on them).  Most scalar OP ExtVector cases are handled by the
7422   // splat path anyway, which does what we want (convert, not bitcast).
7423   // What this rules out for ExtVectors is crazy things like char4*float.
7424   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7425   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7426 
7427   return areVectorTypesSameSize(srcTy, destTy);
7428 }
7429 
7430 /// Is this a legal conversion between two types, one of which is
7431 /// known to be a vector type?
7432 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7433   assert(destTy->isVectorType() || srcTy->isVectorType());
7434 
7435   switch (Context.getLangOpts().getLaxVectorConversions()) {
7436   case LangOptions::LaxVectorConversionKind::None:
7437     return false;
7438 
7439   case LangOptions::LaxVectorConversionKind::Integer:
7440     if (!srcTy->isIntegralOrEnumerationType()) {
7441       auto *Vec = srcTy->getAs<VectorType>();
7442       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7443         return false;
7444     }
7445     if (!destTy->isIntegralOrEnumerationType()) {
7446       auto *Vec = destTy->getAs<VectorType>();
7447       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7448         return false;
7449     }
7450     // OK, integer (vector) -> integer (vector) bitcast.
7451     break;
7452 
7453     case LangOptions::LaxVectorConversionKind::All:
7454     break;
7455   }
7456 
7457   return areLaxCompatibleVectorTypes(srcTy, destTy);
7458 }
7459 
7460 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7461                            CastKind &Kind) {
7462   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7463     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7464       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7465              << DestTy << SrcTy << R;
7466     }
7467   } else if (SrcTy->isMatrixType()) {
7468     return Diag(R.getBegin(),
7469                 diag::err_invalid_conversion_between_matrix_and_type)
7470            << SrcTy << DestTy << R;
7471   } else if (DestTy->isMatrixType()) {
7472     return Diag(R.getBegin(),
7473                 diag::err_invalid_conversion_between_matrix_and_type)
7474            << DestTy << SrcTy << R;
7475   }
7476 
7477   Kind = CK_MatrixCast;
7478   return false;
7479 }
7480 
7481 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7482                            CastKind &Kind) {
7483   assert(VectorTy->isVectorType() && "Not a vector type!");
7484 
7485   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7486     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7487       return Diag(R.getBegin(),
7488                   Ty->isVectorType() ?
7489                   diag::err_invalid_conversion_between_vectors :
7490                   diag::err_invalid_conversion_between_vector_and_integer)
7491         << VectorTy << Ty << R;
7492   } else
7493     return Diag(R.getBegin(),
7494                 diag::err_invalid_conversion_between_vector_and_scalar)
7495       << VectorTy << Ty << R;
7496 
7497   Kind = CK_BitCast;
7498   return false;
7499 }
7500 
7501 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7502   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7503 
7504   if (DestElemTy == SplattedExpr->getType())
7505     return SplattedExpr;
7506 
7507   assert(DestElemTy->isFloatingType() ||
7508          DestElemTy->isIntegralOrEnumerationType());
7509 
7510   CastKind CK;
7511   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7512     // OpenCL requires that we convert `true` boolean expressions to -1, but
7513     // only when splatting vectors.
7514     if (DestElemTy->isFloatingType()) {
7515       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7516       // in two steps: boolean to signed integral, then to floating.
7517       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7518                                                  CK_BooleanToSignedIntegral);
7519       SplattedExpr = CastExprRes.get();
7520       CK = CK_IntegralToFloating;
7521     } else {
7522       CK = CK_BooleanToSignedIntegral;
7523     }
7524   } else {
7525     ExprResult CastExprRes = SplattedExpr;
7526     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7527     if (CastExprRes.isInvalid())
7528       return ExprError();
7529     SplattedExpr = CastExprRes.get();
7530   }
7531   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7532 }
7533 
7534 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7535                                     Expr *CastExpr, CastKind &Kind) {
7536   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7537 
7538   QualType SrcTy = CastExpr->getType();
7539 
7540   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7541   // an ExtVectorType.
7542   // In OpenCL, casts between vectors of different types are not allowed.
7543   // (See OpenCL 6.2).
7544   if (SrcTy->isVectorType()) {
7545     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7546         (getLangOpts().OpenCL &&
7547          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7548       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7549         << DestTy << SrcTy << R;
7550       return ExprError();
7551     }
7552     Kind = CK_BitCast;
7553     return CastExpr;
7554   }
7555 
7556   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7557   // conversion will take place first from scalar to elt type, and then
7558   // splat from elt type to vector.
7559   if (SrcTy->isPointerType())
7560     return Diag(R.getBegin(),
7561                 diag::err_invalid_conversion_between_vector_and_scalar)
7562       << DestTy << SrcTy << R;
7563 
7564   Kind = CK_VectorSplat;
7565   return prepareVectorSplat(DestTy, CastExpr);
7566 }
7567 
7568 ExprResult
7569 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7570                     Declarator &D, ParsedType &Ty,
7571                     SourceLocation RParenLoc, Expr *CastExpr) {
7572   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7573          "ActOnCastExpr(): missing type or expr");
7574 
7575   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7576   if (D.isInvalidType())
7577     return ExprError();
7578 
7579   if (getLangOpts().CPlusPlus) {
7580     // Check that there are no default arguments (C++ only).
7581     CheckExtraCXXDefaultArguments(D);
7582   } else {
7583     // Make sure any TypoExprs have been dealt with.
7584     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7585     if (!Res.isUsable())
7586       return ExprError();
7587     CastExpr = Res.get();
7588   }
7589 
7590   checkUnusedDeclAttributes(D);
7591 
7592   QualType castType = castTInfo->getType();
7593   Ty = CreateParsedType(castType, castTInfo);
7594 
7595   bool isVectorLiteral = false;
7596 
7597   // Check for an altivec or OpenCL literal,
7598   // i.e. all the elements are integer constants.
7599   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7600   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7601   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7602        && castType->isVectorType() && (PE || PLE)) {
7603     if (PLE && PLE->getNumExprs() == 0) {
7604       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7605       return ExprError();
7606     }
7607     if (PE || PLE->getNumExprs() == 1) {
7608       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7609       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7610         isVectorLiteral = true;
7611     }
7612     else
7613       isVectorLiteral = true;
7614   }
7615 
7616   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7617   // then handle it as such.
7618   if (isVectorLiteral)
7619     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7620 
7621   // If the Expr being casted is a ParenListExpr, handle it specially.
7622   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7623   // sequence of BinOp comma operators.
7624   if (isa<ParenListExpr>(CastExpr)) {
7625     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7626     if (Result.isInvalid()) return ExprError();
7627     CastExpr = Result.get();
7628   }
7629 
7630   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7631       !getSourceManager().isInSystemMacro(LParenLoc))
7632     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7633 
7634   CheckTollFreeBridgeCast(castType, CastExpr);
7635 
7636   CheckObjCBridgeRelatedCast(castType, CastExpr);
7637 
7638   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7639 
7640   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7641 }
7642 
7643 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7644                                     SourceLocation RParenLoc, Expr *E,
7645                                     TypeSourceInfo *TInfo) {
7646   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7647          "Expected paren or paren list expression");
7648 
7649   Expr **exprs;
7650   unsigned numExprs;
7651   Expr *subExpr;
7652   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7653   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7654     LiteralLParenLoc = PE->getLParenLoc();
7655     LiteralRParenLoc = PE->getRParenLoc();
7656     exprs = PE->getExprs();
7657     numExprs = PE->getNumExprs();
7658   } else { // isa<ParenExpr> by assertion at function entrance
7659     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7660     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7661     subExpr = cast<ParenExpr>(E)->getSubExpr();
7662     exprs = &subExpr;
7663     numExprs = 1;
7664   }
7665 
7666   QualType Ty = TInfo->getType();
7667   assert(Ty->isVectorType() && "Expected vector type");
7668 
7669   SmallVector<Expr *, 8> initExprs;
7670   const VectorType *VTy = Ty->castAs<VectorType>();
7671   unsigned numElems = VTy->getNumElements();
7672 
7673   // '(...)' form of vector initialization in AltiVec: the number of
7674   // initializers must be one or must match the size of the vector.
7675   // If a single value is specified in the initializer then it will be
7676   // replicated to all the components of the vector
7677   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7678     // The number of initializers must be one or must match the size of the
7679     // vector. If a single value is specified in the initializer then it will
7680     // be replicated to all the components of the vector
7681     if (numExprs == 1) {
7682       QualType ElemTy = VTy->getElementType();
7683       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7684       if (Literal.isInvalid())
7685         return ExprError();
7686       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7687                                   PrepareScalarCast(Literal, ElemTy));
7688       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7689     }
7690     else if (numExprs < numElems) {
7691       Diag(E->getExprLoc(),
7692            diag::err_incorrect_number_of_vector_initializers);
7693       return ExprError();
7694     }
7695     else
7696       initExprs.append(exprs, exprs + numExprs);
7697   }
7698   else {
7699     // For OpenCL, when the number of initializers is a single value,
7700     // it will be replicated to all components of the vector.
7701     if (getLangOpts().OpenCL &&
7702         VTy->getVectorKind() == VectorType::GenericVector &&
7703         numExprs == 1) {
7704         QualType ElemTy = VTy->getElementType();
7705         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7706         if (Literal.isInvalid())
7707           return ExprError();
7708         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7709                                     PrepareScalarCast(Literal, ElemTy));
7710         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7711     }
7712 
7713     initExprs.append(exprs, exprs + numExprs);
7714   }
7715   // FIXME: This means that pretty-printing the final AST will produce curly
7716   // braces instead of the original commas.
7717   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7718                                                    initExprs, LiteralRParenLoc);
7719   initE->setType(Ty);
7720   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7721 }
7722 
7723 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7724 /// the ParenListExpr into a sequence of comma binary operators.
7725 ExprResult
7726 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7727   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7728   if (!E)
7729     return OrigExpr;
7730 
7731   ExprResult Result(E->getExpr(0));
7732 
7733   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7734     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7735                         E->getExpr(i));
7736 
7737   if (Result.isInvalid()) return ExprError();
7738 
7739   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7740 }
7741 
7742 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7743                                     SourceLocation R,
7744                                     MultiExprArg Val) {
7745   return ParenListExpr::Create(Context, L, Val, R);
7746 }
7747 
7748 /// Emit a specialized diagnostic when one expression is a null pointer
7749 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7750 /// emitted.
7751 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7752                                       SourceLocation QuestionLoc) {
7753   Expr *NullExpr = LHSExpr;
7754   Expr *NonPointerExpr = RHSExpr;
7755   Expr::NullPointerConstantKind NullKind =
7756       NullExpr->isNullPointerConstant(Context,
7757                                       Expr::NPC_ValueDependentIsNotNull);
7758 
7759   if (NullKind == Expr::NPCK_NotNull) {
7760     NullExpr = RHSExpr;
7761     NonPointerExpr = LHSExpr;
7762     NullKind =
7763         NullExpr->isNullPointerConstant(Context,
7764                                         Expr::NPC_ValueDependentIsNotNull);
7765   }
7766 
7767   if (NullKind == Expr::NPCK_NotNull)
7768     return false;
7769 
7770   if (NullKind == Expr::NPCK_ZeroExpression)
7771     return false;
7772 
7773   if (NullKind == Expr::NPCK_ZeroLiteral) {
7774     // In this case, check to make sure that we got here from a "NULL"
7775     // string in the source code.
7776     NullExpr = NullExpr->IgnoreParenImpCasts();
7777     SourceLocation loc = NullExpr->getExprLoc();
7778     if (!findMacroSpelling(loc, "NULL"))
7779       return false;
7780   }
7781 
7782   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7783   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7784       << NonPointerExpr->getType() << DiagType
7785       << NonPointerExpr->getSourceRange();
7786   return true;
7787 }
7788 
7789 /// Return false if the condition expression is valid, true otherwise.
7790 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7791   QualType CondTy = Cond->getType();
7792 
7793   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7794   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7795     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7796       << CondTy << Cond->getSourceRange();
7797     return true;
7798   }
7799 
7800   // C99 6.5.15p2
7801   if (CondTy->isScalarType()) return false;
7802 
7803   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7804     << CondTy << Cond->getSourceRange();
7805   return true;
7806 }
7807 
7808 /// Handle when one or both operands are void type.
7809 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7810                                          ExprResult &RHS) {
7811     Expr *LHSExpr = LHS.get();
7812     Expr *RHSExpr = RHS.get();
7813 
7814     if (!LHSExpr->getType()->isVoidType())
7815       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7816           << RHSExpr->getSourceRange();
7817     if (!RHSExpr->getType()->isVoidType())
7818       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7819           << LHSExpr->getSourceRange();
7820     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7821     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7822     return S.Context.VoidTy;
7823 }
7824 
7825 /// Return false if the NullExpr can be promoted to PointerTy,
7826 /// true otherwise.
7827 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7828                                         QualType PointerTy) {
7829   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7830       !NullExpr.get()->isNullPointerConstant(S.Context,
7831                                             Expr::NPC_ValueDependentIsNull))
7832     return true;
7833 
7834   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7835   return false;
7836 }
7837 
7838 /// Checks compatibility between two pointers and return the resulting
7839 /// type.
7840 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7841                                                      ExprResult &RHS,
7842                                                      SourceLocation Loc) {
7843   QualType LHSTy = LHS.get()->getType();
7844   QualType RHSTy = RHS.get()->getType();
7845 
7846   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7847     // Two identical pointers types are always compatible.
7848     return LHSTy;
7849   }
7850 
7851   QualType lhptee, rhptee;
7852 
7853   // Get the pointee types.
7854   bool IsBlockPointer = false;
7855   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7856     lhptee = LHSBTy->getPointeeType();
7857     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7858     IsBlockPointer = true;
7859   } else {
7860     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7861     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7862   }
7863 
7864   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7865   // differently qualified versions of compatible types, the result type is
7866   // a pointer to an appropriately qualified version of the composite
7867   // type.
7868 
7869   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7870   // clause doesn't make sense for our extensions. E.g. address space 2 should
7871   // be incompatible with address space 3: they may live on different devices or
7872   // anything.
7873   Qualifiers lhQual = lhptee.getQualifiers();
7874   Qualifiers rhQual = rhptee.getQualifiers();
7875 
7876   LangAS ResultAddrSpace = LangAS::Default;
7877   LangAS LAddrSpace = lhQual.getAddressSpace();
7878   LangAS RAddrSpace = rhQual.getAddressSpace();
7879 
7880   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7881   // spaces is disallowed.
7882   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7883     ResultAddrSpace = LAddrSpace;
7884   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7885     ResultAddrSpace = RAddrSpace;
7886   else {
7887     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7888         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7889         << RHS.get()->getSourceRange();
7890     return QualType();
7891   }
7892 
7893   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7894   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7895   lhQual.removeCVRQualifiers();
7896   rhQual.removeCVRQualifiers();
7897 
7898   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7899   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7900   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7901   // qual types are compatible iff
7902   //  * corresponded types are compatible
7903   //  * CVR qualifiers are equal
7904   //  * address spaces are equal
7905   // Thus for conditional operator we merge CVR and address space unqualified
7906   // pointees and if there is a composite type we return a pointer to it with
7907   // merged qualifiers.
7908   LHSCastKind =
7909       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7910   RHSCastKind =
7911       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7912   lhQual.removeAddressSpace();
7913   rhQual.removeAddressSpace();
7914 
7915   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7916   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7917 
7918   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7919 
7920   if (CompositeTy.isNull()) {
7921     // In this situation, we assume void* type. No especially good
7922     // reason, but this is what gcc does, and we do have to pick
7923     // to get a consistent AST.
7924     QualType incompatTy;
7925     incompatTy = S.Context.getPointerType(
7926         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7927     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7928     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7929 
7930     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7931     // for casts between types with incompatible address space qualifiers.
7932     // For the following code the compiler produces casts between global and
7933     // local address spaces of the corresponded innermost pointees:
7934     // local int *global *a;
7935     // global int *global *b;
7936     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7937     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7938         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7939         << RHS.get()->getSourceRange();
7940 
7941     return incompatTy;
7942   }
7943 
7944   // The pointer types are compatible.
7945   // In case of OpenCL ResultTy should have the address space qualifier
7946   // which is a superset of address spaces of both the 2nd and the 3rd
7947   // operands of the conditional operator.
7948   QualType ResultTy = [&, ResultAddrSpace]() {
7949     if (S.getLangOpts().OpenCL) {
7950       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7951       CompositeQuals.setAddressSpace(ResultAddrSpace);
7952       return S.Context
7953           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7954           .withCVRQualifiers(MergedCVRQual);
7955     }
7956     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7957   }();
7958   if (IsBlockPointer)
7959     ResultTy = S.Context.getBlockPointerType(ResultTy);
7960   else
7961     ResultTy = S.Context.getPointerType(ResultTy);
7962 
7963   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7964   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7965   return ResultTy;
7966 }
7967 
7968 /// Return the resulting type when the operands are both block pointers.
7969 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7970                                                           ExprResult &LHS,
7971                                                           ExprResult &RHS,
7972                                                           SourceLocation Loc) {
7973   QualType LHSTy = LHS.get()->getType();
7974   QualType RHSTy = RHS.get()->getType();
7975 
7976   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7977     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7978       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7979       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7980       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7981       return destType;
7982     }
7983     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7984       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7985       << RHS.get()->getSourceRange();
7986     return QualType();
7987   }
7988 
7989   // We have 2 block pointer types.
7990   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7991 }
7992 
7993 /// Return the resulting type when the operands are both pointers.
7994 static QualType
7995 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7996                                             ExprResult &RHS,
7997                                             SourceLocation Loc) {
7998   // get the pointer types
7999   QualType LHSTy = LHS.get()->getType();
8000   QualType RHSTy = RHS.get()->getType();
8001 
8002   // get the "pointed to" types
8003   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8004   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8005 
8006   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8007   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8008     // Figure out necessary qualifiers (C99 6.5.15p6)
8009     QualType destPointee
8010       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8011     QualType destType = S.Context.getPointerType(destPointee);
8012     // Add qualifiers if necessary.
8013     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8014     // Promote to void*.
8015     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8016     return destType;
8017   }
8018   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8019     QualType destPointee
8020       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8021     QualType destType = S.Context.getPointerType(destPointee);
8022     // Add qualifiers if necessary.
8023     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8024     // Promote to void*.
8025     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8026     return destType;
8027   }
8028 
8029   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8030 }
8031 
8032 /// Return false if the first expression is not an integer and the second
8033 /// expression is not a pointer, true otherwise.
8034 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8035                                         Expr* PointerExpr, SourceLocation Loc,
8036                                         bool IsIntFirstExpr) {
8037   if (!PointerExpr->getType()->isPointerType() ||
8038       !Int.get()->getType()->isIntegerType())
8039     return false;
8040 
8041   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8042   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8043 
8044   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8045     << Expr1->getType() << Expr2->getType()
8046     << Expr1->getSourceRange() << Expr2->getSourceRange();
8047   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8048                             CK_IntegralToPointer);
8049   return true;
8050 }
8051 
8052 /// Simple conversion between integer and floating point types.
8053 ///
8054 /// Used when handling the OpenCL conditional operator where the
8055 /// condition is a vector while the other operands are scalar.
8056 ///
8057 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8058 /// types are either integer or floating type. Between the two
8059 /// operands, the type with the higher rank is defined as the "result
8060 /// type". The other operand needs to be promoted to the same type. No
8061 /// other type promotion is allowed. We cannot use
8062 /// UsualArithmeticConversions() for this purpose, since it always
8063 /// promotes promotable types.
8064 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8065                                             ExprResult &RHS,
8066                                             SourceLocation QuestionLoc) {
8067   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8068   if (LHS.isInvalid())
8069     return QualType();
8070   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8071   if (RHS.isInvalid())
8072     return QualType();
8073 
8074   // For conversion purposes, we ignore any qualifiers.
8075   // For example, "const float" and "float" are equivalent.
8076   QualType LHSType =
8077     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8078   QualType RHSType =
8079     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8080 
8081   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8082     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8083       << LHSType << LHS.get()->getSourceRange();
8084     return QualType();
8085   }
8086 
8087   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8088     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8089       << RHSType << RHS.get()->getSourceRange();
8090     return QualType();
8091   }
8092 
8093   // If both types are identical, no conversion is needed.
8094   if (LHSType == RHSType)
8095     return LHSType;
8096 
8097   // Now handle "real" floating types (i.e. float, double, long double).
8098   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8099     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8100                                  /*IsCompAssign = */ false);
8101 
8102   // Finally, we have two differing integer types.
8103   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8104   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8105 }
8106 
8107 /// Convert scalar operands to a vector that matches the
8108 ///        condition in length.
8109 ///
8110 /// Used when handling the OpenCL conditional operator where the
8111 /// condition is a vector while the other operands are scalar.
8112 ///
8113 /// We first compute the "result type" for the scalar operands
8114 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8115 /// into a vector of that type where the length matches the condition
8116 /// vector type. s6.11.6 requires that the element types of the result
8117 /// and the condition must have the same number of bits.
8118 static QualType
8119 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8120                               QualType CondTy, SourceLocation QuestionLoc) {
8121   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8122   if (ResTy.isNull()) return QualType();
8123 
8124   const VectorType *CV = CondTy->getAs<VectorType>();
8125   assert(CV);
8126 
8127   // Determine the vector result type
8128   unsigned NumElements = CV->getNumElements();
8129   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8130 
8131   // Ensure that all types have the same number of bits
8132   if (S.Context.getTypeSize(CV->getElementType())
8133       != S.Context.getTypeSize(ResTy)) {
8134     // Since VectorTy is created internally, it does not pretty print
8135     // with an OpenCL name. Instead, we just print a description.
8136     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8137     SmallString<64> Str;
8138     llvm::raw_svector_ostream OS(Str);
8139     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8140     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8141       << CondTy << OS.str();
8142     return QualType();
8143   }
8144 
8145   // Convert operands to the vector result type
8146   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8147   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8148 
8149   return VectorTy;
8150 }
8151 
8152 /// Return false if this is a valid OpenCL condition vector
8153 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8154                                        SourceLocation QuestionLoc) {
8155   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8156   // integral type.
8157   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8158   assert(CondTy);
8159   QualType EleTy = CondTy->getElementType();
8160   if (EleTy->isIntegerType()) return false;
8161 
8162   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8163     << Cond->getType() << Cond->getSourceRange();
8164   return true;
8165 }
8166 
8167 /// Return false if the vector condition type and the vector
8168 ///        result type are compatible.
8169 ///
8170 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8171 /// number of elements, and their element types have the same number
8172 /// of bits.
8173 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8174                               SourceLocation QuestionLoc) {
8175   const VectorType *CV = CondTy->getAs<VectorType>();
8176   const VectorType *RV = VecResTy->getAs<VectorType>();
8177   assert(CV && RV);
8178 
8179   if (CV->getNumElements() != RV->getNumElements()) {
8180     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8181       << CondTy << VecResTy;
8182     return true;
8183   }
8184 
8185   QualType CVE = CV->getElementType();
8186   QualType RVE = RV->getElementType();
8187 
8188   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8189     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8190       << CondTy << VecResTy;
8191     return true;
8192   }
8193 
8194   return false;
8195 }
8196 
8197 /// Return the resulting type for the conditional operator in
8198 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8199 ///        s6.3.i) when the condition is a vector type.
8200 static QualType
8201 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8202                              ExprResult &LHS, ExprResult &RHS,
8203                              SourceLocation QuestionLoc) {
8204   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8205   if (Cond.isInvalid())
8206     return QualType();
8207   QualType CondTy = Cond.get()->getType();
8208 
8209   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8210     return QualType();
8211 
8212   // If either operand is a vector then find the vector type of the
8213   // result as specified in OpenCL v1.1 s6.3.i.
8214   if (LHS.get()->getType()->isVectorType() ||
8215       RHS.get()->getType()->isVectorType()) {
8216     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8217                                               /*isCompAssign*/false,
8218                                               /*AllowBothBool*/true,
8219                                               /*AllowBoolConversions*/false);
8220     if (VecResTy.isNull()) return QualType();
8221     // The result type must match the condition type as specified in
8222     // OpenCL v1.1 s6.11.6.
8223     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8224       return QualType();
8225     return VecResTy;
8226   }
8227 
8228   // Both operands are scalar.
8229   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8230 }
8231 
8232 /// Return true if the Expr is block type
8233 static bool checkBlockType(Sema &S, const Expr *E) {
8234   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8235     QualType Ty = CE->getCallee()->getType();
8236     if (Ty->isBlockPointerType()) {
8237       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8238       return true;
8239     }
8240   }
8241   return false;
8242 }
8243 
8244 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8245 /// In that case, LHS = cond.
8246 /// C99 6.5.15
8247 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8248                                         ExprResult &RHS, ExprValueKind &VK,
8249                                         ExprObjectKind &OK,
8250                                         SourceLocation QuestionLoc) {
8251 
8252   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8253   if (!LHSResult.isUsable()) return QualType();
8254   LHS = LHSResult;
8255 
8256   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8257   if (!RHSResult.isUsable()) return QualType();
8258   RHS = RHSResult;
8259 
8260   // C++ is sufficiently different to merit its own checker.
8261   if (getLangOpts().CPlusPlus)
8262     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8263 
8264   VK = VK_RValue;
8265   OK = OK_Ordinary;
8266 
8267   if (Context.isDependenceAllowed() &&
8268       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8269        RHS.get()->isTypeDependent())) {
8270     assert(!getLangOpts().CPlusPlus);
8271     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8272             RHS.get()->containsErrors()) &&
8273            "should only occur in error-recovery path.");
8274     return Context.DependentTy;
8275   }
8276 
8277   // The OpenCL operator with a vector condition is sufficiently
8278   // different to merit its own checker.
8279   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8280       Cond.get()->getType()->isExtVectorType())
8281     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8282 
8283   // First, check the condition.
8284   Cond = UsualUnaryConversions(Cond.get());
8285   if (Cond.isInvalid())
8286     return QualType();
8287   if (checkCondition(*this, Cond.get(), QuestionLoc))
8288     return QualType();
8289 
8290   // Now check the two expressions.
8291   if (LHS.get()->getType()->isVectorType() ||
8292       RHS.get()->getType()->isVectorType())
8293     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8294                                /*AllowBothBool*/true,
8295                                /*AllowBoolConversions*/false);
8296 
8297   QualType ResTy =
8298       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8299   if (LHS.isInvalid() || RHS.isInvalid())
8300     return QualType();
8301 
8302   QualType LHSTy = LHS.get()->getType();
8303   QualType RHSTy = RHS.get()->getType();
8304 
8305   // Diagnose attempts to convert between __float128 and long double where
8306   // such conversions currently can't be handled.
8307   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8308     Diag(QuestionLoc,
8309          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8310       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8311     return QualType();
8312   }
8313 
8314   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8315   // selection operator (?:).
8316   if (getLangOpts().OpenCL &&
8317       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8318     return QualType();
8319   }
8320 
8321   // If both operands have arithmetic type, do the usual arithmetic conversions
8322   // to find a common type: C99 6.5.15p3,5.
8323   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8324     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8325     // different sizes, or between ExtInts and other types.
8326     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8327       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8328           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8329           << RHS.get()->getSourceRange();
8330       return QualType();
8331     }
8332 
8333     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8334     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8335 
8336     return ResTy;
8337   }
8338 
8339   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8340   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8341     return LHSTy;
8342   }
8343 
8344   // If both operands are the same structure or union type, the result is that
8345   // type.
8346   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8347     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8348       if (LHSRT->getDecl() == RHSRT->getDecl())
8349         // "If both the operands have structure or union type, the result has
8350         // that type."  This implies that CV qualifiers are dropped.
8351         return LHSTy.getUnqualifiedType();
8352     // FIXME: Type of conditional expression must be complete in C mode.
8353   }
8354 
8355   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8356   // The following || allows only one side to be void (a GCC-ism).
8357   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8358     return checkConditionalVoidType(*this, LHS, RHS);
8359   }
8360 
8361   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8362   // the type of the other operand."
8363   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8364   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8365 
8366   // All objective-c pointer type analysis is done here.
8367   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8368                                                         QuestionLoc);
8369   if (LHS.isInvalid() || RHS.isInvalid())
8370     return QualType();
8371   if (!compositeType.isNull())
8372     return compositeType;
8373 
8374 
8375   // Handle block pointer types.
8376   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8377     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8378                                                      QuestionLoc);
8379 
8380   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8381   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8382     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8383                                                        QuestionLoc);
8384 
8385   // GCC compatibility: soften pointer/integer mismatch.  Note that
8386   // null pointers have been filtered out by this point.
8387   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8388       /*IsIntFirstExpr=*/true))
8389     return RHSTy;
8390   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8391       /*IsIntFirstExpr=*/false))
8392     return LHSTy;
8393 
8394   // Allow ?: operations in which both operands have the same
8395   // built-in sizeless type.
8396   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8397     return LHSTy;
8398 
8399   // Emit a better diagnostic if one of the expressions is a null pointer
8400   // constant and the other is not a pointer type. In this case, the user most
8401   // likely forgot to take the address of the other expression.
8402   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8403     return QualType();
8404 
8405   // Otherwise, the operands are not compatible.
8406   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8407     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8408     << RHS.get()->getSourceRange();
8409   return QualType();
8410 }
8411 
8412 /// FindCompositeObjCPointerType - Helper method to find composite type of
8413 /// two objective-c pointer types of the two input expressions.
8414 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8415                                             SourceLocation QuestionLoc) {
8416   QualType LHSTy = LHS.get()->getType();
8417   QualType RHSTy = RHS.get()->getType();
8418 
8419   // Handle things like Class and struct objc_class*.  Here we case the result
8420   // to the pseudo-builtin, because that will be implicitly cast back to the
8421   // redefinition type if an attempt is made to access its fields.
8422   if (LHSTy->isObjCClassType() &&
8423       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8424     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8425     return LHSTy;
8426   }
8427   if (RHSTy->isObjCClassType() &&
8428       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8429     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8430     return RHSTy;
8431   }
8432   // And the same for struct objc_object* / id
8433   if (LHSTy->isObjCIdType() &&
8434       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8435     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8436     return LHSTy;
8437   }
8438   if (RHSTy->isObjCIdType() &&
8439       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8440     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8441     return RHSTy;
8442   }
8443   // And the same for struct objc_selector* / SEL
8444   if (Context.isObjCSelType(LHSTy) &&
8445       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8446     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8447     return LHSTy;
8448   }
8449   if (Context.isObjCSelType(RHSTy) &&
8450       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8451     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8452     return RHSTy;
8453   }
8454   // Check constraints for Objective-C object pointers types.
8455   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8456 
8457     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8458       // Two identical object pointer types are always compatible.
8459       return LHSTy;
8460     }
8461     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8462     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8463     QualType compositeType = LHSTy;
8464 
8465     // If both operands are interfaces and either operand can be
8466     // assigned to the other, use that type as the composite
8467     // type. This allows
8468     //   xxx ? (A*) a : (B*) b
8469     // where B is a subclass of A.
8470     //
8471     // Additionally, as for assignment, if either type is 'id'
8472     // allow silent coercion. Finally, if the types are
8473     // incompatible then make sure to use 'id' as the composite
8474     // type so the result is acceptable for sending messages to.
8475 
8476     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8477     // It could return the composite type.
8478     if (!(compositeType =
8479           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8480       // Nothing more to do.
8481     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8482       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8483     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8484       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8485     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8486                 RHSOPT->isObjCQualifiedIdType()) &&
8487                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8488                                                          true)) {
8489       // Need to handle "id<xx>" explicitly.
8490       // GCC allows qualified id and any Objective-C type to devolve to
8491       // id. Currently localizing to here until clear this should be
8492       // part of ObjCQualifiedIdTypesAreCompatible.
8493       compositeType = Context.getObjCIdType();
8494     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8495       compositeType = Context.getObjCIdType();
8496     } else {
8497       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8498       << LHSTy << RHSTy
8499       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8500       QualType incompatTy = Context.getObjCIdType();
8501       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8502       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8503       return incompatTy;
8504     }
8505     // The object pointer types are compatible.
8506     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8507     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8508     return compositeType;
8509   }
8510   // Check Objective-C object pointer types and 'void *'
8511   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8512     if (getLangOpts().ObjCAutoRefCount) {
8513       // ARC forbids the implicit conversion of object pointers to 'void *',
8514       // so these types are not compatible.
8515       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8516           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8517       LHS = RHS = true;
8518       return QualType();
8519     }
8520     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8521     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8522     QualType destPointee
8523     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8524     QualType destType = Context.getPointerType(destPointee);
8525     // Add qualifiers if necessary.
8526     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8527     // Promote to void*.
8528     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8529     return destType;
8530   }
8531   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8532     if (getLangOpts().ObjCAutoRefCount) {
8533       // ARC forbids the implicit conversion of object pointers to 'void *',
8534       // so these types are not compatible.
8535       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8536           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8537       LHS = RHS = true;
8538       return QualType();
8539     }
8540     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8541     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8542     QualType destPointee
8543     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8544     QualType destType = Context.getPointerType(destPointee);
8545     // Add qualifiers if necessary.
8546     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8547     // Promote to void*.
8548     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8549     return destType;
8550   }
8551   return QualType();
8552 }
8553 
8554 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8555 /// ParenRange in parentheses.
8556 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8557                                const PartialDiagnostic &Note,
8558                                SourceRange ParenRange) {
8559   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8560   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8561       EndLoc.isValid()) {
8562     Self.Diag(Loc, Note)
8563       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8564       << FixItHint::CreateInsertion(EndLoc, ")");
8565   } else {
8566     // We can't display the parentheses, so just show the bare note.
8567     Self.Diag(Loc, Note) << ParenRange;
8568   }
8569 }
8570 
8571 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8572   return BinaryOperator::isAdditiveOp(Opc) ||
8573          BinaryOperator::isMultiplicativeOp(Opc) ||
8574          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8575   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8576   // not any of the logical operators.  Bitwise-xor is commonly used as a
8577   // logical-xor because there is no logical-xor operator.  The logical
8578   // operators, including uses of xor, have a high false positive rate for
8579   // precedence warnings.
8580 }
8581 
8582 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8583 /// expression, either using a built-in or overloaded operator,
8584 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8585 /// expression.
8586 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8587                                    Expr **RHSExprs) {
8588   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8589   E = E->IgnoreImpCasts();
8590   E = E->IgnoreConversionOperatorSingleStep();
8591   E = E->IgnoreImpCasts();
8592   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8593     E = MTE->getSubExpr();
8594     E = E->IgnoreImpCasts();
8595   }
8596 
8597   // Built-in binary operator.
8598   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8599     if (IsArithmeticOp(OP->getOpcode())) {
8600       *Opcode = OP->getOpcode();
8601       *RHSExprs = OP->getRHS();
8602       return true;
8603     }
8604   }
8605 
8606   // Overloaded operator.
8607   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8608     if (Call->getNumArgs() != 2)
8609       return false;
8610 
8611     // Make sure this is really a binary operator that is safe to pass into
8612     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8613     OverloadedOperatorKind OO = Call->getOperator();
8614     if (OO < OO_Plus || OO > OO_Arrow ||
8615         OO == OO_PlusPlus || OO == OO_MinusMinus)
8616       return false;
8617 
8618     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8619     if (IsArithmeticOp(OpKind)) {
8620       *Opcode = OpKind;
8621       *RHSExprs = Call->getArg(1);
8622       return true;
8623     }
8624   }
8625 
8626   return false;
8627 }
8628 
8629 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8630 /// or is a logical expression such as (x==y) which has int type, but is
8631 /// commonly interpreted as boolean.
8632 static bool ExprLooksBoolean(Expr *E) {
8633   E = E->IgnoreParenImpCasts();
8634 
8635   if (E->getType()->isBooleanType())
8636     return true;
8637   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8638     return OP->isComparisonOp() || OP->isLogicalOp();
8639   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8640     return OP->getOpcode() == UO_LNot;
8641   if (E->getType()->isPointerType())
8642     return true;
8643   // FIXME: What about overloaded operator calls returning "unspecified boolean
8644   // type"s (commonly pointer-to-members)?
8645 
8646   return false;
8647 }
8648 
8649 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8650 /// and binary operator are mixed in a way that suggests the programmer assumed
8651 /// the conditional operator has higher precedence, for example:
8652 /// "int x = a + someBinaryCondition ? 1 : 2".
8653 static void DiagnoseConditionalPrecedence(Sema &Self,
8654                                           SourceLocation OpLoc,
8655                                           Expr *Condition,
8656                                           Expr *LHSExpr,
8657                                           Expr *RHSExpr) {
8658   BinaryOperatorKind CondOpcode;
8659   Expr *CondRHS;
8660 
8661   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8662     return;
8663   if (!ExprLooksBoolean(CondRHS))
8664     return;
8665 
8666   // The condition is an arithmetic binary expression, with a right-
8667   // hand side that looks boolean, so warn.
8668 
8669   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8670                         ? diag::warn_precedence_bitwise_conditional
8671                         : diag::warn_precedence_conditional;
8672 
8673   Self.Diag(OpLoc, DiagID)
8674       << Condition->getSourceRange()
8675       << BinaryOperator::getOpcodeStr(CondOpcode);
8676 
8677   SuggestParentheses(
8678       Self, OpLoc,
8679       Self.PDiag(diag::note_precedence_silence)
8680           << BinaryOperator::getOpcodeStr(CondOpcode),
8681       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8682 
8683   SuggestParentheses(Self, OpLoc,
8684                      Self.PDiag(diag::note_precedence_conditional_first),
8685                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8686 }
8687 
8688 /// Compute the nullability of a conditional expression.
8689 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8690                                               QualType LHSTy, QualType RHSTy,
8691                                               ASTContext &Ctx) {
8692   if (!ResTy->isAnyPointerType())
8693     return ResTy;
8694 
8695   auto GetNullability = [&Ctx](QualType Ty) {
8696     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8697     if (Kind) {
8698       // For our purposes, treat _Nullable_result as _Nullable.
8699       if (*Kind == NullabilityKind::NullableResult)
8700         return NullabilityKind::Nullable;
8701       return *Kind;
8702     }
8703     return NullabilityKind::Unspecified;
8704   };
8705 
8706   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8707   NullabilityKind MergedKind;
8708 
8709   // Compute nullability of a binary conditional expression.
8710   if (IsBin) {
8711     if (LHSKind == NullabilityKind::NonNull)
8712       MergedKind = NullabilityKind::NonNull;
8713     else
8714       MergedKind = RHSKind;
8715   // Compute nullability of a normal conditional expression.
8716   } else {
8717     if (LHSKind == NullabilityKind::Nullable ||
8718         RHSKind == NullabilityKind::Nullable)
8719       MergedKind = NullabilityKind::Nullable;
8720     else if (LHSKind == NullabilityKind::NonNull)
8721       MergedKind = RHSKind;
8722     else if (RHSKind == NullabilityKind::NonNull)
8723       MergedKind = LHSKind;
8724     else
8725       MergedKind = NullabilityKind::Unspecified;
8726   }
8727 
8728   // Return if ResTy already has the correct nullability.
8729   if (GetNullability(ResTy) == MergedKind)
8730     return ResTy;
8731 
8732   // Strip all nullability from ResTy.
8733   while (ResTy->getNullability(Ctx))
8734     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8735 
8736   // Create a new AttributedType with the new nullability kind.
8737   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8738   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8739 }
8740 
8741 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8742 /// in the case of a the GNU conditional expr extension.
8743 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8744                                     SourceLocation ColonLoc,
8745                                     Expr *CondExpr, Expr *LHSExpr,
8746                                     Expr *RHSExpr) {
8747   if (!Context.isDependenceAllowed()) {
8748     // C cannot handle TypoExpr nodes in the condition because it
8749     // doesn't handle dependent types properly, so make sure any TypoExprs have
8750     // been dealt with before checking the operands.
8751     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8752     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8753     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8754 
8755     if (!CondResult.isUsable())
8756       return ExprError();
8757 
8758     if (LHSExpr) {
8759       if (!LHSResult.isUsable())
8760         return ExprError();
8761     }
8762 
8763     if (!RHSResult.isUsable())
8764       return ExprError();
8765 
8766     CondExpr = CondResult.get();
8767     LHSExpr = LHSResult.get();
8768     RHSExpr = RHSResult.get();
8769   }
8770 
8771   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8772   // was the condition.
8773   OpaqueValueExpr *opaqueValue = nullptr;
8774   Expr *commonExpr = nullptr;
8775   if (!LHSExpr) {
8776     commonExpr = CondExpr;
8777     // Lower out placeholder types first.  This is important so that we don't
8778     // try to capture a placeholder. This happens in few cases in C++; such
8779     // as Objective-C++'s dictionary subscripting syntax.
8780     if (commonExpr->hasPlaceholderType()) {
8781       ExprResult result = CheckPlaceholderExpr(commonExpr);
8782       if (!result.isUsable()) return ExprError();
8783       commonExpr = result.get();
8784     }
8785     // We usually want to apply unary conversions *before* saving, except
8786     // in the special case of a C++ l-value conditional.
8787     if (!(getLangOpts().CPlusPlus
8788           && !commonExpr->isTypeDependent()
8789           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8790           && commonExpr->isGLValue()
8791           && commonExpr->isOrdinaryOrBitFieldObject()
8792           && RHSExpr->isOrdinaryOrBitFieldObject()
8793           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8794       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8795       if (commonRes.isInvalid())
8796         return ExprError();
8797       commonExpr = commonRes.get();
8798     }
8799 
8800     // If the common expression is a class or array prvalue, materialize it
8801     // so that we can safely refer to it multiple times.
8802     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8803                                    commonExpr->getType()->isArrayType())) {
8804       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8805       if (MatExpr.isInvalid())
8806         return ExprError();
8807       commonExpr = MatExpr.get();
8808     }
8809 
8810     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8811                                                 commonExpr->getType(),
8812                                                 commonExpr->getValueKind(),
8813                                                 commonExpr->getObjectKind(),
8814                                                 commonExpr);
8815     LHSExpr = CondExpr = opaqueValue;
8816   }
8817 
8818   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8819   ExprValueKind VK = VK_RValue;
8820   ExprObjectKind OK = OK_Ordinary;
8821   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8822   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8823                                              VK, OK, QuestionLoc);
8824   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8825       RHS.isInvalid())
8826     return ExprError();
8827 
8828   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8829                                 RHS.get());
8830 
8831   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8832 
8833   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8834                                          Context);
8835 
8836   if (!commonExpr)
8837     return new (Context)
8838         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8839                             RHS.get(), result, VK, OK);
8840 
8841   return new (Context) BinaryConditionalOperator(
8842       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8843       ColonLoc, result, VK, OK);
8844 }
8845 
8846 // Check if we have a conversion between incompatible cmse function pointer
8847 // types, that is, a conversion between a function pointer with the
8848 // cmse_nonsecure_call attribute and one without.
8849 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8850                                           QualType ToType) {
8851   if (const auto *ToFn =
8852           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8853     if (const auto *FromFn =
8854             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8855       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8856       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8857 
8858       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8859     }
8860   }
8861   return false;
8862 }
8863 
8864 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8865 // being closely modeled after the C99 spec:-). The odd characteristic of this
8866 // routine is it effectively iqnores the qualifiers on the top level pointee.
8867 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8868 // FIXME: add a couple examples in this comment.
8869 static Sema::AssignConvertType
8870 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8871   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8872   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8873 
8874   // get the "pointed to" type (ignoring qualifiers at the top level)
8875   const Type *lhptee, *rhptee;
8876   Qualifiers lhq, rhq;
8877   std::tie(lhptee, lhq) =
8878       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8879   std::tie(rhptee, rhq) =
8880       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8881 
8882   Sema::AssignConvertType ConvTy = Sema::Compatible;
8883 
8884   // C99 6.5.16.1p1: This following citation is common to constraints
8885   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8886   // qualifiers of the type *pointed to* by the right;
8887 
8888   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8889   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8890       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8891     // Ignore lifetime for further calculation.
8892     lhq.removeObjCLifetime();
8893     rhq.removeObjCLifetime();
8894   }
8895 
8896   if (!lhq.compatiblyIncludes(rhq)) {
8897     // Treat address-space mismatches as fatal.
8898     if (!lhq.isAddressSpaceSupersetOf(rhq))
8899       return Sema::IncompatiblePointerDiscardsQualifiers;
8900 
8901     // It's okay to add or remove GC or lifetime qualifiers when converting to
8902     // and from void*.
8903     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8904                         .compatiblyIncludes(
8905                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8906              && (lhptee->isVoidType() || rhptee->isVoidType()))
8907       ; // keep old
8908 
8909     // Treat lifetime mismatches as fatal.
8910     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8911       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8912 
8913     // For GCC/MS compatibility, other qualifier mismatches are treated
8914     // as still compatible in C.
8915     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8916   }
8917 
8918   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8919   // incomplete type and the other is a pointer to a qualified or unqualified
8920   // version of void...
8921   if (lhptee->isVoidType()) {
8922     if (rhptee->isIncompleteOrObjectType())
8923       return ConvTy;
8924 
8925     // As an extension, we allow cast to/from void* to function pointer.
8926     assert(rhptee->isFunctionType());
8927     return Sema::FunctionVoidPointer;
8928   }
8929 
8930   if (rhptee->isVoidType()) {
8931     if (lhptee->isIncompleteOrObjectType())
8932       return ConvTy;
8933 
8934     // As an extension, we allow cast to/from void* to function pointer.
8935     assert(lhptee->isFunctionType());
8936     return Sema::FunctionVoidPointer;
8937   }
8938 
8939   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8940   // unqualified versions of compatible types, ...
8941   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8942   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8943     // Check if the pointee types are compatible ignoring the sign.
8944     // We explicitly check for char so that we catch "char" vs
8945     // "unsigned char" on systems where "char" is unsigned.
8946     if (lhptee->isCharType())
8947       ltrans = S.Context.UnsignedCharTy;
8948     else if (lhptee->hasSignedIntegerRepresentation())
8949       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8950 
8951     if (rhptee->isCharType())
8952       rtrans = S.Context.UnsignedCharTy;
8953     else if (rhptee->hasSignedIntegerRepresentation())
8954       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8955 
8956     if (ltrans == rtrans) {
8957       // Types are compatible ignoring the sign. Qualifier incompatibility
8958       // takes priority over sign incompatibility because the sign
8959       // warning can be disabled.
8960       if (ConvTy != Sema::Compatible)
8961         return ConvTy;
8962 
8963       return Sema::IncompatiblePointerSign;
8964     }
8965 
8966     // If we are a multi-level pointer, it's possible that our issue is simply
8967     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8968     // the eventual target type is the same and the pointers have the same
8969     // level of indirection, this must be the issue.
8970     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8971       do {
8972         std::tie(lhptee, lhq) =
8973           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8974         std::tie(rhptee, rhq) =
8975           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8976 
8977         // Inconsistent address spaces at this point is invalid, even if the
8978         // address spaces would be compatible.
8979         // FIXME: This doesn't catch address space mismatches for pointers of
8980         // different nesting levels, like:
8981         //   __local int *** a;
8982         //   int ** b = a;
8983         // It's not clear how to actually determine when such pointers are
8984         // invalidly incompatible.
8985         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8986           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8987 
8988       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8989 
8990       if (lhptee == rhptee)
8991         return Sema::IncompatibleNestedPointerQualifiers;
8992     }
8993 
8994     // General pointer incompatibility takes priority over qualifiers.
8995     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8996       return Sema::IncompatibleFunctionPointer;
8997     return Sema::IncompatiblePointer;
8998   }
8999   if (!S.getLangOpts().CPlusPlus &&
9000       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9001     return Sema::IncompatibleFunctionPointer;
9002   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9003     return Sema::IncompatibleFunctionPointer;
9004   return ConvTy;
9005 }
9006 
9007 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9008 /// block pointer types are compatible or whether a block and normal pointer
9009 /// are compatible. It is more restrict than comparing two function pointer
9010 // types.
9011 static Sema::AssignConvertType
9012 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9013                                     QualType RHSType) {
9014   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9015   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9016 
9017   QualType lhptee, rhptee;
9018 
9019   // get the "pointed to" type (ignoring qualifiers at the top level)
9020   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9021   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9022 
9023   // In C++, the types have to match exactly.
9024   if (S.getLangOpts().CPlusPlus)
9025     return Sema::IncompatibleBlockPointer;
9026 
9027   Sema::AssignConvertType ConvTy = Sema::Compatible;
9028 
9029   // For blocks we enforce that qualifiers are identical.
9030   Qualifiers LQuals = lhptee.getLocalQualifiers();
9031   Qualifiers RQuals = rhptee.getLocalQualifiers();
9032   if (S.getLangOpts().OpenCL) {
9033     LQuals.removeAddressSpace();
9034     RQuals.removeAddressSpace();
9035   }
9036   if (LQuals != RQuals)
9037     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9038 
9039   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9040   // assignment.
9041   // The current behavior is similar to C++ lambdas. A block might be
9042   // assigned to a variable iff its return type and parameters are compatible
9043   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9044   // an assignment. Presumably it should behave in way that a function pointer
9045   // assignment does in C, so for each parameter and return type:
9046   //  * CVR and address space of LHS should be a superset of CVR and address
9047   //  space of RHS.
9048   //  * unqualified types should be compatible.
9049   if (S.getLangOpts().OpenCL) {
9050     if (!S.Context.typesAreBlockPointerCompatible(
9051             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9052             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9053       return Sema::IncompatibleBlockPointer;
9054   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9055     return Sema::IncompatibleBlockPointer;
9056 
9057   return ConvTy;
9058 }
9059 
9060 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9061 /// for assignment compatibility.
9062 static Sema::AssignConvertType
9063 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9064                                    QualType RHSType) {
9065   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9066   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9067 
9068   if (LHSType->isObjCBuiltinType()) {
9069     // Class is not compatible with ObjC object pointers.
9070     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9071         !RHSType->isObjCQualifiedClassType())
9072       return Sema::IncompatiblePointer;
9073     return Sema::Compatible;
9074   }
9075   if (RHSType->isObjCBuiltinType()) {
9076     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9077         !LHSType->isObjCQualifiedClassType())
9078       return Sema::IncompatiblePointer;
9079     return Sema::Compatible;
9080   }
9081   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9082   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9083 
9084   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9085       // make an exception for id<P>
9086       !LHSType->isObjCQualifiedIdType())
9087     return Sema::CompatiblePointerDiscardsQualifiers;
9088 
9089   if (S.Context.typesAreCompatible(LHSType, RHSType))
9090     return Sema::Compatible;
9091   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9092     return Sema::IncompatibleObjCQualifiedId;
9093   return Sema::IncompatiblePointer;
9094 }
9095 
9096 Sema::AssignConvertType
9097 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9098                                  QualType LHSType, QualType RHSType) {
9099   // Fake up an opaque expression.  We don't actually care about what
9100   // cast operations are required, so if CheckAssignmentConstraints
9101   // adds casts to this they'll be wasted, but fortunately that doesn't
9102   // usually happen on valid code.
9103   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
9104   ExprResult RHSPtr = &RHSExpr;
9105   CastKind K;
9106 
9107   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9108 }
9109 
9110 /// This helper function returns true if QT is a vector type that has element
9111 /// type ElementType.
9112 static bool isVector(QualType QT, QualType ElementType) {
9113   if (const VectorType *VT = QT->getAs<VectorType>())
9114     return VT->getElementType().getCanonicalType() == ElementType;
9115   return false;
9116 }
9117 
9118 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9119 /// has code to accommodate several GCC extensions when type checking
9120 /// pointers. Here are some objectionable examples that GCC considers warnings:
9121 ///
9122 ///  int a, *pint;
9123 ///  short *pshort;
9124 ///  struct foo *pfoo;
9125 ///
9126 ///  pint = pshort; // warning: assignment from incompatible pointer type
9127 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9128 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9129 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9130 ///
9131 /// As a result, the code for dealing with pointers is more complex than the
9132 /// C99 spec dictates.
9133 ///
9134 /// Sets 'Kind' for any result kind except Incompatible.
9135 Sema::AssignConvertType
9136 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9137                                  CastKind &Kind, bool ConvertRHS) {
9138   QualType RHSType = RHS.get()->getType();
9139   QualType OrigLHSType = LHSType;
9140 
9141   // Get canonical types.  We're not formatting these types, just comparing
9142   // them.
9143   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9144   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9145 
9146   // Common case: no conversion required.
9147   if (LHSType == RHSType) {
9148     Kind = CK_NoOp;
9149     return Compatible;
9150   }
9151 
9152   // If we have an atomic type, try a non-atomic assignment, then just add an
9153   // atomic qualification step.
9154   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9155     Sema::AssignConvertType result =
9156       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9157     if (result != Compatible)
9158       return result;
9159     if (Kind != CK_NoOp && ConvertRHS)
9160       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9161     Kind = CK_NonAtomicToAtomic;
9162     return Compatible;
9163   }
9164 
9165   // If the left-hand side is a reference type, then we are in a
9166   // (rare!) case where we've allowed the use of references in C,
9167   // e.g., as a parameter type in a built-in function. In this case,
9168   // just make sure that the type referenced is compatible with the
9169   // right-hand side type. The caller is responsible for adjusting
9170   // LHSType so that the resulting expression does not have reference
9171   // type.
9172   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9173     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9174       Kind = CK_LValueBitCast;
9175       return Compatible;
9176     }
9177     return Incompatible;
9178   }
9179 
9180   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9181   // to the same ExtVector type.
9182   if (LHSType->isExtVectorType()) {
9183     if (RHSType->isExtVectorType())
9184       return Incompatible;
9185     if (RHSType->isArithmeticType()) {
9186       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9187       if (ConvertRHS)
9188         RHS = prepareVectorSplat(LHSType, RHS.get());
9189       Kind = CK_VectorSplat;
9190       return Compatible;
9191     }
9192   }
9193 
9194   // Conversions to or from vector type.
9195   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9196     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9197       // Allow assignments of an AltiVec vector type to an equivalent GCC
9198       // vector type and vice versa
9199       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9200         Kind = CK_BitCast;
9201         return Compatible;
9202       }
9203 
9204       // If we are allowing lax vector conversions, and LHS and RHS are both
9205       // vectors, the total size only needs to be the same. This is a bitcast;
9206       // no bits are changed but the result type is different.
9207       if (isLaxVectorConversion(RHSType, LHSType)) {
9208         Kind = CK_BitCast;
9209         return IncompatibleVectors;
9210       }
9211     }
9212 
9213     // When the RHS comes from another lax conversion (e.g. binops between
9214     // scalars and vectors) the result is canonicalized as a vector. When the
9215     // LHS is also a vector, the lax is allowed by the condition above. Handle
9216     // the case where LHS is a scalar.
9217     if (LHSType->isScalarType()) {
9218       const VectorType *VecType = RHSType->getAs<VectorType>();
9219       if (VecType && VecType->getNumElements() == 1 &&
9220           isLaxVectorConversion(RHSType, LHSType)) {
9221         ExprResult *VecExpr = &RHS;
9222         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9223         Kind = CK_BitCast;
9224         return Compatible;
9225       }
9226     }
9227 
9228     // Allow assignments between fixed-length and sizeless SVE vectors.
9229     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9230         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9231       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9232           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9233         Kind = CK_BitCast;
9234         return Compatible;
9235       }
9236 
9237     return Incompatible;
9238   }
9239 
9240   // Diagnose attempts to convert between __float128 and long double where
9241   // such conversions currently can't be handled.
9242   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9243     return Incompatible;
9244 
9245   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9246   // discards the imaginary part.
9247   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9248       !LHSType->getAs<ComplexType>())
9249     return Incompatible;
9250 
9251   // Arithmetic conversions.
9252   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9253       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9254     if (ConvertRHS)
9255       Kind = PrepareScalarCast(RHS, LHSType);
9256     return Compatible;
9257   }
9258 
9259   // Conversions to normal pointers.
9260   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9261     // U* -> T*
9262     if (isa<PointerType>(RHSType)) {
9263       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9264       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9265       if (AddrSpaceL != AddrSpaceR)
9266         Kind = CK_AddressSpaceConversion;
9267       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9268         Kind = CK_NoOp;
9269       else
9270         Kind = CK_BitCast;
9271       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9272     }
9273 
9274     // int -> T*
9275     if (RHSType->isIntegerType()) {
9276       Kind = CK_IntegralToPointer; // FIXME: null?
9277       return IntToPointer;
9278     }
9279 
9280     // C pointers are not compatible with ObjC object pointers,
9281     // with two exceptions:
9282     if (isa<ObjCObjectPointerType>(RHSType)) {
9283       //  - conversions to void*
9284       if (LHSPointer->getPointeeType()->isVoidType()) {
9285         Kind = CK_BitCast;
9286         return Compatible;
9287       }
9288 
9289       //  - conversions from 'Class' to the redefinition type
9290       if (RHSType->isObjCClassType() &&
9291           Context.hasSameType(LHSType,
9292                               Context.getObjCClassRedefinitionType())) {
9293         Kind = CK_BitCast;
9294         return Compatible;
9295       }
9296 
9297       Kind = CK_BitCast;
9298       return IncompatiblePointer;
9299     }
9300 
9301     // U^ -> void*
9302     if (RHSType->getAs<BlockPointerType>()) {
9303       if (LHSPointer->getPointeeType()->isVoidType()) {
9304         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9305         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9306                                 ->getPointeeType()
9307                                 .getAddressSpace();
9308         Kind =
9309             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9310         return Compatible;
9311       }
9312     }
9313 
9314     return Incompatible;
9315   }
9316 
9317   // Conversions to block pointers.
9318   if (isa<BlockPointerType>(LHSType)) {
9319     // U^ -> T^
9320     if (RHSType->isBlockPointerType()) {
9321       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9322                               ->getPointeeType()
9323                               .getAddressSpace();
9324       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9325                               ->getPointeeType()
9326                               .getAddressSpace();
9327       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9328       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9329     }
9330 
9331     // int or null -> T^
9332     if (RHSType->isIntegerType()) {
9333       Kind = CK_IntegralToPointer; // FIXME: null
9334       return IntToBlockPointer;
9335     }
9336 
9337     // id -> T^
9338     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9339       Kind = CK_AnyPointerToBlockPointerCast;
9340       return Compatible;
9341     }
9342 
9343     // void* -> T^
9344     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9345       if (RHSPT->getPointeeType()->isVoidType()) {
9346         Kind = CK_AnyPointerToBlockPointerCast;
9347         return Compatible;
9348       }
9349 
9350     return Incompatible;
9351   }
9352 
9353   // Conversions to Objective-C pointers.
9354   if (isa<ObjCObjectPointerType>(LHSType)) {
9355     // A* -> B*
9356     if (RHSType->isObjCObjectPointerType()) {
9357       Kind = CK_BitCast;
9358       Sema::AssignConvertType result =
9359         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9360       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9361           result == Compatible &&
9362           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9363         result = IncompatibleObjCWeakRef;
9364       return result;
9365     }
9366 
9367     // int or null -> A*
9368     if (RHSType->isIntegerType()) {
9369       Kind = CK_IntegralToPointer; // FIXME: null
9370       return IntToPointer;
9371     }
9372 
9373     // In general, C pointers are not compatible with ObjC object pointers,
9374     // with two exceptions:
9375     if (isa<PointerType>(RHSType)) {
9376       Kind = CK_CPointerToObjCPointerCast;
9377 
9378       //  - conversions from 'void*'
9379       if (RHSType->isVoidPointerType()) {
9380         return Compatible;
9381       }
9382 
9383       //  - conversions to 'Class' from its redefinition type
9384       if (LHSType->isObjCClassType() &&
9385           Context.hasSameType(RHSType,
9386                               Context.getObjCClassRedefinitionType())) {
9387         return Compatible;
9388       }
9389 
9390       return IncompatiblePointer;
9391     }
9392 
9393     // Only under strict condition T^ is compatible with an Objective-C pointer.
9394     if (RHSType->isBlockPointerType() &&
9395         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9396       if (ConvertRHS)
9397         maybeExtendBlockObject(RHS);
9398       Kind = CK_BlockPointerToObjCPointerCast;
9399       return Compatible;
9400     }
9401 
9402     return Incompatible;
9403   }
9404 
9405   // Conversions from pointers that are not covered by the above.
9406   if (isa<PointerType>(RHSType)) {
9407     // T* -> _Bool
9408     if (LHSType == Context.BoolTy) {
9409       Kind = CK_PointerToBoolean;
9410       return Compatible;
9411     }
9412 
9413     // T* -> int
9414     if (LHSType->isIntegerType()) {
9415       Kind = CK_PointerToIntegral;
9416       return PointerToInt;
9417     }
9418 
9419     return Incompatible;
9420   }
9421 
9422   // Conversions from Objective-C pointers that are not covered by the above.
9423   if (isa<ObjCObjectPointerType>(RHSType)) {
9424     // T* -> _Bool
9425     if (LHSType == Context.BoolTy) {
9426       Kind = CK_PointerToBoolean;
9427       return Compatible;
9428     }
9429 
9430     // T* -> int
9431     if (LHSType->isIntegerType()) {
9432       Kind = CK_PointerToIntegral;
9433       return PointerToInt;
9434     }
9435 
9436     return Incompatible;
9437   }
9438 
9439   // struct A -> struct B
9440   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9441     if (Context.typesAreCompatible(LHSType, RHSType)) {
9442       Kind = CK_NoOp;
9443       return Compatible;
9444     }
9445   }
9446 
9447   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9448     Kind = CK_IntToOCLSampler;
9449     return Compatible;
9450   }
9451 
9452   return Incompatible;
9453 }
9454 
9455 /// Constructs a transparent union from an expression that is
9456 /// used to initialize the transparent union.
9457 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9458                                       ExprResult &EResult, QualType UnionType,
9459                                       FieldDecl *Field) {
9460   // Build an initializer list that designates the appropriate member
9461   // of the transparent union.
9462   Expr *E = EResult.get();
9463   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9464                                                    E, SourceLocation());
9465   Initializer->setType(UnionType);
9466   Initializer->setInitializedFieldInUnion(Field);
9467 
9468   // Build a compound literal constructing a value of the transparent
9469   // union type from this initializer list.
9470   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9471   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9472                                         VK_RValue, Initializer, false);
9473 }
9474 
9475 Sema::AssignConvertType
9476 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9477                                                ExprResult &RHS) {
9478   QualType RHSType = RHS.get()->getType();
9479 
9480   // If the ArgType is a Union type, we want to handle a potential
9481   // transparent_union GCC extension.
9482   const RecordType *UT = ArgType->getAsUnionType();
9483   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9484     return Incompatible;
9485 
9486   // The field to initialize within the transparent union.
9487   RecordDecl *UD = UT->getDecl();
9488   FieldDecl *InitField = nullptr;
9489   // It's compatible if the expression matches any of the fields.
9490   for (auto *it : UD->fields()) {
9491     if (it->getType()->isPointerType()) {
9492       // If the transparent union contains a pointer type, we allow:
9493       // 1) void pointer
9494       // 2) null pointer constant
9495       if (RHSType->isPointerType())
9496         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9497           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9498           InitField = it;
9499           break;
9500         }
9501 
9502       if (RHS.get()->isNullPointerConstant(Context,
9503                                            Expr::NPC_ValueDependentIsNull)) {
9504         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9505                                 CK_NullToPointer);
9506         InitField = it;
9507         break;
9508       }
9509     }
9510 
9511     CastKind Kind;
9512     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9513           == Compatible) {
9514       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9515       InitField = it;
9516       break;
9517     }
9518   }
9519 
9520   if (!InitField)
9521     return Incompatible;
9522 
9523   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9524   return Compatible;
9525 }
9526 
9527 Sema::AssignConvertType
9528 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9529                                        bool Diagnose,
9530                                        bool DiagnoseCFAudited,
9531                                        bool ConvertRHS) {
9532   // We need to be able to tell the caller whether we diagnosed a problem, if
9533   // they ask us to issue diagnostics.
9534   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9535 
9536   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9537   // we can't avoid *all* modifications at the moment, so we need some somewhere
9538   // to put the updated value.
9539   ExprResult LocalRHS = CallerRHS;
9540   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9541 
9542   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9543     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9544       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9545           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9546         Diag(RHS.get()->getExprLoc(),
9547              diag::warn_noderef_to_dereferenceable_pointer)
9548             << RHS.get()->getSourceRange();
9549       }
9550     }
9551   }
9552 
9553   if (getLangOpts().CPlusPlus) {
9554     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9555       // C++ 5.17p3: If the left operand is not of class type, the
9556       // expression is implicitly converted (C++ 4) to the
9557       // cv-unqualified type of the left operand.
9558       QualType RHSType = RHS.get()->getType();
9559       if (Diagnose) {
9560         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9561                                         AA_Assigning);
9562       } else {
9563         ImplicitConversionSequence ICS =
9564             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9565                                   /*SuppressUserConversions=*/false,
9566                                   AllowedExplicit::None,
9567                                   /*InOverloadResolution=*/false,
9568                                   /*CStyle=*/false,
9569                                   /*AllowObjCWritebackConversion=*/false);
9570         if (ICS.isFailure())
9571           return Incompatible;
9572         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9573                                         ICS, AA_Assigning);
9574       }
9575       if (RHS.isInvalid())
9576         return Incompatible;
9577       Sema::AssignConvertType result = Compatible;
9578       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9579           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9580         result = IncompatibleObjCWeakRef;
9581       return result;
9582     }
9583 
9584     // FIXME: Currently, we fall through and treat C++ classes like C
9585     // structures.
9586     // FIXME: We also fall through for atomics; not sure what should
9587     // happen there, though.
9588   } else if (RHS.get()->getType() == Context.OverloadTy) {
9589     // As a set of extensions to C, we support overloading on functions. These
9590     // functions need to be resolved here.
9591     DeclAccessPair DAP;
9592     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9593             RHS.get(), LHSType, /*Complain=*/false, DAP))
9594       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9595     else
9596       return Incompatible;
9597   }
9598 
9599   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9600   // a null pointer constant.
9601   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9602        LHSType->isBlockPointerType()) &&
9603       RHS.get()->isNullPointerConstant(Context,
9604                                        Expr::NPC_ValueDependentIsNull)) {
9605     if (Diagnose || ConvertRHS) {
9606       CastKind Kind;
9607       CXXCastPath Path;
9608       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9609                              /*IgnoreBaseAccess=*/false, Diagnose);
9610       if (ConvertRHS)
9611         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9612     }
9613     return Compatible;
9614   }
9615 
9616   // OpenCL queue_t type assignment.
9617   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9618                                  Context, Expr::NPC_ValueDependentIsNull)) {
9619     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9620     return Compatible;
9621   }
9622 
9623   // This check seems unnatural, however it is necessary to ensure the proper
9624   // conversion of functions/arrays. If the conversion were done for all
9625   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9626   // expressions that suppress this implicit conversion (&, sizeof).
9627   //
9628   // Suppress this for references: C++ 8.5.3p5.
9629   if (!LHSType->isReferenceType()) {
9630     // FIXME: We potentially allocate here even if ConvertRHS is false.
9631     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9632     if (RHS.isInvalid())
9633       return Incompatible;
9634   }
9635   CastKind Kind;
9636   Sema::AssignConvertType result =
9637     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9638 
9639   // C99 6.5.16.1p2: The value of the right operand is converted to the
9640   // type of the assignment expression.
9641   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9642   // so that we can use references in built-in functions even in C.
9643   // The getNonReferenceType() call makes sure that the resulting expression
9644   // does not have reference type.
9645   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9646     QualType Ty = LHSType.getNonLValueExprType(Context);
9647     Expr *E = RHS.get();
9648 
9649     // Check for various Objective-C errors. If we are not reporting
9650     // diagnostics and just checking for errors, e.g., during overload
9651     // resolution, return Incompatible to indicate the failure.
9652     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9653         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9654                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9655       if (!Diagnose)
9656         return Incompatible;
9657     }
9658     if (getLangOpts().ObjC &&
9659         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9660                                            E->getType(), E, Diagnose) ||
9661          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9662       if (!Diagnose)
9663         return Incompatible;
9664       // Replace the expression with a corrected version and continue so we
9665       // can find further errors.
9666       RHS = E;
9667       return Compatible;
9668     }
9669 
9670     if (ConvertRHS)
9671       RHS = ImpCastExprToType(E, Ty, Kind);
9672   }
9673 
9674   return result;
9675 }
9676 
9677 namespace {
9678 /// The original operand to an operator, prior to the application of the usual
9679 /// arithmetic conversions and converting the arguments of a builtin operator
9680 /// candidate.
9681 struct OriginalOperand {
9682   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9683     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9684       Op = MTE->getSubExpr();
9685     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9686       Op = BTE->getSubExpr();
9687     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9688       Orig = ICE->getSubExprAsWritten();
9689       Conversion = ICE->getConversionFunction();
9690     }
9691   }
9692 
9693   QualType getType() const { return Orig->getType(); }
9694 
9695   Expr *Orig;
9696   NamedDecl *Conversion;
9697 };
9698 }
9699 
9700 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9701                                ExprResult &RHS) {
9702   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9703 
9704   Diag(Loc, diag::err_typecheck_invalid_operands)
9705     << OrigLHS.getType() << OrigRHS.getType()
9706     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9707 
9708   // If a user-defined conversion was applied to either of the operands prior
9709   // to applying the built-in operator rules, tell the user about it.
9710   if (OrigLHS.Conversion) {
9711     Diag(OrigLHS.Conversion->getLocation(),
9712          diag::note_typecheck_invalid_operands_converted)
9713       << 0 << LHS.get()->getType();
9714   }
9715   if (OrigRHS.Conversion) {
9716     Diag(OrigRHS.Conversion->getLocation(),
9717          diag::note_typecheck_invalid_operands_converted)
9718       << 1 << RHS.get()->getType();
9719   }
9720 
9721   return QualType();
9722 }
9723 
9724 // Diagnose cases where a scalar was implicitly converted to a vector and
9725 // diagnose the underlying types. Otherwise, diagnose the error
9726 // as invalid vector logical operands for non-C++ cases.
9727 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9728                                             ExprResult &RHS) {
9729   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9730   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9731 
9732   bool LHSNatVec = LHSType->isVectorType();
9733   bool RHSNatVec = RHSType->isVectorType();
9734 
9735   if (!(LHSNatVec && RHSNatVec)) {
9736     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9737     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9738     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9739         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9740         << Vector->getSourceRange();
9741     return QualType();
9742   }
9743 
9744   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9745       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9746       << RHS.get()->getSourceRange();
9747 
9748   return QualType();
9749 }
9750 
9751 /// Try to convert a value of non-vector type to a vector type by converting
9752 /// the type to the element type of the vector and then performing a splat.
9753 /// If the language is OpenCL, we only use conversions that promote scalar
9754 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9755 /// for float->int.
9756 ///
9757 /// OpenCL V2.0 6.2.6.p2:
9758 /// An error shall occur if any scalar operand type has greater rank
9759 /// than the type of the vector element.
9760 ///
9761 /// \param scalar - if non-null, actually perform the conversions
9762 /// \return true if the operation fails (but without diagnosing the failure)
9763 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9764                                      QualType scalarTy,
9765                                      QualType vectorEltTy,
9766                                      QualType vectorTy,
9767                                      unsigned &DiagID) {
9768   // The conversion to apply to the scalar before splatting it,
9769   // if necessary.
9770   CastKind scalarCast = CK_NoOp;
9771 
9772   if (vectorEltTy->isIntegralType(S.Context)) {
9773     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9774         (scalarTy->isIntegerType() &&
9775          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9776       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9777       return true;
9778     }
9779     if (!scalarTy->isIntegralType(S.Context))
9780       return true;
9781     scalarCast = CK_IntegralCast;
9782   } else if (vectorEltTy->isRealFloatingType()) {
9783     if (scalarTy->isRealFloatingType()) {
9784       if (S.getLangOpts().OpenCL &&
9785           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9786         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9787         return true;
9788       }
9789       scalarCast = CK_FloatingCast;
9790     }
9791     else if (scalarTy->isIntegralType(S.Context))
9792       scalarCast = CK_IntegralToFloating;
9793     else
9794       return true;
9795   } else {
9796     return true;
9797   }
9798 
9799   // Adjust scalar if desired.
9800   if (scalar) {
9801     if (scalarCast != CK_NoOp)
9802       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9803     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9804   }
9805   return false;
9806 }
9807 
9808 /// Convert vector E to a vector with the same number of elements but different
9809 /// element type.
9810 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9811   const auto *VecTy = E->getType()->getAs<VectorType>();
9812   assert(VecTy && "Expression E must be a vector");
9813   QualType NewVecTy = S.Context.getVectorType(ElementType,
9814                                               VecTy->getNumElements(),
9815                                               VecTy->getVectorKind());
9816 
9817   // Look through the implicit cast. Return the subexpression if its type is
9818   // NewVecTy.
9819   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9820     if (ICE->getSubExpr()->getType() == NewVecTy)
9821       return ICE->getSubExpr();
9822 
9823   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9824   return S.ImpCastExprToType(E, NewVecTy, Cast);
9825 }
9826 
9827 /// Test if a (constant) integer Int can be casted to another integer type
9828 /// IntTy without losing precision.
9829 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9830                                       QualType OtherIntTy) {
9831   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9832 
9833   // Reject cases where the value of the Int is unknown as that would
9834   // possibly cause truncation, but accept cases where the scalar can be
9835   // demoted without loss of precision.
9836   Expr::EvalResult EVResult;
9837   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9838   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9839   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9840   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9841 
9842   if (CstInt) {
9843     // If the scalar is constant and is of a higher order and has more active
9844     // bits that the vector element type, reject it.
9845     llvm::APSInt Result = EVResult.Val.getInt();
9846     unsigned NumBits = IntSigned
9847                            ? (Result.isNegative() ? Result.getMinSignedBits()
9848                                                   : Result.getActiveBits())
9849                            : Result.getActiveBits();
9850     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9851       return true;
9852 
9853     // If the signedness of the scalar type and the vector element type
9854     // differs and the number of bits is greater than that of the vector
9855     // element reject it.
9856     return (IntSigned != OtherIntSigned &&
9857             NumBits > S.Context.getIntWidth(OtherIntTy));
9858   }
9859 
9860   // Reject cases where the value of the scalar is not constant and it's
9861   // order is greater than that of the vector element type.
9862   return (Order < 0);
9863 }
9864 
9865 /// Test if a (constant) integer Int can be casted to floating point type
9866 /// FloatTy without losing precision.
9867 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9868                                      QualType FloatTy) {
9869   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9870 
9871   // Determine if the integer constant can be expressed as a floating point
9872   // number of the appropriate type.
9873   Expr::EvalResult EVResult;
9874   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9875 
9876   uint64_t Bits = 0;
9877   if (CstInt) {
9878     // Reject constants that would be truncated if they were converted to
9879     // the floating point type. Test by simple to/from conversion.
9880     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9881     //        could be avoided if there was a convertFromAPInt method
9882     //        which could signal back if implicit truncation occurred.
9883     llvm::APSInt Result = EVResult.Val.getInt();
9884     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9885     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9886                            llvm::APFloat::rmTowardZero);
9887     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9888                              !IntTy->hasSignedIntegerRepresentation());
9889     bool Ignored = false;
9890     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9891                            &Ignored);
9892     if (Result != ConvertBack)
9893       return true;
9894   } else {
9895     // Reject types that cannot be fully encoded into the mantissa of
9896     // the float.
9897     Bits = S.Context.getTypeSize(IntTy);
9898     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9899         S.Context.getFloatTypeSemantics(FloatTy));
9900     if (Bits > FloatPrec)
9901       return true;
9902   }
9903 
9904   return false;
9905 }
9906 
9907 /// Attempt to convert and splat Scalar into a vector whose types matches
9908 /// Vector following GCC conversion rules. The rule is that implicit
9909 /// conversion can occur when Scalar can be casted to match Vector's element
9910 /// type without causing truncation of Scalar.
9911 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9912                                         ExprResult *Vector) {
9913   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9914   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9915   const VectorType *VT = VectorTy->getAs<VectorType>();
9916 
9917   assert(!isa<ExtVectorType>(VT) &&
9918          "ExtVectorTypes should not be handled here!");
9919 
9920   QualType VectorEltTy = VT->getElementType();
9921 
9922   // Reject cases where the vector element type or the scalar element type are
9923   // not integral or floating point types.
9924   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9925     return true;
9926 
9927   // The conversion to apply to the scalar before splatting it,
9928   // if necessary.
9929   CastKind ScalarCast = CK_NoOp;
9930 
9931   // Accept cases where the vector elements are integers and the scalar is
9932   // an integer.
9933   // FIXME: Notionally if the scalar was a floating point value with a precise
9934   //        integral representation, we could cast it to an appropriate integer
9935   //        type and then perform the rest of the checks here. GCC will perform
9936   //        this conversion in some cases as determined by the input language.
9937   //        We should accept it on a language independent basis.
9938   if (VectorEltTy->isIntegralType(S.Context) &&
9939       ScalarTy->isIntegralType(S.Context) &&
9940       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9941 
9942     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9943       return true;
9944 
9945     ScalarCast = CK_IntegralCast;
9946   } else if (VectorEltTy->isIntegralType(S.Context) &&
9947              ScalarTy->isRealFloatingType()) {
9948     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9949       ScalarCast = CK_FloatingToIntegral;
9950     else
9951       return true;
9952   } else if (VectorEltTy->isRealFloatingType()) {
9953     if (ScalarTy->isRealFloatingType()) {
9954 
9955       // Reject cases where the scalar type is not a constant and has a higher
9956       // Order than the vector element type.
9957       llvm::APFloat Result(0.0);
9958 
9959       // Determine whether this is a constant scalar. In the event that the
9960       // value is dependent (and thus cannot be evaluated by the constant
9961       // evaluator), skip the evaluation. This will then diagnose once the
9962       // expression is instantiated.
9963       bool CstScalar = Scalar->get()->isValueDependent() ||
9964                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9965       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9966       if (!CstScalar && Order < 0)
9967         return true;
9968 
9969       // If the scalar cannot be safely casted to the vector element type,
9970       // reject it.
9971       if (CstScalar) {
9972         bool Truncated = false;
9973         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9974                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9975         if (Truncated)
9976           return true;
9977       }
9978 
9979       ScalarCast = CK_FloatingCast;
9980     } else if (ScalarTy->isIntegralType(S.Context)) {
9981       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9982         return true;
9983 
9984       ScalarCast = CK_IntegralToFloating;
9985     } else
9986       return true;
9987   } else if (ScalarTy->isEnumeralType())
9988     return true;
9989 
9990   // Adjust scalar if desired.
9991   if (Scalar) {
9992     if (ScalarCast != CK_NoOp)
9993       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9994     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9995   }
9996   return false;
9997 }
9998 
9999 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10000                                    SourceLocation Loc, bool IsCompAssign,
10001                                    bool AllowBothBool,
10002                                    bool AllowBoolConversions) {
10003   if (!IsCompAssign) {
10004     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10005     if (LHS.isInvalid())
10006       return QualType();
10007   }
10008   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10009   if (RHS.isInvalid())
10010     return QualType();
10011 
10012   // For conversion purposes, we ignore any qualifiers.
10013   // For example, "const float" and "float" are equivalent.
10014   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10015   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10016 
10017   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10018   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10019   assert(LHSVecType || RHSVecType);
10020 
10021   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10022       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10023     return InvalidOperands(Loc, LHS, RHS);
10024 
10025   // AltiVec-style "vector bool op vector bool" combinations are allowed
10026   // for some operators but not others.
10027   if (!AllowBothBool &&
10028       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10029       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10030     return InvalidOperands(Loc, LHS, RHS);
10031 
10032   // If the vector types are identical, return.
10033   if (Context.hasSameType(LHSType, RHSType))
10034     return LHSType;
10035 
10036   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10037   if (LHSVecType && RHSVecType &&
10038       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10039     if (isa<ExtVectorType>(LHSVecType)) {
10040       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10041       return LHSType;
10042     }
10043 
10044     if (!IsCompAssign)
10045       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10046     return RHSType;
10047   }
10048 
10049   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10050   // can be mixed, with the result being the non-bool type.  The non-bool
10051   // operand must have integer element type.
10052   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10053       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10054       (Context.getTypeSize(LHSVecType->getElementType()) ==
10055        Context.getTypeSize(RHSVecType->getElementType()))) {
10056     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10057         LHSVecType->getElementType()->isIntegerType() &&
10058         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10059       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10060       return LHSType;
10061     }
10062     if (!IsCompAssign &&
10063         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10064         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10065         RHSVecType->getElementType()->isIntegerType()) {
10066       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10067       return RHSType;
10068     }
10069   }
10070 
10071   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10072   // since the ambiguity can affect the ABI.
10073   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10074     const VectorType *VecType = SecondType->getAs<VectorType>();
10075     return FirstType->isSizelessBuiltinType() && VecType &&
10076            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10077             VecType->getVectorKind() ==
10078                 VectorType::SveFixedLengthPredicateVector);
10079   };
10080 
10081   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10082     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10083     return QualType();
10084   }
10085 
10086   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10087   // since the ambiguity can affect the ABI.
10088   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10089     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10090     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10091 
10092     if (FirstVecType && SecondVecType)
10093       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10094              (SecondVecType->getVectorKind() ==
10095                   VectorType::SveFixedLengthDataVector ||
10096               SecondVecType->getVectorKind() ==
10097                   VectorType::SveFixedLengthPredicateVector);
10098 
10099     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10100            SecondVecType->getVectorKind() == VectorType::GenericVector;
10101   };
10102 
10103   if (IsSveGnuConversion(LHSType, RHSType) ||
10104       IsSveGnuConversion(RHSType, LHSType)) {
10105     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10106     return QualType();
10107   }
10108 
10109   // If there's a vector type and a scalar, try to convert the scalar to
10110   // the vector element type and splat.
10111   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10112   if (!RHSVecType) {
10113     if (isa<ExtVectorType>(LHSVecType)) {
10114       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10115                                     LHSVecType->getElementType(), LHSType,
10116                                     DiagID))
10117         return LHSType;
10118     } else {
10119       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10120         return LHSType;
10121     }
10122   }
10123   if (!LHSVecType) {
10124     if (isa<ExtVectorType>(RHSVecType)) {
10125       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10126                                     LHSType, RHSVecType->getElementType(),
10127                                     RHSType, DiagID))
10128         return RHSType;
10129     } else {
10130       if (LHS.get()->getValueKind() == VK_LValue ||
10131           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10132         return RHSType;
10133     }
10134   }
10135 
10136   // FIXME: The code below also handles conversion between vectors and
10137   // non-scalars, we should break this down into fine grained specific checks
10138   // and emit proper diagnostics.
10139   QualType VecType = LHSVecType ? LHSType : RHSType;
10140   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10141   QualType OtherType = LHSVecType ? RHSType : LHSType;
10142   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10143   if (isLaxVectorConversion(OtherType, VecType)) {
10144     // If we're allowing lax vector conversions, only the total (data) size
10145     // needs to be the same. For non compound assignment, if one of the types is
10146     // scalar, the result is always the vector type.
10147     if (!IsCompAssign) {
10148       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10149       return VecType;
10150     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10151     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10152     // type. Note that this is already done by non-compound assignments in
10153     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10154     // <1 x T> -> T. The result is also a vector type.
10155     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10156                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10157       ExprResult *RHSExpr = &RHS;
10158       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10159       return VecType;
10160     }
10161   }
10162 
10163   // Okay, the expression is invalid.
10164 
10165   // If there's a non-vector, non-real operand, diagnose that.
10166   if ((!RHSVecType && !RHSType->isRealType()) ||
10167       (!LHSVecType && !LHSType->isRealType())) {
10168     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10169       << LHSType << RHSType
10170       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10171     return QualType();
10172   }
10173 
10174   // OpenCL V1.1 6.2.6.p1:
10175   // If the operands are of more than one vector type, then an error shall
10176   // occur. Implicit conversions between vector types are not permitted, per
10177   // section 6.2.1.
10178   if (getLangOpts().OpenCL &&
10179       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10180       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10181     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10182                                                            << RHSType;
10183     return QualType();
10184   }
10185 
10186 
10187   // If there is a vector type that is not a ExtVector and a scalar, we reach
10188   // this point if scalar could not be converted to the vector's element type
10189   // without truncation.
10190   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10191       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10192     QualType Scalar = LHSVecType ? RHSType : LHSType;
10193     QualType Vector = LHSVecType ? LHSType : RHSType;
10194     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10195     Diag(Loc,
10196          diag::err_typecheck_vector_not_convertable_implict_truncation)
10197         << ScalarOrVector << Scalar << Vector;
10198 
10199     return QualType();
10200   }
10201 
10202   // Otherwise, use the generic diagnostic.
10203   Diag(Loc, DiagID)
10204     << LHSType << RHSType
10205     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10206   return QualType();
10207 }
10208 
10209 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10210 // expression.  These are mainly cases where the null pointer is used as an
10211 // integer instead of a pointer.
10212 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10213                                 SourceLocation Loc, bool IsCompare) {
10214   // The canonical way to check for a GNU null is with isNullPointerConstant,
10215   // but we use a bit of a hack here for speed; this is a relatively
10216   // hot path, and isNullPointerConstant is slow.
10217   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10218   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10219 
10220   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10221 
10222   // Avoid analyzing cases where the result will either be invalid (and
10223   // diagnosed as such) or entirely valid and not something to warn about.
10224   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10225       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10226     return;
10227 
10228   // Comparison operations would not make sense with a null pointer no matter
10229   // what the other expression is.
10230   if (!IsCompare) {
10231     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10232         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10233         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10234     return;
10235   }
10236 
10237   // The rest of the operations only make sense with a null pointer
10238   // if the other expression is a pointer.
10239   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10240       NonNullType->canDecayToPointerType())
10241     return;
10242 
10243   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10244       << LHSNull /* LHS is NULL */ << NonNullType
10245       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10246 }
10247 
10248 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10249                                           SourceLocation Loc) {
10250   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10251   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10252   if (!LUE || !RUE)
10253     return;
10254   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10255       RUE->getKind() != UETT_SizeOf)
10256     return;
10257 
10258   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10259   QualType LHSTy = LHSArg->getType();
10260   QualType RHSTy;
10261 
10262   if (RUE->isArgumentType())
10263     RHSTy = RUE->getArgumentType().getNonReferenceType();
10264   else
10265     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10266 
10267   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10268     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10269       return;
10270 
10271     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10272     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10273       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10274         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10275             << LHSArgDecl;
10276     }
10277   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10278     QualType ArrayElemTy = ArrayTy->getElementType();
10279     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10280         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10281         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10282         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10283       return;
10284     S.Diag(Loc, diag::warn_division_sizeof_array)
10285         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10286     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10287       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10288         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10289             << LHSArgDecl;
10290     }
10291 
10292     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10293   }
10294 }
10295 
10296 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10297                                                ExprResult &RHS,
10298                                                SourceLocation Loc, bool IsDiv) {
10299   // Check for division/remainder by zero.
10300   Expr::EvalResult RHSValue;
10301   if (!RHS.get()->isValueDependent() &&
10302       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10303       RHSValue.Val.getInt() == 0)
10304     S.DiagRuntimeBehavior(Loc, RHS.get(),
10305                           S.PDiag(diag::warn_remainder_division_by_zero)
10306                             << IsDiv << RHS.get()->getSourceRange());
10307 }
10308 
10309 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10310                                            SourceLocation Loc,
10311                                            bool IsCompAssign, bool IsDiv) {
10312   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10313 
10314   QualType LHSTy = LHS.get()->getType();
10315   QualType RHSTy = RHS.get()->getType();
10316   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10317     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10318                                /*AllowBothBool*/getLangOpts().AltiVec,
10319                                /*AllowBoolConversions*/false);
10320   if (!IsDiv &&
10321       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10322     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10323   // For division, only matrix-by-scalar is supported. Other combinations with
10324   // matrix types are invalid.
10325   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10326     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10327 
10328   QualType compType = UsualArithmeticConversions(
10329       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10330   if (LHS.isInvalid() || RHS.isInvalid())
10331     return QualType();
10332 
10333 
10334   if (compType.isNull() || !compType->isArithmeticType())
10335     return InvalidOperands(Loc, LHS, RHS);
10336   if (IsDiv) {
10337     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10338     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10339   }
10340   return compType;
10341 }
10342 
10343 QualType Sema::CheckRemainderOperands(
10344   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10345   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10346 
10347   if (LHS.get()->getType()->isVectorType() ||
10348       RHS.get()->getType()->isVectorType()) {
10349     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10350         RHS.get()->getType()->hasIntegerRepresentation())
10351       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10352                                  /*AllowBothBool*/getLangOpts().AltiVec,
10353                                  /*AllowBoolConversions*/false);
10354     return InvalidOperands(Loc, LHS, RHS);
10355   }
10356 
10357   QualType compType = UsualArithmeticConversions(
10358       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10359   if (LHS.isInvalid() || RHS.isInvalid())
10360     return QualType();
10361 
10362   if (compType.isNull() || !compType->isIntegerType())
10363     return InvalidOperands(Loc, LHS, RHS);
10364   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10365   return compType;
10366 }
10367 
10368 /// Diagnose invalid arithmetic on two void pointers.
10369 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10370                                                 Expr *LHSExpr, Expr *RHSExpr) {
10371   S.Diag(Loc, S.getLangOpts().CPlusPlus
10372                 ? diag::err_typecheck_pointer_arith_void_type
10373                 : diag::ext_gnu_void_ptr)
10374     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10375                             << RHSExpr->getSourceRange();
10376 }
10377 
10378 /// Diagnose invalid arithmetic on a void pointer.
10379 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10380                                             Expr *Pointer) {
10381   S.Diag(Loc, S.getLangOpts().CPlusPlus
10382                 ? diag::err_typecheck_pointer_arith_void_type
10383                 : diag::ext_gnu_void_ptr)
10384     << 0 /* one pointer */ << Pointer->getSourceRange();
10385 }
10386 
10387 /// Diagnose invalid arithmetic on a null pointer.
10388 ///
10389 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10390 /// idiom, which we recognize as a GNU extension.
10391 ///
10392 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10393                                             Expr *Pointer, bool IsGNUIdiom) {
10394   if (IsGNUIdiom)
10395     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10396       << Pointer->getSourceRange();
10397   else
10398     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10399       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10400 }
10401 
10402 /// Diagnose invalid arithmetic on two function pointers.
10403 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10404                                                     Expr *LHS, Expr *RHS) {
10405   assert(LHS->getType()->isAnyPointerType());
10406   assert(RHS->getType()->isAnyPointerType());
10407   S.Diag(Loc, S.getLangOpts().CPlusPlus
10408                 ? diag::err_typecheck_pointer_arith_function_type
10409                 : diag::ext_gnu_ptr_func_arith)
10410     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10411     // We only show the second type if it differs from the first.
10412     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10413                                                    RHS->getType())
10414     << RHS->getType()->getPointeeType()
10415     << LHS->getSourceRange() << RHS->getSourceRange();
10416 }
10417 
10418 /// Diagnose invalid arithmetic on a function pointer.
10419 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10420                                                 Expr *Pointer) {
10421   assert(Pointer->getType()->isAnyPointerType());
10422   S.Diag(Loc, S.getLangOpts().CPlusPlus
10423                 ? diag::err_typecheck_pointer_arith_function_type
10424                 : diag::ext_gnu_ptr_func_arith)
10425     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10426     << 0 /* one pointer, so only one type */
10427     << Pointer->getSourceRange();
10428 }
10429 
10430 /// Emit error if Operand is incomplete pointer type
10431 ///
10432 /// \returns True if pointer has incomplete type
10433 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10434                                                  Expr *Operand) {
10435   QualType ResType = Operand->getType();
10436   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10437     ResType = ResAtomicType->getValueType();
10438 
10439   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10440   QualType PointeeTy = ResType->getPointeeType();
10441   return S.RequireCompleteSizedType(
10442       Loc, PointeeTy,
10443       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10444       Operand->getSourceRange());
10445 }
10446 
10447 /// Check the validity of an arithmetic pointer operand.
10448 ///
10449 /// If the operand has pointer type, this code will check for pointer types
10450 /// which are invalid in arithmetic operations. These will be diagnosed
10451 /// appropriately, including whether or not the use is supported as an
10452 /// extension.
10453 ///
10454 /// \returns True when the operand is valid to use (even if as an extension).
10455 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10456                                             Expr *Operand) {
10457   QualType ResType = Operand->getType();
10458   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10459     ResType = ResAtomicType->getValueType();
10460 
10461   if (!ResType->isAnyPointerType()) return true;
10462 
10463   QualType PointeeTy = ResType->getPointeeType();
10464   if (PointeeTy->isVoidType()) {
10465     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10466     return !S.getLangOpts().CPlusPlus;
10467   }
10468   if (PointeeTy->isFunctionType()) {
10469     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10470     return !S.getLangOpts().CPlusPlus;
10471   }
10472 
10473   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10474 
10475   return true;
10476 }
10477 
10478 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10479 /// operands.
10480 ///
10481 /// This routine will diagnose any invalid arithmetic on pointer operands much
10482 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10483 /// for emitting a single diagnostic even for operations where both LHS and RHS
10484 /// are (potentially problematic) pointers.
10485 ///
10486 /// \returns True when the operand is valid to use (even if as an extension).
10487 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10488                                                 Expr *LHSExpr, Expr *RHSExpr) {
10489   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10490   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10491   if (!isLHSPointer && !isRHSPointer) return true;
10492 
10493   QualType LHSPointeeTy, RHSPointeeTy;
10494   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10495   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10496 
10497   // if both are pointers check if operation is valid wrt address spaces
10498   if (isLHSPointer && isRHSPointer) {
10499     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10500       S.Diag(Loc,
10501              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10502           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10503           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10504       return false;
10505     }
10506   }
10507 
10508   // Check for arithmetic on pointers to incomplete types.
10509   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10510   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10511   if (isLHSVoidPtr || isRHSVoidPtr) {
10512     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10513     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10514     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10515 
10516     return !S.getLangOpts().CPlusPlus;
10517   }
10518 
10519   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10520   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10521   if (isLHSFuncPtr || isRHSFuncPtr) {
10522     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10523     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10524                                                                 RHSExpr);
10525     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10526 
10527     return !S.getLangOpts().CPlusPlus;
10528   }
10529 
10530   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10531     return false;
10532   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10533     return false;
10534 
10535   return true;
10536 }
10537 
10538 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10539 /// literal.
10540 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10541                                   Expr *LHSExpr, Expr *RHSExpr) {
10542   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10543   Expr* IndexExpr = RHSExpr;
10544   if (!StrExpr) {
10545     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10546     IndexExpr = LHSExpr;
10547   }
10548 
10549   bool IsStringPlusInt = StrExpr &&
10550       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10551   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10552     return;
10553 
10554   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10555   Self.Diag(OpLoc, diag::warn_string_plus_int)
10556       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10557 
10558   // Only print a fixit for "str" + int, not for int + "str".
10559   if (IndexExpr == RHSExpr) {
10560     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10561     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10562         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10563         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10564         << FixItHint::CreateInsertion(EndLoc, "]");
10565   } else
10566     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10567 }
10568 
10569 /// Emit a warning when adding a char literal to a string.
10570 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10571                                    Expr *LHSExpr, Expr *RHSExpr) {
10572   const Expr *StringRefExpr = LHSExpr;
10573   const CharacterLiteral *CharExpr =
10574       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10575 
10576   if (!CharExpr) {
10577     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10578     StringRefExpr = RHSExpr;
10579   }
10580 
10581   if (!CharExpr || !StringRefExpr)
10582     return;
10583 
10584   const QualType StringType = StringRefExpr->getType();
10585 
10586   // Return if not a PointerType.
10587   if (!StringType->isAnyPointerType())
10588     return;
10589 
10590   // Return if not a CharacterType.
10591   if (!StringType->getPointeeType()->isAnyCharacterType())
10592     return;
10593 
10594   ASTContext &Ctx = Self.getASTContext();
10595   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10596 
10597   const QualType CharType = CharExpr->getType();
10598   if (!CharType->isAnyCharacterType() &&
10599       CharType->isIntegerType() &&
10600       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10601     Self.Diag(OpLoc, diag::warn_string_plus_char)
10602         << DiagRange << Ctx.CharTy;
10603   } else {
10604     Self.Diag(OpLoc, diag::warn_string_plus_char)
10605         << DiagRange << CharExpr->getType();
10606   }
10607 
10608   // Only print a fixit for str + char, not for char + str.
10609   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10610     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10611     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10612         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10613         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10614         << FixItHint::CreateInsertion(EndLoc, "]");
10615   } else {
10616     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10617   }
10618 }
10619 
10620 /// Emit error when two pointers are incompatible.
10621 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10622                                            Expr *LHSExpr, Expr *RHSExpr) {
10623   assert(LHSExpr->getType()->isAnyPointerType());
10624   assert(RHSExpr->getType()->isAnyPointerType());
10625   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10626     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10627     << RHSExpr->getSourceRange();
10628 }
10629 
10630 // C99 6.5.6
10631 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10632                                      SourceLocation Loc, BinaryOperatorKind Opc,
10633                                      QualType* CompLHSTy) {
10634   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10635 
10636   if (LHS.get()->getType()->isVectorType() ||
10637       RHS.get()->getType()->isVectorType()) {
10638     QualType compType = CheckVectorOperands(
10639         LHS, RHS, Loc, CompLHSTy,
10640         /*AllowBothBool*/getLangOpts().AltiVec,
10641         /*AllowBoolConversions*/getLangOpts().ZVector);
10642     if (CompLHSTy) *CompLHSTy = compType;
10643     return compType;
10644   }
10645 
10646   if (LHS.get()->getType()->isConstantMatrixType() ||
10647       RHS.get()->getType()->isConstantMatrixType()) {
10648     QualType compType =
10649         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10650     if (CompLHSTy)
10651       *CompLHSTy = compType;
10652     return compType;
10653   }
10654 
10655   QualType compType = UsualArithmeticConversions(
10656       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10657   if (LHS.isInvalid() || RHS.isInvalid())
10658     return QualType();
10659 
10660   // Diagnose "string literal" '+' int and string '+' "char literal".
10661   if (Opc == BO_Add) {
10662     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10663     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10664   }
10665 
10666   // handle the common case first (both operands are arithmetic).
10667   if (!compType.isNull() && compType->isArithmeticType()) {
10668     if (CompLHSTy) *CompLHSTy = compType;
10669     return compType;
10670   }
10671 
10672   // Type-checking.  Ultimately the pointer's going to be in PExp;
10673   // note that we bias towards the LHS being the pointer.
10674   Expr *PExp = LHS.get(), *IExp = RHS.get();
10675 
10676   bool isObjCPointer;
10677   if (PExp->getType()->isPointerType()) {
10678     isObjCPointer = false;
10679   } else if (PExp->getType()->isObjCObjectPointerType()) {
10680     isObjCPointer = true;
10681   } else {
10682     std::swap(PExp, IExp);
10683     if (PExp->getType()->isPointerType()) {
10684       isObjCPointer = false;
10685     } else if (PExp->getType()->isObjCObjectPointerType()) {
10686       isObjCPointer = true;
10687     } else {
10688       return InvalidOperands(Loc, LHS, RHS);
10689     }
10690   }
10691   assert(PExp->getType()->isAnyPointerType());
10692 
10693   if (!IExp->getType()->isIntegerType())
10694     return InvalidOperands(Loc, LHS, RHS);
10695 
10696   // Adding to a null pointer results in undefined behavior.
10697   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10698           Context, Expr::NPC_ValueDependentIsNotNull)) {
10699     // In C++ adding zero to a null pointer is defined.
10700     Expr::EvalResult KnownVal;
10701     if (!getLangOpts().CPlusPlus ||
10702         (!IExp->isValueDependent() &&
10703          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10704           KnownVal.Val.getInt() != 0))) {
10705       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10706       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10707           Context, BO_Add, PExp, IExp);
10708       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10709     }
10710   }
10711 
10712   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10713     return QualType();
10714 
10715   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10716     return QualType();
10717 
10718   // Check array bounds for pointer arithemtic
10719   CheckArrayAccess(PExp, IExp);
10720 
10721   if (CompLHSTy) {
10722     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10723     if (LHSTy.isNull()) {
10724       LHSTy = LHS.get()->getType();
10725       if (LHSTy->isPromotableIntegerType())
10726         LHSTy = Context.getPromotedIntegerType(LHSTy);
10727     }
10728     *CompLHSTy = LHSTy;
10729   }
10730 
10731   return PExp->getType();
10732 }
10733 
10734 // C99 6.5.6
10735 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10736                                         SourceLocation Loc,
10737                                         QualType* CompLHSTy) {
10738   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10739 
10740   if (LHS.get()->getType()->isVectorType() ||
10741       RHS.get()->getType()->isVectorType()) {
10742     QualType compType = CheckVectorOperands(
10743         LHS, RHS, Loc, CompLHSTy,
10744         /*AllowBothBool*/getLangOpts().AltiVec,
10745         /*AllowBoolConversions*/getLangOpts().ZVector);
10746     if (CompLHSTy) *CompLHSTy = compType;
10747     return compType;
10748   }
10749 
10750   if (LHS.get()->getType()->isConstantMatrixType() ||
10751       RHS.get()->getType()->isConstantMatrixType()) {
10752     QualType compType =
10753         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10754     if (CompLHSTy)
10755       *CompLHSTy = compType;
10756     return compType;
10757   }
10758 
10759   QualType compType = UsualArithmeticConversions(
10760       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10761   if (LHS.isInvalid() || RHS.isInvalid())
10762     return QualType();
10763 
10764   // Enforce type constraints: C99 6.5.6p3.
10765 
10766   // Handle the common case first (both operands are arithmetic).
10767   if (!compType.isNull() && compType->isArithmeticType()) {
10768     if (CompLHSTy) *CompLHSTy = compType;
10769     return compType;
10770   }
10771 
10772   // Either ptr - int   or   ptr - ptr.
10773   if (LHS.get()->getType()->isAnyPointerType()) {
10774     QualType lpointee = LHS.get()->getType()->getPointeeType();
10775 
10776     // Diagnose bad cases where we step over interface counts.
10777     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10778         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10779       return QualType();
10780 
10781     // The result type of a pointer-int computation is the pointer type.
10782     if (RHS.get()->getType()->isIntegerType()) {
10783       // Subtracting from a null pointer should produce a warning.
10784       // The last argument to the diagnose call says this doesn't match the
10785       // GNU int-to-pointer idiom.
10786       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10787                                            Expr::NPC_ValueDependentIsNotNull)) {
10788         // In C++ adding zero to a null pointer is defined.
10789         Expr::EvalResult KnownVal;
10790         if (!getLangOpts().CPlusPlus ||
10791             (!RHS.get()->isValueDependent() &&
10792              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10793               KnownVal.Val.getInt() != 0))) {
10794           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10795         }
10796       }
10797 
10798       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10799         return QualType();
10800 
10801       // Check array bounds for pointer arithemtic
10802       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10803                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10804 
10805       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10806       return LHS.get()->getType();
10807     }
10808 
10809     // Handle pointer-pointer subtractions.
10810     if (const PointerType *RHSPTy
10811           = RHS.get()->getType()->getAs<PointerType>()) {
10812       QualType rpointee = RHSPTy->getPointeeType();
10813 
10814       if (getLangOpts().CPlusPlus) {
10815         // Pointee types must be the same: C++ [expr.add]
10816         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10817           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10818         }
10819       } else {
10820         // Pointee types must be compatible C99 6.5.6p3
10821         if (!Context.typesAreCompatible(
10822                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10823                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10824           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10825           return QualType();
10826         }
10827       }
10828 
10829       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10830                                                LHS.get(), RHS.get()))
10831         return QualType();
10832 
10833       // FIXME: Add warnings for nullptr - ptr.
10834 
10835       // The pointee type may have zero size.  As an extension, a structure or
10836       // union may have zero size or an array may have zero length.  In this
10837       // case subtraction does not make sense.
10838       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10839         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10840         if (ElementSize.isZero()) {
10841           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10842             << rpointee.getUnqualifiedType()
10843             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10844         }
10845       }
10846 
10847       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10848       return Context.getPointerDiffType();
10849     }
10850   }
10851 
10852   return InvalidOperands(Loc, LHS, RHS);
10853 }
10854 
10855 static bool isScopedEnumerationType(QualType T) {
10856   if (const EnumType *ET = T->getAs<EnumType>())
10857     return ET->getDecl()->isScoped();
10858   return false;
10859 }
10860 
10861 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10862                                    SourceLocation Loc, BinaryOperatorKind Opc,
10863                                    QualType LHSType) {
10864   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10865   // so skip remaining warnings as we don't want to modify values within Sema.
10866   if (S.getLangOpts().OpenCL)
10867     return;
10868 
10869   // Check right/shifter operand
10870   Expr::EvalResult RHSResult;
10871   if (RHS.get()->isValueDependent() ||
10872       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10873     return;
10874   llvm::APSInt Right = RHSResult.Val.getInt();
10875 
10876   if (Right.isNegative()) {
10877     S.DiagRuntimeBehavior(Loc, RHS.get(),
10878                           S.PDiag(diag::warn_shift_negative)
10879                             << RHS.get()->getSourceRange());
10880     return;
10881   }
10882 
10883   QualType LHSExprType = LHS.get()->getType();
10884   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10885   if (LHSExprType->isExtIntType())
10886     LeftSize = S.Context.getIntWidth(LHSExprType);
10887   else if (LHSExprType->isFixedPointType()) {
10888     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10889     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10890   }
10891   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10892   if (Right.uge(LeftBits)) {
10893     S.DiagRuntimeBehavior(Loc, RHS.get(),
10894                           S.PDiag(diag::warn_shift_gt_typewidth)
10895                             << RHS.get()->getSourceRange());
10896     return;
10897   }
10898 
10899   // FIXME: We probably need to handle fixed point types specially here.
10900   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10901     return;
10902 
10903   // When left shifting an ICE which is signed, we can check for overflow which
10904   // according to C++ standards prior to C++2a has undefined behavior
10905   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10906   // more than the maximum value representable in the result type, so never
10907   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10908   // expression is still probably a bug.)
10909   Expr::EvalResult LHSResult;
10910   if (LHS.get()->isValueDependent() ||
10911       LHSType->hasUnsignedIntegerRepresentation() ||
10912       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10913     return;
10914   llvm::APSInt Left = LHSResult.Val.getInt();
10915 
10916   // If LHS does not have a signed type and non-negative value
10917   // then, the behavior is undefined before C++2a. Warn about it.
10918   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10919       !S.getLangOpts().CPlusPlus20) {
10920     S.DiagRuntimeBehavior(Loc, LHS.get(),
10921                           S.PDiag(diag::warn_shift_lhs_negative)
10922                             << LHS.get()->getSourceRange());
10923     return;
10924   }
10925 
10926   llvm::APInt ResultBits =
10927       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10928   if (LeftBits.uge(ResultBits))
10929     return;
10930   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10931   Result = Result.shl(Right);
10932 
10933   // Print the bit representation of the signed integer as an unsigned
10934   // hexadecimal number.
10935   SmallString<40> HexResult;
10936   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10937 
10938   // If we are only missing a sign bit, this is less likely to result in actual
10939   // bugs -- if the result is cast back to an unsigned type, it will have the
10940   // expected value. Thus we place this behind a different warning that can be
10941   // turned off separately if needed.
10942   if (LeftBits == ResultBits - 1) {
10943     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10944         << HexResult << LHSType
10945         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10946     return;
10947   }
10948 
10949   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10950     << HexResult.str() << Result.getMinSignedBits() << LHSType
10951     << Left.getBitWidth() << LHS.get()->getSourceRange()
10952     << RHS.get()->getSourceRange();
10953 }
10954 
10955 /// Return the resulting type when a vector is shifted
10956 ///        by a scalar or vector shift amount.
10957 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10958                                  SourceLocation Loc, bool IsCompAssign) {
10959   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10960   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10961       !LHS.get()->getType()->isVectorType()) {
10962     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10963       << RHS.get()->getType() << LHS.get()->getType()
10964       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10965     return QualType();
10966   }
10967 
10968   if (!IsCompAssign) {
10969     LHS = S.UsualUnaryConversions(LHS.get());
10970     if (LHS.isInvalid()) return QualType();
10971   }
10972 
10973   RHS = S.UsualUnaryConversions(RHS.get());
10974   if (RHS.isInvalid()) return QualType();
10975 
10976   QualType LHSType = LHS.get()->getType();
10977   // Note that LHS might be a scalar because the routine calls not only in
10978   // OpenCL case.
10979   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10980   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10981 
10982   // Note that RHS might not be a vector.
10983   QualType RHSType = RHS.get()->getType();
10984   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10985   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10986 
10987   // The operands need to be integers.
10988   if (!LHSEleType->isIntegerType()) {
10989     S.Diag(Loc, diag::err_typecheck_expect_int)
10990       << LHS.get()->getType() << LHS.get()->getSourceRange();
10991     return QualType();
10992   }
10993 
10994   if (!RHSEleType->isIntegerType()) {
10995     S.Diag(Loc, diag::err_typecheck_expect_int)
10996       << RHS.get()->getType() << RHS.get()->getSourceRange();
10997     return QualType();
10998   }
10999 
11000   if (!LHSVecTy) {
11001     assert(RHSVecTy);
11002     if (IsCompAssign)
11003       return RHSType;
11004     if (LHSEleType != RHSEleType) {
11005       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11006       LHSEleType = RHSEleType;
11007     }
11008     QualType VecTy =
11009         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11010     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11011     LHSType = VecTy;
11012   } else if (RHSVecTy) {
11013     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11014     // are applied component-wise. So if RHS is a vector, then ensure
11015     // that the number of elements is the same as LHS...
11016     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11017       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11018         << LHS.get()->getType() << RHS.get()->getType()
11019         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11020       return QualType();
11021     }
11022     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11023       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11024       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11025       if (LHSBT != RHSBT &&
11026           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11027         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11028             << LHS.get()->getType() << RHS.get()->getType()
11029             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11030       }
11031     }
11032   } else {
11033     // ...else expand RHS to match the number of elements in LHS.
11034     QualType VecTy =
11035       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11036     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11037   }
11038 
11039   return LHSType;
11040 }
11041 
11042 // C99 6.5.7
11043 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11044                                   SourceLocation Loc, BinaryOperatorKind Opc,
11045                                   bool IsCompAssign) {
11046   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11047 
11048   // Vector shifts promote their scalar inputs to vector type.
11049   if (LHS.get()->getType()->isVectorType() ||
11050       RHS.get()->getType()->isVectorType()) {
11051     if (LangOpts.ZVector) {
11052       // The shift operators for the z vector extensions work basically
11053       // like general shifts, except that neither the LHS nor the RHS is
11054       // allowed to be a "vector bool".
11055       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11056         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11057           return InvalidOperands(Loc, LHS, RHS);
11058       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11059         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11060           return InvalidOperands(Loc, LHS, RHS);
11061     }
11062     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11063   }
11064 
11065   // Shifts don't perform usual arithmetic conversions, they just do integer
11066   // promotions on each operand. C99 6.5.7p3
11067 
11068   // For the LHS, do usual unary conversions, but then reset them away
11069   // if this is a compound assignment.
11070   ExprResult OldLHS = LHS;
11071   LHS = UsualUnaryConversions(LHS.get());
11072   if (LHS.isInvalid())
11073     return QualType();
11074   QualType LHSType = LHS.get()->getType();
11075   if (IsCompAssign) LHS = OldLHS;
11076 
11077   // The RHS is simpler.
11078   RHS = UsualUnaryConversions(RHS.get());
11079   if (RHS.isInvalid())
11080     return QualType();
11081   QualType RHSType = RHS.get()->getType();
11082 
11083   // C99 6.5.7p2: Each of the operands shall have integer type.
11084   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11085   if ((!LHSType->isFixedPointOrIntegerType() &&
11086        !LHSType->hasIntegerRepresentation()) ||
11087       !RHSType->hasIntegerRepresentation())
11088     return InvalidOperands(Loc, LHS, RHS);
11089 
11090   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11091   // hasIntegerRepresentation() above instead of this.
11092   if (isScopedEnumerationType(LHSType) ||
11093       isScopedEnumerationType(RHSType)) {
11094     return InvalidOperands(Loc, LHS, RHS);
11095   }
11096   // Sanity-check shift operands
11097   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11098 
11099   // "The type of the result is that of the promoted left operand."
11100   return LHSType;
11101 }
11102 
11103 /// Diagnose bad pointer comparisons.
11104 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11105                                               ExprResult &LHS, ExprResult &RHS,
11106                                               bool IsError) {
11107   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11108                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11109     << LHS.get()->getType() << RHS.get()->getType()
11110     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11111 }
11112 
11113 /// Returns false if the pointers are converted to a composite type,
11114 /// true otherwise.
11115 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11116                                            ExprResult &LHS, ExprResult &RHS) {
11117   // C++ [expr.rel]p2:
11118   //   [...] Pointer conversions (4.10) and qualification
11119   //   conversions (4.4) are performed on pointer operands (or on
11120   //   a pointer operand and a null pointer constant) to bring
11121   //   them to their composite pointer type. [...]
11122   //
11123   // C++ [expr.eq]p1 uses the same notion for (in)equality
11124   // comparisons of pointers.
11125 
11126   QualType LHSType = LHS.get()->getType();
11127   QualType RHSType = RHS.get()->getType();
11128   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11129          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11130 
11131   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11132   if (T.isNull()) {
11133     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11134         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11135       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11136     else
11137       S.InvalidOperands(Loc, LHS, RHS);
11138     return true;
11139   }
11140 
11141   return false;
11142 }
11143 
11144 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11145                                                     ExprResult &LHS,
11146                                                     ExprResult &RHS,
11147                                                     bool IsError) {
11148   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11149                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11150     << LHS.get()->getType() << RHS.get()->getType()
11151     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11152 }
11153 
11154 static bool isObjCObjectLiteral(ExprResult &E) {
11155   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11156   case Stmt::ObjCArrayLiteralClass:
11157   case Stmt::ObjCDictionaryLiteralClass:
11158   case Stmt::ObjCStringLiteralClass:
11159   case Stmt::ObjCBoxedExprClass:
11160     return true;
11161   default:
11162     // Note that ObjCBoolLiteral is NOT an object literal!
11163     return false;
11164   }
11165 }
11166 
11167 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11168   const ObjCObjectPointerType *Type =
11169     LHS->getType()->getAs<ObjCObjectPointerType>();
11170 
11171   // If this is not actually an Objective-C object, bail out.
11172   if (!Type)
11173     return false;
11174 
11175   // Get the LHS object's interface type.
11176   QualType InterfaceType = Type->getPointeeType();
11177 
11178   // If the RHS isn't an Objective-C object, bail out.
11179   if (!RHS->getType()->isObjCObjectPointerType())
11180     return false;
11181 
11182   // Try to find the -isEqual: method.
11183   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11184   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11185                                                       InterfaceType,
11186                                                       /*IsInstance=*/true);
11187   if (!Method) {
11188     if (Type->isObjCIdType()) {
11189       // For 'id', just check the global pool.
11190       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11191                                                   /*receiverId=*/true);
11192     } else {
11193       // Check protocols.
11194       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11195                                              /*IsInstance=*/true);
11196     }
11197   }
11198 
11199   if (!Method)
11200     return false;
11201 
11202   QualType T = Method->parameters()[0]->getType();
11203   if (!T->isObjCObjectPointerType())
11204     return false;
11205 
11206   QualType R = Method->getReturnType();
11207   if (!R->isScalarType())
11208     return false;
11209 
11210   return true;
11211 }
11212 
11213 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11214   FromE = FromE->IgnoreParenImpCasts();
11215   switch (FromE->getStmtClass()) {
11216     default:
11217       break;
11218     case Stmt::ObjCStringLiteralClass:
11219       // "string literal"
11220       return LK_String;
11221     case Stmt::ObjCArrayLiteralClass:
11222       // "array literal"
11223       return LK_Array;
11224     case Stmt::ObjCDictionaryLiteralClass:
11225       // "dictionary literal"
11226       return LK_Dictionary;
11227     case Stmt::BlockExprClass:
11228       return LK_Block;
11229     case Stmt::ObjCBoxedExprClass: {
11230       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11231       switch (Inner->getStmtClass()) {
11232         case Stmt::IntegerLiteralClass:
11233         case Stmt::FloatingLiteralClass:
11234         case Stmt::CharacterLiteralClass:
11235         case Stmt::ObjCBoolLiteralExprClass:
11236         case Stmt::CXXBoolLiteralExprClass:
11237           // "numeric literal"
11238           return LK_Numeric;
11239         case Stmt::ImplicitCastExprClass: {
11240           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11241           // Boolean literals can be represented by implicit casts.
11242           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11243             return LK_Numeric;
11244           break;
11245         }
11246         default:
11247           break;
11248       }
11249       return LK_Boxed;
11250     }
11251   }
11252   return LK_None;
11253 }
11254 
11255 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11256                                           ExprResult &LHS, ExprResult &RHS,
11257                                           BinaryOperator::Opcode Opc){
11258   Expr *Literal;
11259   Expr *Other;
11260   if (isObjCObjectLiteral(LHS)) {
11261     Literal = LHS.get();
11262     Other = RHS.get();
11263   } else {
11264     Literal = RHS.get();
11265     Other = LHS.get();
11266   }
11267 
11268   // Don't warn on comparisons against nil.
11269   Other = Other->IgnoreParenCasts();
11270   if (Other->isNullPointerConstant(S.getASTContext(),
11271                                    Expr::NPC_ValueDependentIsNotNull))
11272     return;
11273 
11274   // This should be kept in sync with warn_objc_literal_comparison.
11275   // LK_String should always be after the other literals, since it has its own
11276   // warning flag.
11277   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11278   assert(LiteralKind != Sema::LK_Block);
11279   if (LiteralKind == Sema::LK_None) {
11280     llvm_unreachable("Unknown Objective-C object literal kind");
11281   }
11282 
11283   if (LiteralKind == Sema::LK_String)
11284     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11285       << Literal->getSourceRange();
11286   else
11287     S.Diag(Loc, diag::warn_objc_literal_comparison)
11288       << LiteralKind << Literal->getSourceRange();
11289 
11290   if (BinaryOperator::isEqualityOp(Opc) &&
11291       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11292     SourceLocation Start = LHS.get()->getBeginLoc();
11293     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11294     CharSourceRange OpRange =
11295       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11296 
11297     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11298       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11299       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11300       << FixItHint::CreateInsertion(End, "]");
11301   }
11302 }
11303 
11304 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11305 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11306                                            ExprResult &RHS, SourceLocation Loc,
11307                                            BinaryOperatorKind Opc) {
11308   // Check that left hand side is !something.
11309   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11310   if (!UO || UO->getOpcode() != UO_LNot) return;
11311 
11312   // Only check if the right hand side is non-bool arithmetic type.
11313   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11314 
11315   // Make sure that the something in !something is not bool.
11316   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11317   if (SubExpr->isKnownToHaveBooleanValue()) return;
11318 
11319   // Emit warning.
11320   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11321   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11322       << Loc << IsBitwiseOp;
11323 
11324   // First note suggest !(x < y)
11325   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11326   SourceLocation FirstClose = RHS.get()->getEndLoc();
11327   FirstClose = S.getLocForEndOfToken(FirstClose);
11328   if (FirstClose.isInvalid())
11329     FirstOpen = SourceLocation();
11330   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11331       << IsBitwiseOp
11332       << FixItHint::CreateInsertion(FirstOpen, "(")
11333       << FixItHint::CreateInsertion(FirstClose, ")");
11334 
11335   // Second note suggests (!x) < y
11336   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11337   SourceLocation SecondClose = LHS.get()->getEndLoc();
11338   SecondClose = S.getLocForEndOfToken(SecondClose);
11339   if (SecondClose.isInvalid())
11340     SecondOpen = SourceLocation();
11341   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11342       << FixItHint::CreateInsertion(SecondOpen, "(")
11343       << FixItHint::CreateInsertion(SecondClose, ")");
11344 }
11345 
11346 // Returns true if E refers to a non-weak array.
11347 static bool checkForArray(const Expr *E) {
11348   const ValueDecl *D = nullptr;
11349   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11350     D = DR->getDecl();
11351   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11352     if (Mem->isImplicitAccess())
11353       D = Mem->getMemberDecl();
11354   }
11355   if (!D)
11356     return false;
11357   return D->getType()->isArrayType() && !D->isWeak();
11358 }
11359 
11360 /// Diagnose some forms of syntactically-obvious tautological comparison.
11361 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11362                                            Expr *LHS, Expr *RHS,
11363                                            BinaryOperatorKind Opc) {
11364   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11365   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11366 
11367   QualType LHSType = LHS->getType();
11368   QualType RHSType = RHS->getType();
11369   if (LHSType->hasFloatingRepresentation() ||
11370       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11371       S.inTemplateInstantiation())
11372     return;
11373 
11374   // Comparisons between two array types are ill-formed for operator<=>, so
11375   // we shouldn't emit any additional warnings about it.
11376   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11377     return;
11378 
11379   // For non-floating point types, check for self-comparisons of the form
11380   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11381   // often indicate logic errors in the program.
11382   //
11383   // NOTE: Don't warn about comparison expressions resulting from macro
11384   // expansion. Also don't warn about comparisons which are only self
11385   // comparisons within a template instantiation. The warnings should catch
11386   // obvious cases in the definition of the template anyways. The idea is to
11387   // warn when the typed comparison operator will always evaluate to the same
11388   // result.
11389 
11390   // Used for indexing into %select in warn_comparison_always
11391   enum {
11392     AlwaysConstant,
11393     AlwaysTrue,
11394     AlwaysFalse,
11395     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11396   };
11397 
11398   // C++2a [depr.array.comp]:
11399   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11400   //   operands of array type are deprecated.
11401   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11402       RHSStripped->getType()->isArrayType()) {
11403     S.Diag(Loc, diag::warn_depr_array_comparison)
11404         << LHS->getSourceRange() << RHS->getSourceRange()
11405         << LHSStripped->getType() << RHSStripped->getType();
11406     // Carry on to produce the tautological comparison warning, if this
11407     // expression is potentially-evaluated, we can resolve the array to a
11408     // non-weak declaration, and so on.
11409   }
11410 
11411   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11412     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11413       unsigned Result;
11414       switch (Opc) {
11415       case BO_EQ:
11416       case BO_LE:
11417       case BO_GE:
11418         Result = AlwaysTrue;
11419         break;
11420       case BO_NE:
11421       case BO_LT:
11422       case BO_GT:
11423         Result = AlwaysFalse;
11424         break;
11425       case BO_Cmp:
11426         Result = AlwaysEqual;
11427         break;
11428       default:
11429         Result = AlwaysConstant;
11430         break;
11431       }
11432       S.DiagRuntimeBehavior(Loc, nullptr,
11433                             S.PDiag(diag::warn_comparison_always)
11434                                 << 0 /*self-comparison*/
11435                                 << Result);
11436     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11437       // What is it always going to evaluate to?
11438       unsigned Result;
11439       switch (Opc) {
11440       case BO_EQ: // e.g. array1 == array2
11441         Result = AlwaysFalse;
11442         break;
11443       case BO_NE: // e.g. array1 != array2
11444         Result = AlwaysTrue;
11445         break;
11446       default: // e.g. array1 <= array2
11447         // The best we can say is 'a constant'
11448         Result = AlwaysConstant;
11449         break;
11450       }
11451       S.DiagRuntimeBehavior(Loc, nullptr,
11452                             S.PDiag(diag::warn_comparison_always)
11453                                 << 1 /*array comparison*/
11454                                 << Result);
11455     }
11456   }
11457 
11458   if (isa<CastExpr>(LHSStripped))
11459     LHSStripped = LHSStripped->IgnoreParenCasts();
11460   if (isa<CastExpr>(RHSStripped))
11461     RHSStripped = RHSStripped->IgnoreParenCasts();
11462 
11463   // Warn about comparisons against a string constant (unless the other
11464   // operand is null); the user probably wants string comparison function.
11465   Expr *LiteralString = nullptr;
11466   Expr *LiteralStringStripped = nullptr;
11467   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11468       !RHSStripped->isNullPointerConstant(S.Context,
11469                                           Expr::NPC_ValueDependentIsNull)) {
11470     LiteralString = LHS;
11471     LiteralStringStripped = LHSStripped;
11472   } else if ((isa<StringLiteral>(RHSStripped) ||
11473               isa<ObjCEncodeExpr>(RHSStripped)) &&
11474              !LHSStripped->isNullPointerConstant(S.Context,
11475                                           Expr::NPC_ValueDependentIsNull)) {
11476     LiteralString = RHS;
11477     LiteralStringStripped = RHSStripped;
11478   }
11479 
11480   if (LiteralString) {
11481     S.DiagRuntimeBehavior(Loc, nullptr,
11482                           S.PDiag(diag::warn_stringcompare)
11483                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11484                               << LiteralString->getSourceRange());
11485   }
11486 }
11487 
11488 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11489   switch (CK) {
11490   default: {
11491 #ifndef NDEBUG
11492     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11493                  << "\n";
11494 #endif
11495     llvm_unreachable("unhandled cast kind");
11496   }
11497   case CK_UserDefinedConversion:
11498     return ICK_Identity;
11499   case CK_LValueToRValue:
11500     return ICK_Lvalue_To_Rvalue;
11501   case CK_ArrayToPointerDecay:
11502     return ICK_Array_To_Pointer;
11503   case CK_FunctionToPointerDecay:
11504     return ICK_Function_To_Pointer;
11505   case CK_IntegralCast:
11506     return ICK_Integral_Conversion;
11507   case CK_FloatingCast:
11508     return ICK_Floating_Conversion;
11509   case CK_IntegralToFloating:
11510   case CK_FloatingToIntegral:
11511     return ICK_Floating_Integral;
11512   case CK_IntegralComplexCast:
11513   case CK_FloatingComplexCast:
11514   case CK_FloatingComplexToIntegralComplex:
11515   case CK_IntegralComplexToFloatingComplex:
11516     return ICK_Complex_Conversion;
11517   case CK_FloatingComplexToReal:
11518   case CK_FloatingRealToComplex:
11519   case CK_IntegralComplexToReal:
11520   case CK_IntegralRealToComplex:
11521     return ICK_Complex_Real;
11522   }
11523 }
11524 
11525 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11526                                              QualType FromType,
11527                                              SourceLocation Loc) {
11528   // Check for a narrowing implicit conversion.
11529   StandardConversionSequence SCS;
11530   SCS.setAsIdentityConversion();
11531   SCS.setToType(0, FromType);
11532   SCS.setToType(1, ToType);
11533   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11534     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11535 
11536   APValue PreNarrowingValue;
11537   QualType PreNarrowingType;
11538   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11539                                PreNarrowingType,
11540                                /*IgnoreFloatToIntegralConversion*/ true)) {
11541   case NK_Dependent_Narrowing:
11542     // Implicit conversion to a narrower type, but the expression is
11543     // value-dependent so we can't tell whether it's actually narrowing.
11544   case NK_Not_Narrowing:
11545     return false;
11546 
11547   case NK_Constant_Narrowing:
11548     // Implicit conversion to a narrower type, and the value is not a constant
11549     // expression.
11550     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11551         << /*Constant*/ 1
11552         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11553     return true;
11554 
11555   case NK_Variable_Narrowing:
11556     // Implicit conversion to a narrower type, and the value is not a constant
11557     // expression.
11558   case NK_Type_Narrowing:
11559     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11560         << /*Constant*/ 0 << FromType << ToType;
11561     // TODO: It's not a constant expression, but what if the user intended it
11562     // to be? Can we produce notes to help them figure out why it isn't?
11563     return true;
11564   }
11565   llvm_unreachable("unhandled case in switch");
11566 }
11567 
11568 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11569                                                          ExprResult &LHS,
11570                                                          ExprResult &RHS,
11571                                                          SourceLocation Loc) {
11572   QualType LHSType = LHS.get()->getType();
11573   QualType RHSType = RHS.get()->getType();
11574   // Dig out the original argument type and expression before implicit casts
11575   // were applied. These are the types/expressions we need to check the
11576   // [expr.spaceship] requirements against.
11577   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11578   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11579   QualType LHSStrippedType = LHSStripped.get()->getType();
11580   QualType RHSStrippedType = RHSStripped.get()->getType();
11581 
11582   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11583   // other is not, the program is ill-formed.
11584   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11585     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11586     return QualType();
11587   }
11588 
11589   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11590   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11591                     RHSStrippedType->isEnumeralType();
11592   if (NumEnumArgs == 1) {
11593     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11594     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11595     if (OtherTy->hasFloatingRepresentation()) {
11596       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11597       return QualType();
11598     }
11599   }
11600   if (NumEnumArgs == 2) {
11601     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11602     // type E, the operator yields the result of converting the operands
11603     // to the underlying type of E and applying <=> to the converted operands.
11604     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11605       S.InvalidOperands(Loc, LHS, RHS);
11606       return QualType();
11607     }
11608     QualType IntType =
11609         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11610     assert(IntType->isArithmeticType());
11611 
11612     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11613     // promote the boolean type, and all other promotable integer types, to
11614     // avoid this.
11615     if (IntType->isPromotableIntegerType())
11616       IntType = S.Context.getPromotedIntegerType(IntType);
11617 
11618     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11619     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11620     LHSType = RHSType = IntType;
11621   }
11622 
11623   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11624   // usual arithmetic conversions are applied to the operands.
11625   QualType Type =
11626       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11627   if (LHS.isInvalid() || RHS.isInvalid())
11628     return QualType();
11629   if (Type.isNull())
11630     return S.InvalidOperands(Loc, LHS, RHS);
11631 
11632   Optional<ComparisonCategoryType> CCT =
11633       getComparisonCategoryForBuiltinCmp(Type);
11634   if (!CCT)
11635     return S.InvalidOperands(Loc, LHS, RHS);
11636 
11637   bool HasNarrowing = checkThreeWayNarrowingConversion(
11638       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11639   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11640                                                    RHS.get()->getBeginLoc());
11641   if (HasNarrowing)
11642     return QualType();
11643 
11644   assert(!Type.isNull() && "composite type for <=> has not been set");
11645 
11646   return S.CheckComparisonCategoryType(
11647       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11648 }
11649 
11650 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11651                                                  ExprResult &RHS,
11652                                                  SourceLocation Loc,
11653                                                  BinaryOperatorKind Opc) {
11654   if (Opc == BO_Cmp)
11655     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11656 
11657   // C99 6.5.8p3 / C99 6.5.9p4
11658   QualType Type =
11659       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11660   if (LHS.isInvalid() || RHS.isInvalid())
11661     return QualType();
11662   if (Type.isNull())
11663     return S.InvalidOperands(Loc, LHS, RHS);
11664   assert(Type->isArithmeticType() || Type->isEnumeralType());
11665 
11666   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11667     return S.InvalidOperands(Loc, LHS, RHS);
11668 
11669   // Check for comparisons of floating point operands using != and ==.
11670   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11671     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11672 
11673   // The result of comparisons is 'bool' in C++, 'int' in C.
11674   return S.Context.getLogicalOperationType();
11675 }
11676 
11677 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11678   if (!NullE.get()->getType()->isAnyPointerType())
11679     return;
11680   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11681   if (!E.get()->getType()->isAnyPointerType() &&
11682       E.get()->isNullPointerConstant(Context,
11683                                      Expr::NPC_ValueDependentIsNotNull) ==
11684         Expr::NPCK_ZeroExpression) {
11685     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11686       if (CL->getValue() == 0)
11687         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11688             << NullValue
11689             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11690                                             NullValue ? "NULL" : "(void *)0");
11691     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11692         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11693         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11694         if (T == Context.CharTy)
11695           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11696               << NullValue
11697               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11698                                               NullValue ? "NULL" : "(void *)0");
11699       }
11700   }
11701 }
11702 
11703 // C99 6.5.8, C++ [expr.rel]
11704 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11705                                     SourceLocation Loc,
11706                                     BinaryOperatorKind Opc) {
11707   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11708   bool IsThreeWay = Opc == BO_Cmp;
11709   bool IsOrdered = IsRelational || IsThreeWay;
11710   auto IsAnyPointerType = [](ExprResult E) {
11711     QualType Ty = E.get()->getType();
11712     return Ty->isPointerType() || Ty->isMemberPointerType();
11713   };
11714 
11715   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11716   // type, array-to-pointer, ..., conversions are performed on both operands to
11717   // bring them to their composite type.
11718   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11719   // any type-related checks.
11720   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11721     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11722     if (LHS.isInvalid())
11723       return QualType();
11724     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11725     if (RHS.isInvalid())
11726       return QualType();
11727   } else {
11728     LHS = DefaultLvalueConversion(LHS.get());
11729     if (LHS.isInvalid())
11730       return QualType();
11731     RHS = DefaultLvalueConversion(RHS.get());
11732     if (RHS.isInvalid())
11733       return QualType();
11734   }
11735 
11736   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11737   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11738     CheckPtrComparisonWithNullChar(LHS, RHS);
11739     CheckPtrComparisonWithNullChar(RHS, LHS);
11740   }
11741 
11742   // Handle vector comparisons separately.
11743   if (LHS.get()->getType()->isVectorType() ||
11744       RHS.get()->getType()->isVectorType())
11745     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11746 
11747   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11748   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11749 
11750   QualType LHSType = LHS.get()->getType();
11751   QualType RHSType = RHS.get()->getType();
11752   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11753       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11754     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11755 
11756   const Expr::NullPointerConstantKind LHSNullKind =
11757       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11758   const Expr::NullPointerConstantKind RHSNullKind =
11759       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11760   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11761   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11762 
11763   auto computeResultTy = [&]() {
11764     if (Opc != BO_Cmp)
11765       return Context.getLogicalOperationType();
11766     assert(getLangOpts().CPlusPlus);
11767     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11768 
11769     QualType CompositeTy = LHS.get()->getType();
11770     assert(!CompositeTy->isReferenceType());
11771 
11772     Optional<ComparisonCategoryType> CCT =
11773         getComparisonCategoryForBuiltinCmp(CompositeTy);
11774     if (!CCT)
11775       return InvalidOperands(Loc, LHS, RHS);
11776 
11777     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11778       // P0946R0: Comparisons between a null pointer constant and an object
11779       // pointer result in std::strong_equality, which is ill-formed under
11780       // P1959R0.
11781       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11782           << (LHSIsNull ? LHS.get()->getSourceRange()
11783                         : RHS.get()->getSourceRange());
11784       return QualType();
11785     }
11786 
11787     return CheckComparisonCategoryType(
11788         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11789   };
11790 
11791   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11792     bool IsEquality = Opc == BO_EQ;
11793     if (RHSIsNull)
11794       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11795                                    RHS.get()->getSourceRange());
11796     else
11797       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11798                                    LHS.get()->getSourceRange());
11799   }
11800 
11801   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11802       (RHSType->isIntegerType() && !RHSIsNull)) {
11803     // Skip normal pointer conversion checks in this case; we have better
11804     // diagnostics for this below.
11805   } else if (getLangOpts().CPlusPlus) {
11806     // Equality comparison of a function pointer to a void pointer is invalid,
11807     // but we allow it as an extension.
11808     // FIXME: If we really want to allow this, should it be part of composite
11809     // pointer type computation so it works in conditionals too?
11810     if (!IsOrdered &&
11811         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11812          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11813       // This is a gcc extension compatibility comparison.
11814       // In a SFINAE context, we treat this as a hard error to maintain
11815       // conformance with the C++ standard.
11816       diagnoseFunctionPointerToVoidComparison(
11817           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11818 
11819       if (isSFINAEContext())
11820         return QualType();
11821 
11822       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11823       return computeResultTy();
11824     }
11825 
11826     // C++ [expr.eq]p2:
11827     //   If at least one operand is a pointer [...] bring them to their
11828     //   composite pointer type.
11829     // C++ [expr.spaceship]p6
11830     //  If at least one of the operands is of pointer type, [...] bring them
11831     //  to their composite pointer type.
11832     // C++ [expr.rel]p2:
11833     //   If both operands are pointers, [...] bring them to their composite
11834     //   pointer type.
11835     // For <=>, the only valid non-pointer types are arrays and functions, and
11836     // we already decayed those, so this is really the same as the relational
11837     // comparison rule.
11838     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11839             (IsOrdered ? 2 : 1) &&
11840         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11841                                          RHSType->isObjCObjectPointerType()))) {
11842       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11843         return QualType();
11844       return computeResultTy();
11845     }
11846   } else if (LHSType->isPointerType() &&
11847              RHSType->isPointerType()) { // C99 6.5.8p2
11848     // All of the following pointer-related warnings are GCC extensions, except
11849     // when handling null pointer constants.
11850     QualType LCanPointeeTy =
11851       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11852     QualType RCanPointeeTy =
11853       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11854 
11855     // C99 6.5.9p2 and C99 6.5.8p2
11856     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11857                                    RCanPointeeTy.getUnqualifiedType())) {
11858       if (IsRelational) {
11859         // Pointers both need to point to complete or incomplete types
11860         if ((LCanPointeeTy->isIncompleteType() !=
11861              RCanPointeeTy->isIncompleteType()) &&
11862             !getLangOpts().C11) {
11863           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11864               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11865               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11866               << RCanPointeeTy->isIncompleteType();
11867         }
11868         if (LCanPointeeTy->isFunctionType()) {
11869           // Valid unless a relational comparison of function pointers
11870           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11871               << LHSType << RHSType << LHS.get()->getSourceRange()
11872               << RHS.get()->getSourceRange();
11873         }
11874       }
11875     } else if (!IsRelational &&
11876                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11877       // Valid unless comparison between non-null pointer and function pointer
11878       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11879           && !LHSIsNull && !RHSIsNull)
11880         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11881                                                 /*isError*/false);
11882     } else {
11883       // Invalid
11884       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11885     }
11886     if (LCanPointeeTy != RCanPointeeTy) {
11887       // Treat NULL constant as a special case in OpenCL.
11888       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11889         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11890           Diag(Loc,
11891                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11892               << LHSType << RHSType << 0 /* comparison */
11893               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11894         }
11895       }
11896       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11897       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11898       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11899                                                : CK_BitCast;
11900       if (LHSIsNull && !RHSIsNull)
11901         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11902       else
11903         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11904     }
11905     return computeResultTy();
11906   }
11907 
11908   if (getLangOpts().CPlusPlus) {
11909     // C++ [expr.eq]p4:
11910     //   Two operands of type std::nullptr_t or one operand of type
11911     //   std::nullptr_t and the other a null pointer constant compare equal.
11912     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11913       if (LHSType->isNullPtrType()) {
11914         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11915         return computeResultTy();
11916       }
11917       if (RHSType->isNullPtrType()) {
11918         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11919         return computeResultTy();
11920       }
11921     }
11922 
11923     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11924     // These aren't covered by the composite pointer type rules.
11925     if (!IsOrdered && RHSType->isNullPtrType() &&
11926         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11927       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11928       return computeResultTy();
11929     }
11930     if (!IsOrdered && LHSType->isNullPtrType() &&
11931         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11932       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11933       return computeResultTy();
11934     }
11935 
11936     if (IsRelational &&
11937         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11938          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11939       // HACK: Relational comparison of nullptr_t against a pointer type is
11940       // invalid per DR583, but we allow it within std::less<> and friends,
11941       // since otherwise common uses of it break.
11942       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11943       // friends to have std::nullptr_t overload candidates.
11944       DeclContext *DC = CurContext;
11945       if (isa<FunctionDecl>(DC))
11946         DC = DC->getParent();
11947       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11948         if (CTSD->isInStdNamespace() &&
11949             llvm::StringSwitch<bool>(CTSD->getName())
11950                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11951                 .Default(false)) {
11952           if (RHSType->isNullPtrType())
11953             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11954           else
11955             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11956           return computeResultTy();
11957         }
11958       }
11959     }
11960 
11961     // C++ [expr.eq]p2:
11962     //   If at least one operand is a pointer to member, [...] bring them to
11963     //   their composite pointer type.
11964     if (!IsOrdered &&
11965         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11966       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11967         return QualType();
11968       else
11969         return computeResultTy();
11970     }
11971   }
11972 
11973   // Handle block pointer types.
11974   if (!IsOrdered && LHSType->isBlockPointerType() &&
11975       RHSType->isBlockPointerType()) {
11976     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11977     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11978 
11979     if (!LHSIsNull && !RHSIsNull &&
11980         !Context.typesAreCompatible(lpointee, rpointee)) {
11981       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11982         << LHSType << RHSType << LHS.get()->getSourceRange()
11983         << RHS.get()->getSourceRange();
11984     }
11985     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11986     return computeResultTy();
11987   }
11988 
11989   // Allow block pointers to be compared with null pointer constants.
11990   if (!IsOrdered
11991       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11992           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11993     if (!LHSIsNull && !RHSIsNull) {
11994       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11995              ->getPointeeType()->isVoidType())
11996             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11997                 ->getPointeeType()->isVoidType())))
11998         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11999           << LHSType << RHSType << LHS.get()->getSourceRange()
12000           << RHS.get()->getSourceRange();
12001     }
12002     if (LHSIsNull && !RHSIsNull)
12003       LHS = ImpCastExprToType(LHS.get(), RHSType,
12004                               RHSType->isPointerType() ? CK_BitCast
12005                                 : CK_AnyPointerToBlockPointerCast);
12006     else
12007       RHS = ImpCastExprToType(RHS.get(), LHSType,
12008                               LHSType->isPointerType() ? CK_BitCast
12009                                 : CK_AnyPointerToBlockPointerCast);
12010     return computeResultTy();
12011   }
12012 
12013   if (LHSType->isObjCObjectPointerType() ||
12014       RHSType->isObjCObjectPointerType()) {
12015     const PointerType *LPT = LHSType->getAs<PointerType>();
12016     const PointerType *RPT = RHSType->getAs<PointerType>();
12017     if (LPT || RPT) {
12018       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12019       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12020 
12021       if (!LPtrToVoid && !RPtrToVoid &&
12022           !Context.typesAreCompatible(LHSType, RHSType)) {
12023         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12024                                           /*isError*/false);
12025       }
12026       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12027       // the RHS, but we have test coverage for this behavior.
12028       // FIXME: Consider using convertPointersToCompositeType in C++.
12029       if (LHSIsNull && !RHSIsNull) {
12030         Expr *E = LHS.get();
12031         if (getLangOpts().ObjCAutoRefCount)
12032           CheckObjCConversion(SourceRange(), RHSType, E,
12033                               CCK_ImplicitConversion);
12034         LHS = ImpCastExprToType(E, RHSType,
12035                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12036       }
12037       else {
12038         Expr *E = RHS.get();
12039         if (getLangOpts().ObjCAutoRefCount)
12040           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12041                               /*Diagnose=*/true,
12042                               /*DiagnoseCFAudited=*/false, Opc);
12043         RHS = ImpCastExprToType(E, LHSType,
12044                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12045       }
12046       return computeResultTy();
12047     }
12048     if (LHSType->isObjCObjectPointerType() &&
12049         RHSType->isObjCObjectPointerType()) {
12050       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12051         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12052                                           /*isError*/false);
12053       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12054         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12055 
12056       if (LHSIsNull && !RHSIsNull)
12057         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12058       else
12059         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12060       return computeResultTy();
12061     }
12062 
12063     if (!IsOrdered && LHSType->isBlockPointerType() &&
12064         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12065       LHS = ImpCastExprToType(LHS.get(), RHSType,
12066                               CK_BlockPointerToObjCPointerCast);
12067       return computeResultTy();
12068     } else if (!IsOrdered &&
12069                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12070                RHSType->isBlockPointerType()) {
12071       RHS = ImpCastExprToType(RHS.get(), LHSType,
12072                               CK_BlockPointerToObjCPointerCast);
12073       return computeResultTy();
12074     }
12075   }
12076   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12077       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12078     unsigned DiagID = 0;
12079     bool isError = false;
12080     if (LangOpts.DebuggerSupport) {
12081       // Under a debugger, allow the comparison of pointers to integers,
12082       // since users tend to want to compare addresses.
12083     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12084                (RHSIsNull && RHSType->isIntegerType())) {
12085       if (IsOrdered) {
12086         isError = getLangOpts().CPlusPlus;
12087         DiagID =
12088           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12089                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12090       }
12091     } else if (getLangOpts().CPlusPlus) {
12092       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12093       isError = true;
12094     } else if (IsOrdered)
12095       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12096     else
12097       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12098 
12099     if (DiagID) {
12100       Diag(Loc, DiagID)
12101         << LHSType << RHSType << LHS.get()->getSourceRange()
12102         << RHS.get()->getSourceRange();
12103       if (isError)
12104         return QualType();
12105     }
12106 
12107     if (LHSType->isIntegerType())
12108       LHS = ImpCastExprToType(LHS.get(), RHSType,
12109                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12110     else
12111       RHS = ImpCastExprToType(RHS.get(), LHSType,
12112                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12113     return computeResultTy();
12114   }
12115 
12116   // Handle block pointers.
12117   if (!IsOrdered && RHSIsNull
12118       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12119     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12120     return computeResultTy();
12121   }
12122   if (!IsOrdered && LHSIsNull
12123       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12124     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12125     return computeResultTy();
12126   }
12127 
12128   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12129     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12130       return computeResultTy();
12131     }
12132 
12133     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12134       return computeResultTy();
12135     }
12136 
12137     if (LHSIsNull && RHSType->isQueueT()) {
12138       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12139       return computeResultTy();
12140     }
12141 
12142     if (LHSType->isQueueT() && RHSIsNull) {
12143       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12144       return computeResultTy();
12145     }
12146   }
12147 
12148   return InvalidOperands(Loc, LHS, RHS);
12149 }
12150 
12151 // Return a signed ext_vector_type that is of identical size and number of
12152 // elements. For floating point vectors, return an integer type of identical
12153 // size and number of elements. In the non ext_vector_type case, search from
12154 // the largest type to the smallest type to avoid cases where long long == long,
12155 // where long gets picked over long long.
12156 QualType Sema::GetSignedVectorType(QualType V) {
12157   const VectorType *VTy = V->castAs<VectorType>();
12158   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12159 
12160   if (isa<ExtVectorType>(VTy)) {
12161     if (TypeSize == Context.getTypeSize(Context.CharTy))
12162       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12163     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12164       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12165     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12166       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12167     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12168       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12169     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12170            "Unhandled vector element size in vector compare");
12171     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12172   }
12173 
12174   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12175     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12176                                  VectorType::GenericVector);
12177   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12178     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12179                                  VectorType::GenericVector);
12180   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12181     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12182                                  VectorType::GenericVector);
12183   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12184     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12185                                  VectorType::GenericVector);
12186   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12187          "Unhandled vector element size in vector compare");
12188   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12189                                VectorType::GenericVector);
12190 }
12191 
12192 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12193 /// operates on extended vector types.  Instead of producing an IntTy result,
12194 /// like a scalar comparison, a vector comparison produces a vector of integer
12195 /// types.
12196 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12197                                           SourceLocation Loc,
12198                                           BinaryOperatorKind Opc) {
12199   if (Opc == BO_Cmp) {
12200     Diag(Loc, diag::err_three_way_vector_comparison);
12201     return QualType();
12202   }
12203 
12204   // Check to make sure we're operating on vectors of the same type and width,
12205   // Allowing one side to be a scalar of element type.
12206   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12207                               /*AllowBothBool*/true,
12208                               /*AllowBoolConversions*/getLangOpts().ZVector);
12209   if (vType.isNull())
12210     return vType;
12211 
12212   QualType LHSType = LHS.get()->getType();
12213 
12214   // If AltiVec, the comparison results in a numeric type, i.e.
12215   // bool for C++, int for C
12216   if (getLangOpts().AltiVec &&
12217       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12218     return Context.getLogicalOperationType();
12219 
12220   // For non-floating point types, check for self-comparisons of the form
12221   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12222   // often indicate logic errors in the program.
12223   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12224 
12225   // Check for comparisons of floating point operands using != and ==.
12226   if (BinaryOperator::isEqualityOp(Opc) &&
12227       LHSType->hasFloatingRepresentation()) {
12228     assert(RHS.get()->getType()->hasFloatingRepresentation());
12229     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12230   }
12231 
12232   // Return a signed type for the vector.
12233   return GetSignedVectorType(vType);
12234 }
12235 
12236 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12237                                     const ExprResult &XorRHS,
12238                                     const SourceLocation Loc) {
12239   // Do not diagnose macros.
12240   if (Loc.isMacroID())
12241     return;
12242 
12243   // Do not diagnose if both LHS and RHS are macros.
12244   if (XorLHS.get()->getExprLoc().isMacroID() &&
12245       XorRHS.get()->getExprLoc().isMacroID())
12246     return;
12247 
12248   bool Negative = false;
12249   bool ExplicitPlus = false;
12250   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12251   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12252 
12253   if (!LHSInt)
12254     return;
12255   if (!RHSInt) {
12256     // Check negative literals.
12257     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12258       UnaryOperatorKind Opc = UO->getOpcode();
12259       if (Opc != UO_Minus && Opc != UO_Plus)
12260         return;
12261       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12262       if (!RHSInt)
12263         return;
12264       Negative = (Opc == UO_Minus);
12265       ExplicitPlus = !Negative;
12266     } else {
12267       return;
12268     }
12269   }
12270 
12271   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12272   llvm::APInt RightSideValue = RHSInt->getValue();
12273   if (LeftSideValue != 2 && LeftSideValue != 10)
12274     return;
12275 
12276   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12277     return;
12278 
12279   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12280       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12281   llvm::StringRef ExprStr =
12282       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12283 
12284   CharSourceRange XorRange =
12285       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12286   llvm::StringRef XorStr =
12287       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12288   // Do not diagnose if xor keyword/macro is used.
12289   if (XorStr == "xor")
12290     return;
12291 
12292   std::string LHSStr = std::string(Lexer::getSourceText(
12293       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12294       S.getSourceManager(), S.getLangOpts()));
12295   std::string RHSStr = std::string(Lexer::getSourceText(
12296       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12297       S.getSourceManager(), S.getLangOpts()));
12298 
12299   if (Negative) {
12300     RightSideValue = -RightSideValue;
12301     RHSStr = "-" + RHSStr;
12302   } else if (ExplicitPlus) {
12303     RHSStr = "+" + RHSStr;
12304   }
12305 
12306   StringRef LHSStrRef = LHSStr;
12307   StringRef RHSStrRef = RHSStr;
12308   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12309   // literals.
12310   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12311       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12312       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12313       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12314       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12315       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12316       LHSStrRef.find('\'') != StringRef::npos ||
12317       RHSStrRef.find('\'') != StringRef::npos)
12318     return;
12319 
12320   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12321   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12322   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12323   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12324     std::string SuggestedExpr = "1 << " + RHSStr;
12325     bool Overflow = false;
12326     llvm::APInt One = (LeftSideValue - 1);
12327     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12328     if (Overflow) {
12329       if (RightSideIntValue < 64)
12330         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12331             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12332             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12333       else if (RightSideIntValue == 64)
12334         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12335       else
12336         return;
12337     } else {
12338       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12339           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12340           << PowValue.toString(10, true)
12341           << FixItHint::CreateReplacement(
12342                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12343     }
12344 
12345     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12346   } else if (LeftSideValue == 10) {
12347     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12348     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12349         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12350         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12351     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12352   }
12353 }
12354 
12355 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12356                                           SourceLocation Loc) {
12357   // Ensure that either both operands are of the same vector type, or
12358   // one operand is of a vector type and the other is of its element type.
12359   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12360                                        /*AllowBothBool*/true,
12361                                        /*AllowBoolConversions*/false);
12362   if (vType.isNull())
12363     return InvalidOperands(Loc, LHS, RHS);
12364   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12365       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12366     return InvalidOperands(Loc, LHS, RHS);
12367   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12368   //        usage of the logical operators && and || with vectors in C. This
12369   //        check could be notionally dropped.
12370   if (!getLangOpts().CPlusPlus &&
12371       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12372     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12373 
12374   return GetSignedVectorType(LHS.get()->getType());
12375 }
12376 
12377 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12378                                               SourceLocation Loc,
12379                                               bool IsCompAssign) {
12380   if (!IsCompAssign) {
12381     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12382     if (LHS.isInvalid())
12383       return QualType();
12384   }
12385   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12386   if (RHS.isInvalid())
12387     return QualType();
12388 
12389   // For conversion purposes, we ignore any qualifiers.
12390   // For example, "const float" and "float" are equivalent.
12391   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12392   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12393 
12394   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12395   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12396   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12397 
12398   if (Context.hasSameType(LHSType, RHSType))
12399     return LHSType;
12400 
12401   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12402   // case we have to return InvalidOperands.
12403   ExprResult OriginalLHS = LHS;
12404   ExprResult OriginalRHS = RHS;
12405   if (LHSMatType && !RHSMatType) {
12406     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12407     if (!RHS.isInvalid())
12408       return LHSType;
12409 
12410     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12411   }
12412 
12413   if (!LHSMatType && RHSMatType) {
12414     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12415     if (!LHS.isInvalid())
12416       return RHSType;
12417     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12418   }
12419 
12420   return InvalidOperands(Loc, LHS, RHS);
12421 }
12422 
12423 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12424                                            SourceLocation Loc,
12425                                            bool IsCompAssign) {
12426   if (!IsCompAssign) {
12427     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12428     if (LHS.isInvalid())
12429       return QualType();
12430   }
12431   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12432   if (RHS.isInvalid())
12433     return QualType();
12434 
12435   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12436   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12437   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12438 
12439   if (LHSMatType && RHSMatType) {
12440     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12441       return InvalidOperands(Loc, LHS, RHS);
12442 
12443     if (!Context.hasSameType(LHSMatType->getElementType(),
12444                              RHSMatType->getElementType()))
12445       return InvalidOperands(Loc, LHS, RHS);
12446 
12447     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12448                                          LHSMatType->getNumRows(),
12449                                          RHSMatType->getNumColumns());
12450   }
12451   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12452 }
12453 
12454 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12455                                            SourceLocation Loc,
12456                                            BinaryOperatorKind Opc) {
12457   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12458 
12459   bool IsCompAssign =
12460       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12461 
12462   if (LHS.get()->getType()->isVectorType() ||
12463       RHS.get()->getType()->isVectorType()) {
12464     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12465         RHS.get()->getType()->hasIntegerRepresentation())
12466       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12467                         /*AllowBothBool*/true,
12468                         /*AllowBoolConversions*/getLangOpts().ZVector);
12469     return InvalidOperands(Loc, LHS, RHS);
12470   }
12471 
12472   if (Opc == BO_And)
12473     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12474 
12475   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12476       RHS.get()->getType()->hasFloatingRepresentation())
12477     return InvalidOperands(Loc, LHS, RHS);
12478 
12479   ExprResult LHSResult = LHS, RHSResult = RHS;
12480   QualType compType = UsualArithmeticConversions(
12481       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12482   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12483     return QualType();
12484   LHS = LHSResult.get();
12485   RHS = RHSResult.get();
12486 
12487   if (Opc == BO_Xor)
12488     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12489 
12490   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12491     return compType;
12492   return InvalidOperands(Loc, LHS, RHS);
12493 }
12494 
12495 // C99 6.5.[13,14]
12496 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12497                                            SourceLocation Loc,
12498                                            BinaryOperatorKind Opc) {
12499   // Check vector operands differently.
12500   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12501     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12502 
12503   bool EnumConstantInBoolContext = false;
12504   for (const ExprResult &HS : {LHS, RHS}) {
12505     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12506       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12507       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12508         EnumConstantInBoolContext = true;
12509     }
12510   }
12511 
12512   if (EnumConstantInBoolContext)
12513     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12514 
12515   // Diagnose cases where the user write a logical and/or but probably meant a
12516   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12517   // is a constant.
12518   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12519       !LHS.get()->getType()->isBooleanType() &&
12520       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12521       // Don't warn in macros or template instantiations.
12522       !Loc.isMacroID() && !inTemplateInstantiation()) {
12523     // If the RHS can be constant folded, and if it constant folds to something
12524     // that isn't 0 or 1 (which indicate a potential logical operation that
12525     // happened to fold to true/false) then warn.
12526     // Parens on the RHS are ignored.
12527     Expr::EvalResult EVResult;
12528     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12529       llvm::APSInt Result = EVResult.Val.getInt();
12530       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12531            !RHS.get()->getExprLoc().isMacroID()) ||
12532           (Result != 0 && Result != 1)) {
12533         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12534           << RHS.get()->getSourceRange()
12535           << (Opc == BO_LAnd ? "&&" : "||");
12536         // Suggest replacing the logical operator with the bitwise version
12537         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12538             << (Opc == BO_LAnd ? "&" : "|")
12539             << FixItHint::CreateReplacement(SourceRange(
12540                                                  Loc, getLocForEndOfToken(Loc)),
12541                                             Opc == BO_LAnd ? "&" : "|");
12542         if (Opc == BO_LAnd)
12543           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12544           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12545               << FixItHint::CreateRemoval(
12546                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12547                                  RHS.get()->getEndLoc()));
12548       }
12549     }
12550   }
12551 
12552   if (!Context.getLangOpts().CPlusPlus) {
12553     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12554     // not operate on the built-in scalar and vector float types.
12555     if (Context.getLangOpts().OpenCL &&
12556         Context.getLangOpts().OpenCLVersion < 120) {
12557       if (LHS.get()->getType()->isFloatingType() ||
12558           RHS.get()->getType()->isFloatingType())
12559         return InvalidOperands(Loc, LHS, RHS);
12560     }
12561 
12562     LHS = UsualUnaryConversions(LHS.get());
12563     if (LHS.isInvalid())
12564       return QualType();
12565 
12566     RHS = UsualUnaryConversions(RHS.get());
12567     if (RHS.isInvalid())
12568       return QualType();
12569 
12570     if (!LHS.get()->getType()->isScalarType() ||
12571         !RHS.get()->getType()->isScalarType())
12572       return InvalidOperands(Loc, LHS, RHS);
12573 
12574     return Context.IntTy;
12575   }
12576 
12577   // The following is safe because we only use this method for
12578   // non-overloadable operands.
12579 
12580   // C++ [expr.log.and]p1
12581   // C++ [expr.log.or]p1
12582   // The operands are both contextually converted to type bool.
12583   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12584   if (LHSRes.isInvalid())
12585     return InvalidOperands(Loc, LHS, RHS);
12586   LHS = LHSRes;
12587 
12588   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12589   if (RHSRes.isInvalid())
12590     return InvalidOperands(Loc, LHS, RHS);
12591   RHS = RHSRes;
12592 
12593   // C++ [expr.log.and]p2
12594   // C++ [expr.log.or]p2
12595   // The result is a bool.
12596   return Context.BoolTy;
12597 }
12598 
12599 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12600   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12601   if (!ME) return false;
12602   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12603   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12604       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12605   if (!Base) return false;
12606   return Base->getMethodDecl() != nullptr;
12607 }
12608 
12609 /// Is the given expression (which must be 'const') a reference to a
12610 /// variable which was originally non-const, but which has become
12611 /// 'const' due to being captured within a block?
12612 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12613 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12614   assert(E->isLValue() && E->getType().isConstQualified());
12615   E = E->IgnoreParens();
12616 
12617   // Must be a reference to a declaration from an enclosing scope.
12618   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12619   if (!DRE) return NCCK_None;
12620   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12621 
12622   // The declaration must be a variable which is not declared 'const'.
12623   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12624   if (!var) return NCCK_None;
12625   if (var->getType().isConstQualified()) return NCCK_None;
12626   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12627 
12628   // Decide whether the first capture was for a block or a lambda.
12629   DeclContext *DC = S.CurContext, *Prev = nullptr;
12630   // Decide whether the first capture was for a block or a lambda.
12631   while (DC) {
12632     // For init-capture, it is possible that the variable belongs to the
12633     // template pattern of the current context.
12634     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12635       if (var->isInitCapture() &&
12636           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12637         break;
12638     if (DC == var->getDeclContext())
12639       break;
12640     Prev = DC;
12641     DC = DC->getParent();
12642   }
12643   // Unless we have an init-capture, we've gone one step too far.
12644   if (!var->isInitCapture())
12645     DC = Prev;
12646   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12647 }
12648 
12649 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12650   Ty = Ty.getNonReferenceType();
12651   if (IsDereference && Ty->isPointerType())
12652     Ty = Ty->getPointeeType();
12653   return !Ty.isConstQualified();
12654 }
12655 
12656 // Update err_typecheck_assign_const and note_typecheck_assign_const
12657 // when this enum is changed.
12658 enum {
12659   ConstFunction,
12660   ConstVariable,
12661   ConstMember,
12662   ConstMethod,
12663   NestedConstMember,
12664   ConstUnknown,  // Keep as last element
12665 };
12666 
12667 /// Emit the "read-only variable not assignable" error and print notes to give
12668 /// more information about why the variable is not assignable, such as pointing
12669 /// to the declaration of a const variable, showing that a method is const, or
12670 /// that the function is returning a const reference.
12671 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12672                                     SourceLocation Loc) {
12673   SourceRange ExprRange = E->getSourceRange();
12674 
12675   // Only emit one error on the first const found.  All other consts will emit
12676   // a note to the error.
12677   bool DiagnosticEmitted = false;
12678 
12679   // Track if the current expression is the result of a dereference, and if the
12680   // next checked expression is the result of a dereference.
12681   bool IsDereference = false;
12682   bool NextIsDereference = false;
12683 
12684   // Loop to process MemberExpr chains.
12685   while (true) {
12686     IsDereference = NextIsDereference;
12687 
12688     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12689     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12690       NextIsDereference = ME->isArrow();
12691       const ValueDecl *VD = ME->getMemberDecl();
12692       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12693         // Mutable fields can be modified even if the class is const.
12694         if (Field->isMutable()) {
12695           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12696           break;
12697         }
12698 
12699         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12700           if (!DiagnosticEmitted) {
12701             S.Diag(Loc, diag::err_typecheck_assign_const)
12702                 << ExprRange << ConstMember << false /*static*/ << Field
12703                 << Field->getType();
12704             DiagnosticEmitted = true;
12705           }
12706           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12707               << ConstMember << false /*static*/ << Field << Field->getType()
12708               << Field->getSourceRange();
12709         }
12710         E = ME->getBase();
12711         continue;
12712       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12713         if (VDecl->getType().isConstQualified()) {
12714           if (!DiagnosticEmitted) {
12715             S.Diag(Loc, diag::err_typecheck_assign_const)
12716                 << ExprRange << ConstMember << true /*static*/ << VDecl
12717                 << VDecl->getType();
12718             DiagnosticEmitted = true;
12719           }
12720           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12721               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12722               << VDecl->getSourceRange();
12723         }
12724         // Static fields do not inherit constness from parents.
12725         break;
12726       }
12727       break; // End MemberExpr
12728     } else if (const ArraySubscriptExpr *ASE =
12729                    dyn_cast<ArraySubscriptExpr>(E)) {
12730       E = ASE->getBase()->IgnoreParenImpCasts();
12731       continue;
12732     } else if (const ExtVectorElementExpr *EVE =
12733                    dyn_cast<ExtVectorElementExpr>(E)) {
12734       E = EVE->getBase()->IgnoreParenImpCasts();
12735       continue;
12736     }
12737     break;
12738   }
12739 
12740   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12741     // Function calls
12742     const FunctionDecl *FD = CE->getDirectCallee();
12743     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12744       if (!DiagnosticEmitted) {
12745         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12746                                                       << ConstFunction << FD;
12747         DiagnosticEmitted = true;
12748       }
12749       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12750              diag::note_typecheck_assign_const)
12751           << ConstFunction << FD << FD->getReturnType()
12752           << FD->getReturnTypeSourceRange();
12753     }
12754   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12755     // Point to variable declaration.
12756     if (const ValueDecl *VD = DRE->getDecl()) {
12757       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12758         if (!DiagnosticEmitted) {
12759           S.Diag(Loc, diag::err_typecheck_assign_const)
12760               << ExprRange << ConstVariable << VD << VD->getType();
12761           DiagnosticEmitted = true;
12762         }
12763         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12764             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12765       }
12766     }
12767   } else if (isa<CXXThisExpr>(E)) {
12768     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12769       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12770         if (MD->isConst()) {
12771           if (!DiagnosticEmitted) {
12772             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12773                                                           << ConstMethod << MD;
12774             DiagnosticEmitted = true;
12775           }
12776           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12777               << ConstMethod << MD << MD->getSourceRange();
12778         }
12779       }
12780     }
12781   }
12782 
12783   if (DiagnosticEmitted)
12784     return;
12785 
12786   // Can't determine a more specific message, so display the generic error.
12787   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12788 }
12789 
12790 enum OriginalExprKind {
12791   OEK_Variable,
12792   OEK_Member,
12793   OEK_LValue
12794 };
12795 
12796 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12797                                          const RecordType *Ty,
12798                                          SourceLocation Loc, SourceRange Range,
12799                                          OriginalExprKind OEK,
12800                                          bool &DiagnosticEmitted) {
12801   std::vector<const RecordType *> RecordTypeList;
12802   RecordTypeList.push_back(Ty);
12803   unsigned NextToCheckIndex = 0;
12804   // We walk the record hierarchy breadth-first to ensure that we print
12805   // diagnostics in field nesting order.
12806   while (RecordTypeList.size() > NextToCheckIndex) {
12807     bool IsNested = NextToCheckIndex > 0;
12808     for (const FieldDecl *Field :
12809          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12810       // First, check every field for constness.
12811       QualType FieldTy = Field->getType();
12812       if (FieldTy.isConstQualified()) {
12813         if (!DiagnosticEmitted) {
12814           S.Diag(Loc, diag::err_typecheck_assign_const)
12815               << Range << NestedConstMember << OEK << VD
12816               << IsNested << Field;
12817           DiagnosticEmitted = true;
12818         }
12819         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12820             << NestedConstMember << IsNested << Field
12821             << FieldTy << Field->getSourceRange();
12822       }
12823 
12824       // Then we append it to the list to check next in order.
12825       FieldTy = FieldTy.getCanonicalType();
12826       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12827         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12828           RecordTypeList.push_back(FieldRecTy);
12829       }
12830     }
12831     ++NextToCheckIndex;
12832   }
12833 }
12834 
12835 /// Emit an error for the case where a record we are trying to assign to has a
12836 /// const-qualified field somewhere in its hierarchy.
12837 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12838                                          SourceLocation Loc) {
12839   QualType Ty = E->getType();
12840   assert(Ty->isRecordType() && "lvalue was not record?");
12841   SourceRange Range = E->getSourceRange();
12842   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12843   bool DiagEmitted = false;
12844 
12845   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12846     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12847             Range, OEK_Member, DiagEmitted);
12848   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12849     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12850             Range, OEK_Variable, DiagEmitted);
12851   else
12852     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12853             Range, OEK_LValue, DiagEmitted);
12854   if (!DiagEmitted)
12855     DiagnoseConstAssignment(S, E, Loc);
12856 }
12857 
12858 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12859 /// emit an error and return true.  If so, return false.
12860 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12861   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12862 
12863   S.CheckShadowingDeclModification(E, Loc);
12864 
12865   SourceLocation OrigLoc = Loc;
12866   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12867                                                               &Loc);
12868   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12869     IsLV = Expr::MLV_InvalidMessageExpression;
12870   if (IsLV == Expr::MLV_Valid)
12871     return false;
12872 
12873   unsigned DiagID = 0;
12874   bool NeedType = false;
12875   switch (IsLV) { // C99 6.5.16p2
12876   case Expr::MLV_ConstQualified:
12877     // Use a specialized diagnostic when we're assigning to an object
12878     // from an enclosing function or block.
12879     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12880       if (NCCK == NCCK_Block)
12881         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12882       else
12883         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12884       break;
12885     }
12886 
12887     // In ARC, use some specialized diagnostics for occasions where we
12888     // infer 'const'.  These are always pseudo-strong variables.
12889     if (S.getLangOpts().ObjCAutoRefCount) {
12890       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12891       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12892         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12893 
12894         // Use the normal diagnostic if it's pseudo-__strong but the
12895         // user actually wrote 'const'.
12896         if (var->isARCPseudoStrong() &&
12897             (!var->getTypeSourceInfo() ||
12898              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12899           // There are three pseudo-strong cases:
12900           //  - self
12901           ObjCMethodDecl *method = S.getCurMethodDecl();
12902           if (method && var == method->getSelfDecl()) {
12903             DiagID = method->isClassMethod()
12904               ? diag::err_typecheck_arc_assign_self_class_method
12905               : diag::err_typecheck_arc_assign_self;
12906 
12907           //  - Objective-C externally_retained attribute.
12908           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12909                      isa<ParmVarDecl>(var)) {
12910             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12911 
12912           //  - fast enumeration variables
12913           } else {
12914             DiagID = diag::err_typecheck_arr_assign_enumeration;
12915           }
12916 
12917           SourceRange Assign;
12918           if (Loc != OrigLoc)
12919             Assign = SourceRange(OrigLoc, OrigLoc);
12920           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12921           // We need to preserve the AST regardless, so migration tool
12922           // can do its job.
12923           return false;
12924         }
12925       }
12926     }
12927 
12928     // If none of the special cases above are triggered, then this is a
12929     // simple const assignment.
12930     if (DiagID == 0) {
12931       DiagnoseConstAssignment(S, E, Loc);
12932       return true;
12933     }
12934 
12935     break;
12936   case Expr::MLV_ConstAddrSpace:
12937     DiagnoseConstAssignment(S, E, Loc);
12938     return true;
12939   case Expr::MLV_ConstQualifiedField:
12940     DiagnoseRecursiveConstFields(S, E, Loc);
12941     return true;
12942   case Expr::MLV_ArrayType:
12943   case Expr::MLV_ArrayTemporary:
12944     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12945     NeedType = true;
12946     break;
12947   case Expr::MLV_NotObjectType:
12948     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12949     NeedType = true;
12950     break;
12951   case Expr::MLV_LValueCast:
12952     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12953     break;
12954   case Expr::MLV_Valid:
12955     llvm_unreachable("did not take early return for MLV_Valid");
12956   case Expr::MLV_InvalidExpression:
12957   case Expr::MLV_MemberFunction:
12958   case Expr::MLV_ClassTemporary:
12959     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12960     break;
12961   case Expr::MLV_IncompleteType:
12962   case Expr::MLV_IncompleteVoidType:
12963     return S.RequireCompleteType(Loc, E->getType(),
12964              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12965   case Expr::MLV_DuplicateVectorComponents:
12966     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12967     break;
12968   case Expr::MLV_NoSetterProperty:
12969     llvm_unreachable("readonly properties should be processed differently");
12970   case Expr::MLV_InvalidMessageExpression:
12971     DiagID = diag::err_readonly_message_assignment;
12972     break;
12973   case Expr::MLV_SubObjCPropertySetting:
12974     DiagID = diag::err_no_subobject_property_setting;
12975     break;
12976   }
12977 
12978   SourceRange Assign;
12979   if (Loc != OrigLoc)
12980     Assign = SourceRange(OrigLoc, OrigLoc);
12981   if (NeedType)
12982     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12983   else
12984     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12985   return true;
12986 }
12987 
12988 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12989                                          SourceLocation Loc,
12990                                          Sema &Sema) {
12991   if (Sema.inTemplateInstantiation())
12992     return;
12993   if (Sema.isUnevaluatedContext())
12994     return;
12995   if (Loc.isInvalid() || Loc.isMacroID())
12996     return;
12997   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12998     return;
12999 
13000   // C / C++ fields
13001   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13002   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13003   if (ML && MR) {
13004     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13005       return;
13006     const ValueDecl *LHSDecl =
13007         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13008     const ValueDecl *RHSDecl =
13009         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13010     if (LHSDecl != RHSDecl)
13011       return;
13012     if (LHSDecl->getType().isVolatileQualified())
13013       return;
13014     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13015       if (RefTy->getPointeeType().isVolatileQualified())
13016         return;
13017 
13018     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13019   }
13020 
13021   // Objective-C instance variables
13022   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13023   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13024   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13025     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13026     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13027     if (RL && RR && RL->getDecl() == RR->getDecl())
13028       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13029   }
13030 }
13031 
13032 // C99 6.5.16.1
13033 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13034                                        SourceLocation Loc,
13035                                        QualType CompoundType) {
13036   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13037 
13038   // Verify that LHS is a modifiable lvalue, and emit error if not.
13039   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13040     return QualType();
13041 
13042   QualType LHSType = LHSExpr->getType();
13043   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13044                                              CompoundType;
13045   // OpenCL v1.2 s6.1.1.1 p2:
13046   // The half data type can only be used to declare a pointer to a buffer that
13047   // contains half values
13048   if (getLangOpts().OpenCL &&
13049       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13050       LHSType->isHalfType()) {
13051     Diag(Loc, diag::err_opencl_half_load_store) << 1
13052         << LHSType.getUnqualifiedType();
13053     return QualType();
13054   }
13055 
13056   AssignConvertType ConvTy;
13057   if (CompoundType.isNull()) {
13058     Expr *RHSCheck = RHS.get();
13059 
13060     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13061 
13062     QualType LHSTy(LHSType);
13063     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13064     if (RHS.isInvalid())
13065       return QualType();
13066     // Special case of NSObject attributes on c-style pointer types.
13067     if (ConvTy == IncompatiblePointer &&
13068         ((Context.isObjCNSObjectType(LHSType) &&
13069           RHSType->isObjCObjectPointerType()) ||
13070          (Context.isObjCNSObjectType(RHSType) &&
13071           LHSType->isObjCObjectPointerType())))
13072       ConvTy = Compatible;
13073 
13074     if (ConvTy == Compatible &&
13075         LHSType->isObjCObjectType())
13076         Diag(Loc, diag::err_objc_object_assignment)
13077           << LHSType;
13078 
13079     // If the RHS is a unary plus or minus, check to see if they = and + are
13080     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13081     // instead of "x += 4".
13082     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13083       RHSCheck = ICE->getSubExpr();
13084     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13085       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13086           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13087           // Only if the two operators are exactly adjacent.
13088           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13089           // And there is a space or other character before the subexpr of the
13090           // unary +/-.  We don't want to warn on "x=-1".
13091           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13092           UO->getSubExpr()->getBeginLoc().isFileID()) {
13093         Diag(Loc, diag::warn_not_compound_assign)
13094           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13095           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13096       }
13097     }
13098 
13099     if (ConvTy == Compatible) {
13100       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13101         // Warn about retain cycles where a block captures the LHS, but
13102         // not if the LHS is a simple variable into which the block is
13103         // being stored...unless that variable can be captured by reference!
13104         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13105         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13106         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13107           checkRetainCycles(LHSExpr, RHS.get());
13108       }
13109 
13110       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13111           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13112         // It is safe to assign a weak reference into a strong variable.
13113         // Although this code can still have problems:
13114         //   id x = self.weakProp;
13115         //   id y = self.weakProp;
13116         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13117         // paths through the function. This should be revisited if
13118         // -Wrepeated-use-of-weak is made flow-sensitive.
13119         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13120         // variable, which will be valid for the current autorelease scope.
13121         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13122                              RHS.get()->getBeginLoc()))
13123           getCurFunction()->markSafeWeakUse(RHS.get());
13124 
13125       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13126         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13127       }
13128     }
13129   } else {
13130     // Compound assignment "x += y"
13131     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13132   }
13133 
13134   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13135                                RHS.get(), AA_Assigning))
13136     return QualType();
13137 
13138   CheckForNullPointerDereference(*this, LHSExpr);
13139 
13140   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13141     if (CompoundType.isNull()) {
13142       // C++2a [expr.ass]p5:
13143       //   A simple-assignment whose left operand is of a volatile-qualified
13144       //   type is deprecated unless the assignment is either a discarded-value
13145       //   expression or an unevaluated operand
13146       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13147     } else {
13148       // C++2a [expr.ass]p6:
13149       //   [Compound-assignment] expressions are deprecated if E1 has
13150       //   volatile-qualified type
13151       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13152     }
13153   }
13154 
13155   // C99 6.5.16p3: The type of an assignment expression is the type of the
13156   // left operand unless the left operand has qualified type, in which case
13157   // it is the unqualified version of the type of the left operand.
13158   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13159   // is converted to the type of the assignment expression (above).
13160   // C++ 5.17p1: the type of the assignment expression is that of its left
13161   // operand.
13162   return (getLangOpts().CPlusPlus
13163           ? LHSType : LHSType.getUnqualifiedType());
13164 }
13165 
13166 // Only ignore explicit casts to void.
13167 static bool IgnoreCommaOperand(const Expr *E) {
13168   E = E->IgnoreParens();
13169 
13170   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13171     if (CE->getCastKind() == CK_ToVoid) {
13172       return true;
13173     }
13174 
13175     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13176     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13177         CE->getSubExpr()->getType()->isDependentType()) {
13178       return true;
13179     }
13180   }
13181 
13182   return false;
13183 }
13184 
13185 // Look for instances where it is likely the comma operator is confused with
13186 // another operator.  There is an explicit list of acceptable expressions for
13187 // the left hand side of the comma operator, otherwise emit a warning.
13188 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13189   // No warnings in macros
13190   if (Loc.isMacroID())
13191     return;
13192 
13193   // Don't warn in template instantiations.
13194   if (inTemplateInstantiation())
13195     return;
13196 
13197   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13198   // instead, skip more than needed, then call back into here with the
13199   // CommaVisitor in SemaStmt.cpp.
13200   // The listed locations are the initialization and increment portions
13201   // of a for loop.  The additional checks are on the condition of
13202   // if statements, do/while loops, and for loops.
13203   // Differences in scope flags for C89 mode requires the extra logic.
13204   const unsigned ForIncrementFlags =
13205       getLangOpts().C99 || getLangOpts().CPlusPlus
13206           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13207           : Scope::ContinueScope | Scope::BreakScope;
13208   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13209   const unsigned ScopeFlags = getCurScope()->getFlags();
13210   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13211       (ScopeFlags & ForInitFlags) == ForInitFlags)
13212     return;
13213 
13214   // If there are multiple comma operators used together, get the RHS of the
13215   // of the comma operator as the LHS.
13216   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13217     if (BO->getOpcode() != BO_Comma)
13218       break;
13219     LHS = BO->getRHS();
13220   }
13221 
13222   // Only allow some expressions on LHS to not warn.
13223   if (IgnoreCommaOperand(LHS))
13224     return;
13225 
13226   Diag(Loc, diag::warn_comma_operator);
13227   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13228       << LHS->getSourceRange()
13229       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13230                                     LangOpts.CPlusPlus ? "static_cast<void>("
13231                                                        : "(void)(")
13232       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13233                                     ")");
13234 }
13235 
13236 // C99 6.5.17
13237 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13238                                    SourceLocation Loc) {
13239   LHS = S.CheckPlaceholderExpr(LHS.get());
13240   RHS = S.CheckPlaceholderExpr(RHS.get());
13241   if (LHS.isInvalid() || RHS.isInvalid())
13242     return QualType();
13243 
13244   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13245   // operands, but not unary promotions.
13246   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13247 
13248   // So we treat the LHS as a ignored value, and in C++ we allow the
13249   // containing site to determine what should be done with the RHS.
13250   LHS = S.IgnoredValueConversions(LHS.get());
13251   if (LHS.isInvalid())
13252     return QualType();
13253 
13254   S.DiagnoseUnusedExprResult(LHS.get());
13255 
13256   if (!S.getLangOpts().CPlusPlus) {
13257     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13258     if (RHS.isInvalid())
13259       return QualType();
13260     if (!RHS.get()->getType()->isVoidType())
13261       S.RequireCompleteType(Loc, RHS.get()->getType(),
13262                             diag::err_incomplete_type);
13263   }
13264 
13265   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13266     S.DiagnoseCommaOperator(LHS.get(), Loc);
13267 
13268   return RHS.get()->getType();
13269 }
13270 
13271 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13272 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13273 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13274                                                ExprValueKind &VK,
13275                                                ExprObjectKind &OK,
13276                                                SourceLocation OpLoc,
13277                                                bool IsInc, bool IsPrefix) {
13278   if (Op->isTypeDependent())
13279     return S.Context.DependentTy;
13280 
13281   QualType ResType = Op->getType();
13282   // Atomic types can be used for increment / decrement where the non-atomic
13283   // versions can, so ignore the _Atomic() specifier for the purpose of
13284   // checking.
13285   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13286     ResType = ResAtomicType->getValueType();
13287 
13288   assert(!ResType.isNull() && "no type for increment/decrement expression");
13289 
13290   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13291     // Decrement of bool is not allowed.
13292     if (!IsInc) {
13293       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13294       return QualType();
13295     }
13296     // Increment of bool sets it to true, but is deprecated.
13297     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13298                                               : diag::warn_increment_bool)
13299       << Op->getSourceRange();
13300   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13301     // Error on enum increments and decrements in C++ mode
13302     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13303     return QualType();
13304   } else if (ResType->isRealType()) {
13305     // OK!
13306   } else if (ResType->isPointerType()) {
13307     // C99 6.5.2.4p2, 6.5.6p2
13308     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13309       return QualType();
13310   } else if (ResType->isObjCObjectPointerType()) {
13311     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13312     // Otherwise, we just need a complete type.
13313     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13314         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13315       return QualType();
13316   } else if (ResType->isAnyComplexType()) {
13317     // C99 does not support ++/-- on complex types, we allow as an extension.
13318     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13319       << ResType << Op->getSourceRange();
13320   } else if (ResType->isPlaceholderType()) {
13321     ExprResult PR = S.CheckPlaceholderExpr(Op);
13322     if (PR.isInvalid()) return QualType();
13323     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13324                                           IsInc, IsPrefix);
13325   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13326     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13327   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13328              (ResType->castAs<VectorType>()->getVectorKind() !=
13329               VectorType::AltiVecBool)) {
13330     // The z vector extensions allow ++ and -- for non-bool vectors.
13331   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13332             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13333     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13334   } else {
13335     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13336       << ResType << int(IsInc) << Op->getSourceRange();
13337     return QualType();
13338   }
13339   // At this point, we know we have a real, complex or pointer type.
13340   // Now make sure the operand is a modifiable lvalue.
13341   if (CheckForModifiableLvalue(Op, OpLoc, S))
13342     return QualType();
13343   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13344     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13345     //   An operand with volatile-qualified type is deprecated
13346     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13347         << IsInc << ResType;
13348   }
13349   // In C++, a prefix increment is the same type as the operand. Otherwise
13350   // (in C or with postfix), the increment is the unqualified type of the
13351   // operand.
13352   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13353     VK = VK_LValue;
13354     OK = Op->getObjectKind();
13355     return ResType;
13356   } else {
13357     VK = VK_RValue;
13358     return ResType.getUnqualifiedType();
13359   }
13360 }
13361 
13362 
13363 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13364 /// This routine allows us to typecheck complex/recursive expressions
13365 /// where the declaration is needed for type checking. We only need to
13366 /// handle cases when the expression references a function designator
13367 /// or is an lvalue. Here are some examples:
13368 ///  - &(x) => x
13369 ///  - &*****f => f for f a function designator.
13370 ///  - &s.xx => s
13371 ///  - &s.zz[1].yy -> s, if zz is an array
13372 ///  - *(x + 1) -> x, if x is an array
13373 ///  - &"123"[2] -> 0
13374 ///  - & __real__ x -> x
13375 ///
13376 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13377 /// members.
13378 static ValueDecl *getPrimaryDecl(Expr *E) {
13379   switch (E->getStmtClass()) {
13380   case Stmt::DeclRefExprClass:
13381     return cast<DeclRefExpr>(E)->getDecl();
13382   case Stmt::MemberExprClass:
13383     // If this is an arrow operator, the address is an offset from
13384     // the base's value, so the object the base refers to is
13385     // irrelevant.
13386     if (cast<MemberExpr>(E)->isArrow())
13387       return nullptr;
13388     // Otherwise, the expression refers to a part of the base
13389     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13390   case Stmt::ArraySubscriptExprClass: {
13391     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13392     // promotion of register arrays earlier.
13393     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13394     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13395       if (ICE->getSubExpr()->getType()->isArrayType())
13396         return getPrimaryDecl(ICE->getSubExpr());
13397     }
13398     return nullptr;
13399   }
13400   case Stmt::UnaryOperatorClass: {
13401     UnaryOperator *UO = cast<UnaryOperator>(E);
13402 
13403     switch(UO->getOpcode()) {
13404     case UO_Real:
13405     case UO_Imag:
13406     case UO_Extension:
13407       return getPrimaryDecl(UO->getSubExpr());
13408     default:
13409       return nullptr;
13410     }
13411   }
13412   case Stmt::ParenExprClass:
13413     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13414   case Stmt::ImplicitCastExprClass:
13415     // If the result of an implicit cast is an l-value, we care about
13416     // the sub-expression; otherwise, the result here doesn't matter.
13417     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13418   case Stmt::CXXUuidofExprClass:
13419     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13420   default:
13421     return nullptr;
13422   }
13423 }
13424 
13425 namespace {
13426 enum {
13427   AO_Bit_Field = 0,
13428   AO_Vector_Element = 1,
13429   AO_Property_Expansion = 2,
13430   AO_Register_Variable = 3,
13431   AO_Matrix_Element = 4,
13432   AO_No_Error = 5
13433 };
13434 }
13435 /// Diagnose invalid operand for address of operations.
13436 ///
13437 /// \param Type The type of operand which cannot have its address taken.
13438 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13439                                          Expr *E, unsigned Type) {
13440   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13441 }
13442 
13443 /// CheckAddressOfOperand - The operand of & must be either a function
13444 /// designator or an lvalue designating an object. If it is an lvalue, the
13445 /// object cannot be declared with storage class register or be a bit field.
13446 /// Note: The usual conversions are *not* applied to the operand of the &
13447 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13448 /// In C++, the operand might be an overloaded function name, in which case
13449 /// we allow the '&' but retain the overloaded-function type.
13450 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13451   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13452     if (PTy->getKind() == BuiltinType::Overload) {
13453       Expr *E = OrigOp.get()->IgnoreParens();
13454       if (!isa<OverloadExpr>(E)) {
13455         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13456         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13457           << OrigOp.get()->getSourceRange();
13458         return QualType();
13459       }
13460 
13461       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13462       if (isa<UnresolvedMemberExpr>(Ovl))
13463         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13464           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13465             << OrigOp.get()->getSourceRange();
13466           return QualType();
13467         }
13468 
13469       return Context.OverloadTy;
13470     }
13471 
13472     if (PTy->getKind() == BuiltinType::UnknownAny)
13473       return Context.UnknownAnyTy;
13474 
13475     if (PTy->getKind() == BuiltinType::BoundMember) {
13476       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13477         << OrigOp.get()->getSourceRange();
13478       return QualType();
13479     }
13480 
13481     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13482     if (OrigOp.isInvalid()) return QualType();
13483   }
13484 
13485   if (OrigOp.get()->isTypeDependent())
13486     return Context.DependentTy;
13487 
13488   assert(!OrigOp.get()->getType()->isPlaceholderType());
13489 
13490   // Make sure to ignore parentheses in subsequent checks
13491   Expr *op = OrigOp.get()->IgnoreParens();
13492 
13493   // In OpenCL captures for blocks called as lambda functions
13494   // are located in the private address space. Blocks used in
13495   // enqueue_kernel can be located in a different address space
13496   // depending on a vendor implementation. Thus preventing
13497   // taking an address of the capture to avoid invalid AS casts.
13498   if (LangOpts.OpenCL) {
13499     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13500     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13501       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13502       return QualType();
13503     }
13504   }
13505 
13506   if (getLangOpts().C99) {
13507     // Implement C99-only parts of addressof rules.
13508     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13509       if (uOp->getOpcode() == UO_Deref)
13510         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13511         // (assuming the deref expression is valid).
13512         return uOp->getSubExpr()->getType();
13513     }
13514     // Technically, there should be a check for array subscript
13515     // expressions here, but the result of one is always an lvalue anyway.
13516   }
13517   ValueDecl *dcl = getPrimaryDecl(op);
13518 
13519   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13520     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13521                                            op->getBeginLoc()))
13522       return QualType();
13523 
13524   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13525   unsigned AddressOfError = AO_No_Error;
13526 
13527   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13528     bool sfinae = (bool)isSFINAEContext();
13529     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13530                                   : diag::ext_typecheck_addrof_temporary)
13531       << op->getType() << op->getSourceRange();
13532     if (sfinae)
13533       return QualType();
13534     // Materialize the temporary as an lvalue so that we can take its address.
13535     OrigOp = op =
13536         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13537   } else if (isa<ObjCSelectorExpr>(op)) {
13538     return Context.getPointerType(op->getType());
13539   } else if (lval == Expr::LV_MemberFunction) {
13540     // If it's an instance method, make a member pointer.
13541     // The expression must have exactly the form &A::foo.
13542 
13543     // If the underlying expression isn't a decl ref, give up.
13544     if (!isa<DeclRefExpr>(op)) {
13545       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13546         << OrigOp.get()->getSourceRange();
13547       return QualType();
13548     }
13549     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13550     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13551 
13552     // The id-expression was parenthesized.
13553     if (OrigOp.get() != DRE) {
13554       Diag(OpLoc, diag::err_parens_pointer_member_function)
13555         << OrigOp.get()->getSourceRange();
13556 
13557     // The method was named without a qualifier.
13558     } else if (!DRE->getQualifier()) {
13559       if (MD->getParent()->getName().empty())
13560         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13561           << op->getSourceRange();
13562       else {
13563         SmallString<32> Str;
13564         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13565         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13566           << op->getSourceRange()
13567           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13568       }
13569     }
13570 
13571     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13572     if (isa<CXXDestructorDecl>(MD))
13573       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13574 
13575     QualType MPTy = Context.getMemberPointerType(
13576         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13577     // Under the MS ABI, lock down the inheritance model now.
13578     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13579       (void)isCompleteType(OpLoc, MPTy);
13580     return MPTy;
13581   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13582     // C99 6.5.3.2p1
13583     // The operand must be either an l-value or a function designator
13584     if (!op->getType()->isFunctionType()) {
13585       // Use a special diagnostic for loads from property references.
13586       if (isa<PseudoObjectExpr>(op)) {
13587         AddressOfError = AO_Property_Expansion;
13588       } else {
13589         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13590           << op->getType() << op->getSourceRange();
13591         return QualType();
13592       }
13593     }
13594   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13595     // The operand cannot be a bit-field
13596     AddressOfError = AO_Bit_Field;
13597   } else if (op->getObjectKind() == OK_VectorComponent) {
13598     // The operand cannot be an element of a vector
13599     AddressOfError = AO_Vector_Element;
13600   } else if (op->getObjectKind() == OK_MatrixComponent) {
13601     // The operand cannot be an element of a matrix.
13602     AddressOfError = AO_Matrix_Element;
13603   } else if (dcl) { // C99 6.5.3.2p1
13604     // We have an lvalue with a decl. Make sure the decl is not declared
13605     // with the register storage-class specifier.
13606     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13607       // in C++ it is not error to take address of a register
13608       // variable (c++03 7.1.1P3)
13609       if (vd->getStorageClass() == SC_Register &&
13610           !getLangOpts().CPlusPlus) {
13611         AddressOfError = AO_Register_Variable;
13612       }
13613     } else if (isa<MSPropertyDecl>(dcl)) {
13614       AddressOfError = AO_Property_Expansion;
13615     } else if (isa<FunctionTemplateDecl>(dcl)) {
13616       return Context.OverloadTy;
13617     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13618       // Okay: we can take the address of a field.
13619       // Could be a pointer to member, though, if there is an explicit
13620       // scope qualifier for the class.
13621       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13622         DeclContext *Ctx = dcl->getDeclContext();
13623         if (Ctx && Ctx->isRecord()) {
13624           if (dcl->getType()->isReferenceType()) {
13625             Diag(OpLoc,
13626                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13627               << dcl->getDeclName() << dcl->getType();
13628             return QualType();
13629           }
13630 
13631           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13632             Ctx = Ctx->getParent();
13633 
13634           QualType MPTy = Context.getMemberPointerType(
13635               op->getType(),
13636               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13637           // Under the MS ABI, lock down the inheritance model now.
13638           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13639             (void)isCompleteType(OpLoc, MPTy);
13640           return MPTy;
13641         }
13642       }
13643     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13644                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13645       llvm_unreachable("Unknown/unexpected decl type");
13646   }
13647 
13648   if (AddressOfError != AO_No_Error) {
13649     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13650     return QualType();
13651   }
13652 
13653   if (lval == Expr::LV_IncompleteVoidType) {
13654     // Taking the address of a void variable is technically illegal, but we
13655     // allow it in cases which are otherwise valid.
13656     // Example: "extern void x; void* y = &x;".
13657     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13658   }
13659 
13660   // If the operand has type "type", the result has type "pointer to type".
13661   if (op->getType()->isObjCObjectType())
13662     return Context.getObjCObjectPointerType(op->getType());
13663 
13664   CheckAddressOfPackedMember(op);
13665 
13666   return Context.getPointerType(op->getType());
13667 }
13668 
13669 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13670   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13671   if (!DRE)
13672     return;
13673   const Decl *D = DRE->getDecl();
13674   if (!D)
13675     return;
13676   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13677   if (!Param)
13678     return;
13679   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13680     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13681       return;
13682   if (FunctionScopeInfo *FD = S.getCurFunction())
13683     if (!FD->ModifiedNonNullParams.count(Param))
13684       FD->ModifiedNonNullParams.insert(Param);
13685 }
13686 
13687 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13688 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13689                                         SourceLocation OpLoc) {
13690   if (Op->isTypeDependent())
13691     return S.Context.DependentTy;
13692 
13693   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13694   if (ConvResult.isInvalid())
13695     return QualType();
13696   Op = ConvResult.get();
13697   QualType OpTy = Op->getType();
13698   QualType Result;
13699 
13700   if (isa<CXXReinterpretCastExpr>(Op)) {
13701     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13702     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13703                                      Op->getSourceRange());
13704   }
13705 
13706   if (const PointerType *PT = OpTy->getAs<PointerType>())
13707   {
13708     Result = PT->getPointeeType();
13709   }
13710   else if (const ObjCObjectPointerType *OPT =
13711              OpTy->getAs<ObjCObjectPointerType>())
13712     Result = OPT->getPointeeType();
13713   else {
13714     ExprResult PR = S.CheckPlaceholderExpr(Op);
13715     if (PR.isInvalid()) return QualType();
13716     if (PR.get() != Op)
13717       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13718   }
13719 
13720   if (Result.isNull()) {
13721     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13722       << OpTy << Op->getSourceRange();
13723     return QualType();
13724   }
13725 
13726   // Note that per both C89 and C99, indirection is always legal, even if Result
13727   // is an incomplete type or void.  It would be possible to warn about
13728   // dereferencing a void pointer, but it's completely well-defined, and such a
13729   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13730   // for pointers to 'void' but is fine for any other pointer type:
13731   //
13732   // C++ [expr.unary.op]p1:
13733   //   [...] the expression to which [the unary * operator] is applied shall
13734   //   be a pointer to an object type, or a pointer to a function type
13735   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13736     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13737       << OpTy << Op->getSourceRange();
13738 
13739   // Dereferences are usually l-values...
13740   VK = VK_LValue;
13741 
13742   // ...except that certain expressions are never l-values in C.
13743   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13744     VK = VK_RValue;
13745 
13746   return Result;
13747 }
13748 
13749 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13750   BinaryOperatorKind Opc;
13751   switch (Kind) {
13752   default: llvm_unreachable("Unknown binop!");
13753   case tok::periodstar:           Opc = BO_PtrMemD; break;
13754   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13755   case tok::star:                 Opc = BO_Mul; break;
13756   case tok::slash:                Opc = BO_Div; break;
13757   case tok::percent:              Opc = BO_Rem; break;
13758   case tok::plus:                 Opc = BO_Add; break;
13759   case tok::minus:                Opc = BO_Sub; break;
13760   case tok::lessless:             Opc = BO_Shl; break;
13761   case tok::greatergreater:       Opc = BO_Shr; break;
13762   case tok::lessequal:            Opc = BO_LE; break;
13763   case tok::less:                 Opc = BO_LT; break;
13764   case tok::greaterequal:         Opc = BO_GE; break;
13765   case tok::greater:              Opc = BO_GT; break;
13766   case tok::exclaimequal:         Opc = BO_NE; break;
13767   case tok::equalequal:           Opc = BO_EQ; break;
13768   case tok::spaceship:            Opc = BO_Cmp; break;
13769   case tok::amp:                  Opc = BO_And; break;
13770   case tok::caret:                Opc = BO_Xor; break;
13771   case tok::pipe:                 Opc = BO_Or; break;
13772   case tok::ampamp:               Opc = BO_LAnd; break;
13773   case tok::pipepipe:             Opc = BO_LOr; break;
13774   case tok::equal:                Opc = BO_Assign; break;
13775   case tok::starequal:            Opc = BO_MulAssign; break;
13776   case tok::slashequal:           Opc = BO_DivAssign; break;
13777   case tok::percentequal:         Opc = BO_RemAssign; break;
13778   case tok::plusequal:            Opc = BO_AddAssign; break;
13779   case tok::minusequal:           Opc = BO_SubAssign; break;
13780   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13781   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13782   case tok::ampequal:             Opc = BO_AndAssign; break;
13783   case tok::caretequal:           Opc = BO_XorAssign; break;
13784   case tok::pipeequal:            Opc = BO_OrAssign; break;
13785   case tok::comma:                Opc = BO_Comma; break;
13786   }
13787   return Opc;
13788 }
13789 
13790 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13791   tok::TokenKind Kind) {
13792   UnaryOperatorKind Opc;
13793   switch (Kind) {
13794   default: llvm_unreachable("Unknown unary op!");
13795   case tok::plusplus:     Opc = UO_PreInc; break;
13796   case tok::minusminus:   Opc = UO_PreDec; break;
13797   case tok::amp:          Opc = UO_AddrOf; break;
13798   case tok::star:         Opc = UO_Deref; break;
13799   case tok::plus:         Opc = UO_Plus; break;
13800   case tok::minus:        Opc = UO_Minus; break;
13801   case tok::tilde:        Opc = UO_Not; break;
13802   case tok::exclaim:      Opc = UO_LNot; break;
13803   case tok::kw___real:    Opc = UO_Real; break;
13804   case tok::kw___imag:    Opc = UO_Imag; break;
13805   case tok::kw___extension__: Opc = UO_Extension; break;
13806   }
13807   return Opc;
13808 }
13809 
13810 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13811 /// This warning suppressed in the event of macro expansions.
13812 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13813                                    SourceLocation OpLoc, bool IsBuiltin) {
13814   if (S.inTemplateInstantiation())
13815     return;
13816   if (S.isUnevaluatedContext())
13817     return;
13818   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13819     return;
13820   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13821   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13822   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13823   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13824   if (!LHSDeclRef || !RHSDeclRef ||
13825       LHSDeclRef->getLocation().isMacroID() ||
13826       RHSDeclRef->getLocation().isMacroID())
13827     return;
13828   const ValueDecl *LHSDecl =
13829     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13830   const ValueDecl *RHSDecl =
13831     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13832   if (LHSDecl != RHSDecl)
13833     return;
13834   if (LHSDecl->getType().isVolatileQualified())
13835     return;
13836   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13837     if (RefTy->getPointeeType().isVolatileQualified())
13838       return;
13839 
13840   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13841                           : diag::warn_self_assignment_overloaded)
13842       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13843       << RHSExpr->getSourceRange();
13844 }
13845 
13846 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13847 /// is usually indicative of introspection within the Objective-C pointer.
13848 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13849                                           SourceLocation OpLoc) {
13850   if (!S.getLangOpts().ObjC)
13851     return;
13852 
13853   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13854   const Expr *LHS = L.get();
13855   const Expr *RHS = R.get();
13856 
13857   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13858     ObjCPointerExpr = LHS;
13859     OtherExpr = RHS;
13860   }
13861   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13862     ObjCPointerExpr = RHS;
13863     OtherExpr = LHS;
13864   }
13865 
13866   // This warning is deliberately made very specific to reduce false
13867   // positives with logic that uses '&' for hashing.  This logic mainly
13868   // looks for code trying to introspect into tagged pointers, which
13869   // code should generally never do.
13870   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13871     unsigned Diag = diag::warn_objc_pointer_masking;
13872     // Determine if we are introspecting the result of performSelectorXXX.
13873     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13874     // Special case messages to -performSelector and friends, which
13875     // can return non-pointer values boxed in a pointer value.
13876     // Some clients may wish to silence warnings in this subcase.
13877     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13878       Selector S = ME->getSelector();
13879       StringRef SelArg0 = S.getNameForSlot(0);
13880       if (SelArg0.startswith("performSelector"))
13881         Diag = diag::warn_objc_pointer_masking_performSelector;
13882     }
13883 
13884     S.Diag(OpLoc, Diag)
13885       << ObjCPointerExpr->getSourceRange();
13886   }
13887 }
13888 
13889 static NamedDecl *getDeclFromExpr(Expr *E) {
13890   if (!E)
13891     return nullptr;
13892   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13893     return DRE->getDecl();
13894   if (auto *ME = dyn_cast<MemberExpr>(E))
13895     return ME->getMemberDecl();
13896   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13897     return IRE->getDecl();
13898   return nullptr;
13899 }
13900 
13901 // This helper function promotes a binary operator's operands (which are of a
13902 // half vector type) to a vector of floats and then truncates the result to
13903 // a vector of either half or short.
13904 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13905                                       BinaryOperatorKind Opc, QualType ResultTy,
13906                                       ExprValueKind VK, ExprObjectKind OK,
13907                                       bool IsCompAssign, SourceLocation OpLoc,
13908                                       FPOptionsOverride FPFeatures) {
13909   auto &Context = S.getASTContext();
13910   assert((isVector(ResultTy, Context.HalfTy) ||
13911           isVector(ResultTy, Context.ShortTy)) &&
13912          "Result must be a vector of half or short");
13913   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13914          isVector(RHS.get()->getType(), Context.HalfTy) &&
13915          "both operands expected to be a half vector");
13916 
13917   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13918   QualType BinOpResTy = RHS.get()->getType();
13919 
13920   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13921   // change BinOpResTy to a vector of ints.
13922   if (isVector(ResultTy, Context.ShortTy))
13923     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13924 
13925   if (IsCompAssign)
13926     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13927                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13928                                           BinOpResTy, BinOpResTy);
13929 
13930   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13931   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13932                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13933   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13934 }
13935 
13936 static std::pair<ExprResult, ExprResult>
13937 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13938                            Expr *RHSExpr) {
13939   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13940   if (!S.Context.isDependenceAllowed()) {
13941     // C cannot handle TypoExpr nodes on either side of a binop because it
13942     // doesn't handle dependent types properly, so make sure any TypoExprs have
13943     // been dealt with before checking the operands.
13944     LHS = S.CorrectDelayedTyposInExpr(LHS);
13945     RHS = S.CorrectDelayedTyposInExpr(
13946         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13947         [Opc, LHS](Expr *E) {
13948           if (Opc != BO_Assign)
13949             return ExprResult(E);
13950           // Avoid correcting the RHS to the same Expr as the LHS.
13951           Decl *D = getDeclFromExpr(E);
13952           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13953         });
13954   }
13955   return std::make_pair(LHS, RHS);
13956 }
13957 
13958 /// Returns true if conversion between vectors of halfs and vectors of floats
13959 /// is needed.
13960 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13961                                      Expr *E0, Expr *E1 = nullptr) {
13962   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13963       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13964     return false;
13965 
13966   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13967     QualType Ty = E->IgnoreImplicit()->getType();
13968 
13969     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13970     // to vectors of floats. Although the element type of the vectors is __fp16,
13971     // the vectors shouldn't be treated as storage-only types. See the
13972     // discussion here: https://reviews.llvm.org/rG825235c140e7
13973     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13974       if (VT->getVectorKind() == VectorType::NeonVector)
13975         return false;
13976       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13977     }
13978     return false;
13979   };
13980 
13981   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13982 }
13983 
13984 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13985 /// operator @p Opc at location @c TokLoc. This routine only supports
13986 /// built-in operations; ActOnBinOp handles overloaded operators.
13987 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13988                                     BinaryOperatorKind Opc,
13989                                     Expr *LHSExpr, Expr *RHSExpr) {
13990   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13991     // The syntax only allows initializer lists on the RHS of assignment,
13992     // so we don't need to worry about accepting invalid code for
13993     // non-assignment operators.
13994     // C++11 5.17p9:
13995     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13996     //   of x = {} is x = T().
13997     InitializationKind Kind = InitializationKind::CreateDirectList(
13998         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13999     InitializedEntity Entity =
14000         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14001     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14002     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14003     if (Init.isInvalid())
14004       return Init;
14005     RHSExpr = Init.get();
14006   }
14007 
14008   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14009   QualType ResultTy;     // Result type of the binary operator.
14010   // The following two variables are used for compound assignment operators
14011   QualType CompLHSTy;    // Type of LHS after promotions for computation
14012   QualType CompResultTy; // Type of computation result
14013   ExprValueKind VK = VK_RValue;
14014   ExprObjectKind OK = OK_Ordinary;
14015   bool ConvertHalfVec = false;
14016 
14017   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14018   if (!LHS.isUsable() || !RHS.isUsable())
14019     return ExprError();
14020 
14021   if (getLangOpts().OpenCL) {
14022     QualType LHSTy = LHSExpr->getType();
14023     QualType RHSTy = RHSExpr->getType();
14024     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14025     // the ATOMIC_VAR_INIT macro.
14026     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14027       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14028       if (BO_Assign == Opc)
14029         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14030       else
14031         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14032       return ExprError();
14033     }
14034 
14035     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14036     // only with a builtin functions and therefore should be disallowed here.
14037     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14038         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14039         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14040         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14041       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14042       return ExprError();
14043     }
14044   }
14045 
14046   switch (Opc) {
14047   case BO_Assign:
14048     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14049     if (getLangOpts().CPlusPlus &&
14050         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14051       VK = LHS.get()->getValueKind();
14052       OK = LHS.get()->getObjectKind();
14053     }
14054     if (!ResultTy.isNull()) {
14055       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14056       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14057 
14058       // Avoid copying a block to the heap if the block is assigned to a local
14059       // auto variable that is declared in the same scope as the block. This
14060       // optimization is unsafe if the local variable is declared in an outer
14061       // scope. For example:
14062       //
14063       // BlockTy b;
14064       // {
14065       //   b = ^{...};
14066       // }
14067       // // It is unsafe to invoke the block here if it wasn't copied to the
14068       // // heap.
14069       // b();
14070 
14071       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14072         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14073           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14074             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14075               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14076 
14077       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14078         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14079                               NTCUC_Assignment, NTCUK_Copy);
14080     }
14081     RecordModifiableNonNullParam(*this, LHS.get());
14082     break;
14083   case BO_PtrMemD:
14084   case BO_PtrMemI:
14085     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14086                                             Opc == BO_PtrMemI);
14087     break;
14088   case BO_Mul:
14089   case BO_Div:
14090     ConvertHalfVec = true;
14091     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14092                                            Opc == BO_Div);
14093     break;
14094   case BO_Rem:
14095     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14096     break;
14097   case BO_Add:
14098     ConvertHalfVec = true;
14099     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14100     break;
14101   case BO_Sub:
14102     ConvertHalfVec = true;
14103     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14104     break;
14105   case BO_Shl:
14106   case BO_Shr:
14107     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14108     break;
14109   case BO_LE:
14110   case BO_LT:
14111   case BO_GE:
14112   case BO_GT:
14113     ConvertHalfVec = true;
14114     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14115     break;
14116   case BO_EQ:
14117   case BO_NE:
14118     ConvertHalfVec = true;
14119     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14120     break;
14121   case BO_Cmp:
14122     ConvertHalfVec = true;
14123     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14124     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14125     break;
14126   case BO_And:
14127     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14128     LLVM_FALLTHROUGH;
14129   case BO_Xor:
14130   case BO_Or:
14131     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14132     break;
14133   case BO_LAnd:
14134   case BO_LOr:
14135     ConvertHalfVec = true;
14136     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14137     break;
14138   case BO_MulAssign:
14139   case BO_DivAssign:
14140     ConvertHalfVec = true;
14141     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14142                                                Opc == BO_DivAssign);
14143     CompLHSTy = CompResultTy;
14144     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14145       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14146     break;
14147   case BO_RemAssign:
14148     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14149     CompLHSTy = CompResultTy;
14150     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14151       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14152     break;
14153   case BO_AddAssign:
14154     ConvertHalfVec = true;
14155     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14156     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14157       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14158     break;
14159   case BO_SubAssign:
14160     ConvertHalfVec = true;
14161     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14162     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14163       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14164     break;
14165   case BO_ShlAssign:
14166   case BO_ShrAssign:
14167     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14168     CompLHSTy = CompResultTy;
14169     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14170       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14171     break;
14172   case BO_AndAssign:
14173   case BO_OrAssign: // fallthrough
14174     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14175     LLVM_FALLTHROUGH;
14176   case BO_XorAssign:
14177     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14178     CompLHSTy = CompResultTy;
14179     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14180       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14181     break;
14182   case BO_Comma:
14183     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14184     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14185       VK = RHS.get()->getValueKind();
14186       OK = RHS.get()->getObjectKind();
14187     }
14188     break;
14189   }
14190   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14191     return ExprError();
14192 
14193   // Some of the binary operations require promoting operands of half vector to
14194   // float vectors and truncating the result back to half vector. For now, we do
14195   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14196   // arm64).
14197   assert(
14198       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14199                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14200       "both sides are half vectors or neither sides are");
14201   ConvertHalfVec =
14202       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14203 
14204   // Check for array bounds violations for both sides of the BinaryOperator
14205   CheckArrayAccess(LHS.get());
14206   CheckArrayAccess(RHS.get());
14207 
14208   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14209     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14210                                                  &Context.Idents.get("object_setClass"),
14211                                                  SourceLocation(), LookupOrdinaryName);
14212     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14213       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14214       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14215           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14216                                         "object_setClass(")
14217           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14218                                           ",")
14219           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14220     }
14221     else
14222       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14223   }
14224   else if (const ObjCIvarRefExpr *OIRE =
14225            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14226     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14227 
14228   // Opc is not a compound assignment if CompResultTy is null.
14229   if (CompResultTy.isNull()) {
14230     if (ConvertHalfVec)
14231       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14232                                  OpLoc, CurFPFeatureOverrides());
14233     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14234                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14235   }
14236 
14237   // Handle compound assignments.
14238   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14239       OK_ObjCProperty) {
14240     VK = VK_LValue;
14241     OK = LHS.get()->getObjectKind();
14242   }
14243 
14244   // The LHS is not converted to the result type for fixed-point compound
14245   // assignment as the common type is computed on demand. Reset the CompLHSTy
14246   // to the LHS type we would have gotten after unary conversions.
14247   if (CompResultTy->isFixedPointType())
14248     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14249 
14250   if (ConvertHalfVec)
14251     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14252                                OpLoc, CurFPFeatureOverrides());
14253 
14254   return CompoundAssignOperator::Create(
14255       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14256       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14257 }
14258 
14259 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14260 /// operators are mixed in a way that suggests that the programmer forgot that
14261 /// comparison operators have higher precedence. The most typical example of
14262 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14263 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14264                                       SourceLocation OpLoc, Expr *LHSExpr,
14265                                       Expr *RHSExpr) {
14266   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14267   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14268 
14269   // Check that one of the sides is a comparison operator and the other isn't.
14270   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14271   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14272   if (isLeftComp == isRightComp)
14273     return;
14274 
14275   // Bitwise operations are sometimes used as eager logical ops.
14276   // Don't diagnose this.
14277   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14278   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14279   if (isLeftBitwise || isRightBitwise)
14280     return;
14281 
14282   SourceRange DiagRange = isLeftComp
14283                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14284                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14285   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14286   SourceRange ParensRange =
14287       isLeftComp
14288           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14289           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14290 
14291   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14292     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14293   SuggestParentheses(Self, OpLoc,
14294     Self.PDiag(diag::note_precedence_silence) << OpStr,
14295     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14296   SuggestParentheses(Self, OpLoc,
14297     Self.PDiag(diag::note_precedence_bitwise_first)
14298       << BinaryOperator::getOpcodeStr(Opc),
14299     ParensRange);
14300 }
14301 
14302 /// It accepts a '&&' expr that is inside a '||' one.
14303 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14304 /// in parentheses.
14305 static void
14306 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14307                                        BinaryOperator *Bop) {
14308   assert(Bop->getOpcode() == BO_LAnd);
14309   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14310       << Bop->getSourceRange() << OpLoc;
14311   SuggestParentheses(Self, Bop->getOperatorLoc(),
14312     Self.PDiag(diag::note_precedence_silence)
14313       << Bop->getOpcodeStr(),
14314     Bop->getSourceRange());
14315 }
14316 
14317 /// Returns true if the given expression can be evaluated as a constant
14318 /// 'true'.
14319 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14320   bool Res;
14321   return !E->isValueDependent() &&
14322          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14323 }
14324 
14325 /// Returns true if the given expression can be evaluated as a constant
14326 /// 'false'.
14327 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14328   bool Res;
14329   return !E->isValueDependent() &&
14330          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14331 }
14332 
14333 /// Look for '&&' in the left hand of a '||' expr.
14334 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14335                                              Expr *LHSExpr, Expr *RHSExpr) {
14336   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14337     if (Bop->getOpcode() == BO_LAnd) {
14338       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14339       if (EvaluatesAsFalse(S, RHSExpr))
14340         return;
14341       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14342       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14343         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14344     } else if (Bop->getOpcode() == BO_LOr) {
14345       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14346         // If it's "a || b && 1 || c" we didn't warn earlier for
14347         // "a || b && 1", but warn now.
14348         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14349           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14350       }
14351     }
14352   }
14353 }
14354 
14355 /// Look for '&&' in the right hand of a '||' expr.
14356 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14357                                              Expr *LHSExpr, Expr *RHSExpr) {
14358   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14359     if (Bop->getOpcode() == BO_LAnd) {
14360       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14361       if (EvaluatesAsFalse(S, LHSExpr))
14362         return;
14363       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14364       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14365         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14366     }
14367   }
14368 }
14369 
14370 /// Look for bitwise op in the left or right hand of a bitwise op with
14371 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14372 /// the '&' expression in parentheses.
14373 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14374                                          SourceLocation OpLoc, Expr *SubExpr) {
14375   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14376     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14377       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14378         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14379         << Bop->getSourceRange() << OpLoc;
14380       SuggestParentheses(S, Bop->getOperatorLoc(),
14381         S.PDiag(diag::note_precedence_silence)
14382           << Bop->getOpcodeStr(),
14383         Bop->getSourceRange());
14384     }
14385   }
14386 }
14387 
14388 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14389                                     Expr *SubExpr, StringRef Shift) {
14390   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14391     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14392       StringRef Op = Bop->getOpcodeStr();
14393       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14394           << Bop->getSourceRange() << OpLoc << Shift << Op;
14395       SuggestParentheses(S, Bop->getOperatorLoc(),
14396           S.PDiag(diag::note_precedence_silence) << Op,
14397           Bop->getSourceRange());
14398     }
14399   }
14400 }
14401 
14402 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14403                                  Expr *LHSExpr, Expr *RHSExpr) {
14404   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14405   if (!OCE)
14406     return;
14407 
14408   FunctionDecl *FD = OCE->getDirectCallee();
14409   if (!FD || !FD->isOverloadedOperator())
14410     return;
14411 
14412   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14413   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14414     return;
14415 
14416   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14417       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14418       << (Kind == OO_LessLess);
14419   SuggestParentheses(S, OCE->getOperatorLoc(),
14420                      S.PDiag(diag::note_precedence_silence)
14421                          << (Kind == OO_LessLess ? "<<" : ">>"),
14422                      OCE->getSourceRange());
14423   SuggestParentheses(
14424       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14425       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14426 }
14427 
14428 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14429 /// precedence.
14430 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14431                                     SourceLocation OpLoc, Expr *LHSExpr,
14432                                     Expr *RHSExpr){
14433   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14434   if (BinaryOperator::isBitwiseOp(Opc))
14435     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14436 
14437   // Diagnose "arg1 & arg2 | arg3"
14438   if ((Opc == BO_Or || Opc == BO_Xor) &&
14439       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14440     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14441     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14442   }
14443 
14444   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14445   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14446   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14447     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14448     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14449   }
14450 
14451   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14452       || Opc == BO_Shr) {
14453     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14454     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14455     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14456   }
14457 
14458   // Warn on overloaded shift operators and comparisons, such as:
14459   // cout << 5 == 4;
14460   if (BinaryOperator::isComparisonOp(Opc))
14461     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14462 }
14463 
14464 // Binary Operators.  'Tok' is the token for the operator.
14465 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14466                             tok::TokenKind Kind,
14467                             Expr *LHSExpr, Expr *RHSExpr) {
14468   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14469   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14470   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14471 
14472   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14473   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14474 
14475   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14476 }
14477 
14478 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14479                        UnresolvedSetImpl &Functions) {
14480   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14481   if (OverOp != OO_None && OverOp != OO_Equal)
14482     LookupOverloadedOperatorName(OverOp, S, Functions);
14483 
14484   // In C++20 onwards, we may have a second operator to look up.
14485   if (getLangOpts().CPlusPlus20) {
14486     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14487       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14488   }
14489 }
14490 
14491 /// Build an overloaded binary operator expression in the given scope.
14492 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14493                                        BinaryOperatorKind Opc,
14494                                        Expr *LHS, Expr *RHS) {
14495   switch (Opc) {
14496   case BO_Assign:
14497   case BO_DivAssign:
14498   case BO_RemAssign:
14499   case BO_SubAssign:
14500   case BO_AndAssign:
14501   case BO_OrAssign:
14502   case BO_XorAssign:
14503     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14504     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14505     break;
14506   default:
14507     break;
14508   }
14509 
14510   // Find all of the overloaded operators visible from this point.
14511   UnresolvedSet<16> Functions;
14512   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14513 
14514   // Build the (potentially-overloaded, potentially-dependent)
14515   // binary operation.
14516   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14517 }
14518 
14519 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14520                             BinaryOperatorKind Opc,
14521                             Expr *LHSExpr, Expr *RHSExpr) {
14522   ExprResult LHS, RHS;
14523   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14524   if (!LHS.isUsable() || !RHS.isUsable())
14525     return ExprError();
14526   LHSExpr = LHS.get();
14527   RHSExpr = RHS.get();
14528 
14529   // We want to end up calling one of checkPseudoObjectAssignment
14530   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14531   // both expressions are overloadable or either is type-dependent),
14532   // or CreateBuiltinBinOp (in any other case).  We also want to get
14533   // any placeholder types out of the way.
14534 
14535   // Handle pseudo-objects in the LHS.
14536   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14537     // Assignments with a pseudo-object l-value need special analysis.
14538     if (pty->getKind() == BuiltinType::PseudoObject &&
14539         BinaryOperator::isAssignmentOp(Opc))
14540       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14541 
14542     // Don't resolve overloads if the other type is overloadable.
14543     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14544       // We can't actually test that if we still have a placeholder,
14545       // though.  Fortunately, none of the exceptions we see in that
14546       // code below are valid when the LHS is an overload set.  Note
14547       // that an overload set can be dependently-typed, but it never
14548       // instantiates to having an overloadable type.
14549       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14550       if (resolvedRHS.isInvalid()) return ExprError();
14551       RHSExpr = resolvedRHS.get();
14552 
14553       if (RHSExpr->isTypeDependent() ||
14554           RHSExpr->getType()->isOverloadableType())
14555         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14556     }
14557 
14558     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14559     // template, diagnose the missing 'template' keyword instead of diagnosing
14560     // an invalid use of a bound member function.
14561     //
14562     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14563     // to C++1z [over.over]/1.4, but we already checked for that case above.
14564     if (Opc == BO_LT && inTemplateInstantiation() &&
14565         (pty->getKind() == BuiltinType::BoundMember ||
14566          pty->getKind() == BuiltinType::Overload)) {
14567       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14568       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14569           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14570             return isa<FunctionTemplateDecl>(ND);
14571           })) {
14572         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14573                                 : OE->getNameLoc(),
14574              diag::err_template_kw_missing)
14575           << OE->getName().getAsString() << "";
14576         return ExprError();
14577       }
14578     }
14579 
14580     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14581     if (LHS.isInvalid()) return ExprError();
14582     LHSExpr = LHS.get();
14583   }
14584 
14585   // Handle pseudo-objects in the RHS.
14586   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14587     // An overload in the RHS can potentially be resolved by the type
14588     // being assigned to.
14589     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14590       if (getLangOpts().CPlusPlus &&
14591           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14592            LHSExpr->getType()->isOverloadableType()))
14593         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14594 
14595       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14596     }
14597 
14598     // Don't resolve overloads if the other type is overloadable.
14599     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14600         LHSExpr->getType()->isOverloadableType())
14601       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14602 
14603     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14604     if (!resolvedRHS.isUsable()) return ExprError();
14605     RHSExpr = resolvedRHS.get();
14606   }
14607 
14608   if (getLangOpts().CPlusPlus) {
14609     // If either expression is type-dependent, always build an
14610     // overloaded op.
14611     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14612       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14613 
14614     // Otherwise, build an overloaded op if either expression has an
14615     // overloadable type.
14616     if (LHSExpr->getType()->isOverloadableType() ||
14617         RHSExpr->getType()->isOverloadableType())
14618       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14619   }
14620 
14621   if (getLangOpts().RecoveryAST &&
14622       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14623     assert(!getLangOpts().CPlusPlus);
14624     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14625            "Should only occur in error-recovery path.");
14626     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14627       // C [6.15.16] p3:
14628       // An assignment expression has the value of the left operand after the
14629       // assignment, but is not an lvalue.
14630       return CompoundAssignOperator::Create(
14631           Context, LHSExpr, RHSExpr, Opc,
14632           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14633           OpLoc, CurFPFeatureOverrides());
14634     QualType ResultType;
14635     switch (Opc) {
14636     case BO_Assign:
14637       ResultType = LHSExpr->getType().getUnqualifiedType();
14638       break;
14639     case BO_LT:
14640     case BO_GT:
14641     case BO_LE:
14642     case BO_GE:
14643     case BO_EQ:
14644     case BO_NE:
14645     case BO_LAnd:
14646     case BO_LOr:
14647       // These operators have a fixed result type regardless of operands.
14648       ResultType = Context.IntTy;
14649       break;
14650     case BO_Comma:
14651       ResultType = RHSExpr->getType();
14652       break;
14653     default:
14654       ResultType = Context.DependentTy;
14655       break;
14656     }
14657     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14658                                   VK_RValue, OK_Ordinary, OpLoc,
14659                                   CurFPFeatureOverrides());
14660   }
14661 
14662   // Build a built-in binary operation.
14663   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14664 }
14665 
14666 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14667   if (T.isNull() || T->isDependentType())
14668     return false;
14669 
14670   if (!T->isPromotableIntegerType())
14671     return true;
14672 
14673   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14674 }
14675 
14676 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14677                                       UnaryOperatorKind Opc,
14678                                       Expr *InputExpr) {
14679   ExprResult Input = InputExpr;
14680   ExprValueKind VK = VK_RValue;
14681   ExprObjectKind OK = OK_Ordinary;
14682   QualType resultType;
14683   bool CanOverflow = false;
14684 
14685   bool ConvertHalfVec = false;
14686   if (getLangOpts().OpenCL) {
14687     QualType Ty = InputExpr->getType();
14688     // The only legal unary operation for atomics is '&'.
14689     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14690     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14691     // only with a builtin functions and therefore should be disallowed here.
14692         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14693         || Ty->isBlockPointerType())) {
14694       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14695                        << InputExpr->getType()
14696                        << Input.get()->getSourceRange());
14697     }
14698   }
14699 
14700   switch (Opc) {
14701   case UO_PreInc:
14702   case UO_PreDec:
14703   case UO_PostInc:
14704   case UO_PostDec:
14705     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14706                                                 OpLoc,
14707                                                 Opc == UO_PreInc ||
14708                                                 Opc == UO_PostInc,
14709                                                 Opc == UO_PreInc ||
14710                                                 Opc == UO_PreDec);
14711     CanOverflow = isOverflowingIntegerType(Context, resultType);
14712     break;
14713   case UO_AddrOf:
14714     resultType = CheckAddressOfOperand(Input, OpLoc);
14715     CheckAddressOfNoDeref(InputExpr);
14716     RecordModifiableNonNullParam(*this, InputExpr);
14717     break;
14718   case UO_Deref: {
14719     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14720     if (Input.isInvalid()) return ExprError();
14721     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14722     break;
14723   }
14724   case UO_Plus:
14725   case UO_Minus:
14726     CanOverflow = Opc == UO_Minus &&
14727                   isOverflowingIntegerType(Context, Input.get()->getType());
14728     Input = UsualUnaryConversions(Input.get());
14729     if (Input.isInvalid()) return ExprError();
14730     // Unary plus and minus require promoting an operand of half vector to a
14731     // float vector and truncating the result back to a half vector. For now, we
14732     // do this only when HalfArgsAndReturns is set (that is, when the target is
14733     // arm or arm64).
14734     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14735 
14736     // If the operand is a half vector, promote it to a float vector.
14737     if (ConvertHalfVec)
14738       Input = convertVector(Input.get(), Context.FloatTy, *this);
14739     resultType = Input.get()->getType();
14740     if (resultType->isDependentType())
14741       break;
14742     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14743       break;
14744     else if (resultType->isVectorType() &&
14745              // The z vector extensions don't allow + or - with bool vectors.
14746              (!Context.getLangOpts().ZVector ||
14747               resultType->castAs<VectorType>()->getVectorKind() !=
14748               VectorType::AltiVecBool))
14749       break;
14750     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14751              Opc == UO_Plus &&
14752              resultType->isPointerType())
14753       break;
14754 
14755     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14756       << resultType << Input.get()->getSourceRange());
14757 
14758   case UO_Not: // bitwise complement
14759     Input = UsualUnaryConversions(Input.get());
14760     if (Input.isInvalid())
14761       return ExprError();
14762     resultType = Input.get()->getType();
14763     if (resultType->isDependentType())
14764       break;
14765     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14766     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14767       // C99 does not support '~' for complex conjugation.
14768       Diag(OpLoc, diag::ext_integer_complement_complex)
14769           << resultType << Input.get()->getSourceRange();
14770     else if (resultType->hasIntegerRepresentation())
14771       break;
14772     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14773       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14774       // on vector float types.
14775       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14776       if (!T->isIntegerType())
14777         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14778                           << resultType << Input.get()->getSourceRange());
14779     } else {
14780       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14781                        << resultType << Input.get()->getSourceRange());
14782     }
14783     break;
14784 
14785   case UO_LNot: // logical negation
14786     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14787     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14788     if (Input.isInvalid()) return ExprError();
14789     resultType = Input.get()->getType();
14790 
14791     // Though we still have to promote half FP to float...
14792     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14793       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14794       resultType = Context.FloatTy;
14795     }
14796 
14797     if (resultType->isDependentType())
14798       break;
14799     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14800       // C99 6.5.3.3p1: ok, fallthrough;
14801       if (Context.getLangOpts().CPlusPlus) {
14802         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14803         // operand contextually converted to bool.
14804         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14805                                   ScalarTypeToBooleanCastKind(resultType));
14806       } else if (Context.getLangOpts().OpenCL &&
14807                  Context.getLangOpts().OpenCLVersion < 120) {
14808         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14809         // operate on scalar float types.
14810         if (!resultType->isIntegerType() && !resultType->isPointerType())
14811           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14812                            << resultType << Input.get()->getSourceRange());
14813       }
14814     } else if (resultType->isExtVectorType()) {
14815       if (Context.getLangOpts().OpenCL &&
14816           Context.getLangOpts().OpenCLVersion < 120 &&
14817           !Context.getLangOpts().OpenCLCPlusPlus) {
14818         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14819         // operate on vector float types.
14820         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14821         if (!T->isIntegerType())
14822           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14823                            << resultType << Input.get()->getSourceRange());
14824       }
14825       // Vector logical not returns the signed variant of the operand type.
14826       resultType = GetSignedVectorType(resultType);
14827       break;
14828     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14829       const VectorType *VTy = resultType->castAs<VectorType>();
14830       if (VTy->getVectorKind() != VectorType::GenericVector)
14831         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14832                          << resultType << Input.get()->getSourceRange());
14833 
14834       // Vector logical not returns the signed variant of the operand type.
14835       resultType = GetSignedVectorType(resultType);
14836       break;
14837     } else {
14838       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14839         << resultType << Input.get()->getSourceRange());
14840     }
14841 
14842     // LNot always has type int. C99 6.5.3.3p5.
14843     // In C++, it's bool. C++ 5.3.1p8
14844     resultType = Context.getLogicalOperationType();
14845     break;
14846   case UO_Real:
14847   case UO_Imag:
14848     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14849     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14850     // complex l-values to ordinary l-values and all other values to r-values.
14851     if (Input.isInvalid()) return ExprError();
14852     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14853       if (Input.get()->getValueKind() != VK_RValue &&
14854           Input.get()->getObjectKind() == OK_Ordinary)
14855         VK = Input.get()->getValueKind();
14856     } else if (!getLangOpts().CPlusPlus) {
14857       // In C, a volatile scalar is read by __imag. In C++, it is not.
14858       Input = DefaultLvalueConversion(Input.get());
14859     }
14860     break;
14861   case UO_Extension:
14862     resultType = Input.get()->getType();
14863     VK = Input.get()->getValueKind();
14864     OK = Input.get()->getObjectKind();
14865     break;
14866   case UO_Coawait:
14867     // It's unnecessary to represent the pass-through operator co_await in the
14868     // AST; just return the input expression instead.
14869     assert(!Input.get()->getType()->isDependentType() &&
14870                    "the co_await expression must be non-dependant before "
14871                    "building operator co_await");
14872     return Input;
14873   }
14874   if (resultType.isNull() || Input.isInvalid())
14875     return ExprError();
14876 
14877   // Check for array bounds violations in the operand of the UnaryOperator,
14878   // except for the '*' and '&' operators that have to be handled specially
14879   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14880   // that are explicitly defined as valid by the standard).
14881   if (Opc != UO_AddrOf && Opc != UO_Deref)
14882     CheckArrayAccess(Input.get());
14883 
14884   auto *UO =
14885       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14886                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14887 
14888   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14889       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14890       !isUnevaluatedContext())
14891     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14892 
14893   // Convert the result back to a half vector.
14894   if (ConvertHalfVec)
14895     return convertVector(UO, Context.HalfTy, *this);
14896   return UO;
14897 }
14898 
14899 /// Determine whether the given expression is a qualified member
14900 /// access expression, of a form that could be turned into a pointer to member
14901 /// with the address-of operator.
14902 bool Sema::isQualifiedMemberAccess(Expr *E) {
14903   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14904     if (!DRE->getQualifier())
14905       return false;
14906 
14907     ValueDecl *VD = DRE->getDecl();
14908     if (!VD->isCXXClassMember())
14909       return false;
14910 
14911     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14912       return true;
14913     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14914       return Method->isInstance();
14915 
14916     return false;
14917   }
14918 
14919   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14920     if (!ULE->getQualifier())
14921       return false;
14922 
14923     for (NamedDecl *D : ULE->decls()) {
14924       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14925         if (Method->isInstance())
14926           return true;
14927       } else {
14928         // Overload set does not contain methods.
14929         break;
14930       }
14931     }
14932 
14933     return false;
14934   }
14935 
14936   return false;
14937 }
14938 
14939 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14940                               UnaryOperatorKind Opc, Expr *Input) {
14941   // First things first: handle placeholders so that the
14942   // overloaded-operator check considers the right type.
14943   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14944     // Increment and decrement of pseudo-object references.
14945     if (pty->getKind() == BuiltinType::PseudoObject &&
14946         UnaryOperator::isIncrementDecrementOp(Opc))
14947       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14948 
14949     // extension is always a builtin operator.
14950     if (Opc == UO_Extension)
14951       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14952 
14953     // & gets special logic for several kinds of placeholder.
14954     // The builtin code knows what to do.
14955     if (Opc == UO_AddrOf &&
14956         (pty->getKind() == BuiltinType::Overload ||
14957          pty->getKind() == BuiltinType::UnknownAny ||
14958          pty->getKind() == BuiltinType::BoundMember))
14959       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14960 
14961     // Anything else needs to be handled now.
14962     ExprResult Result = CheckPlaceholderExpr(Input);
14963     if (Result.isInvalid()) return ExprError();
14964     Input = Result.get();
14965   }
14966 
14967   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14968       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14969       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14970     // Find all of the overloaded operators visible from this point.
14971     UnresolvedSet<16> Functions;
14972     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14973     if (S && OverOp != OO_None)
14974       LookupOverloadedOperatorName(OverOp, S, Functions);
14975 
14976     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14977   }
14978 
14979   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14980 }
14981 
14982 // Unary Operators.  'Tok' is the token for the operator.
14983 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14984                               tok::TokenKind Op, Expr *Input) {
14985   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14986 }
14987 
14988 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14989 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14990                                 LabelDecl *TheDecl) {
14991   TheDecl->markUsed(Context);
14992   // Create the AST node.  The address of a label always has type 'void*'.
14993   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14994                                      Context.getPointerType(Context.VoidTy));
14995 }
14996 
14997 void Sema::ActOnStartStmtExpr() {
14998   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14999 }
15000 
15001 void Sema::ActOnStmtExprError() {
15002   // Note that function is also called by TreeTransform when leaving a
15003   // StmtExpr scope without rebuilding anything.
15004 
15005   DiscardCleanupsInEvaluationContext();
15006   PopExpressionEvaluationContext();
15007 }
15008 
15009 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15010                                SourceLocation RPLoc) {
15011   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15012 }
15013 
15014 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15015                                SourceLocation RPLoc, unsigned TemplateDepth) {
15016   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15017   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15018 
15019   if (hasAnyUnrecoverableErrorsInThisFunction())
15020     DiscardCleanupsInEvaluationContext();
15021   assert(!Cleanup.exprNeedsCleanups() &&
15022          "cleanups within StmtExpr not correctly bound!");
15023   PopExpressionEvaluationContext();
15024 
15025   // FIXME: there are a variety of strange constraints to enforce here, for
15026   // example, it is not possible to goto into a stmt expression apparently.
15027   // More semantic analysis is needed.
15028 
15029   // If there are sub-stmts in the compound stmt, take the type of the last one
15030   // as the type of the stmtexpr.
15031   QualType Ty = Context.VoidTy;
15032   bool StmtExprMayBindToTemp = false;
15033   if (!Compound->body_empty()) {
15034     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15035     if (const auto *LastStmt =
15036             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15037       if (const Expr *Value = LastStmt->getExprStmt()) {
15038         StmtExprMayBindToTemp = true;
15039         Ty = Value->getType();
15040       }
15041     }
15042   }
15043 
15044   // FIXME: Check that expression type is complete/non-abstract; statement
15045   // expressions are not lvalues.
15046   Expr *ResStmtExpr =
15047       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15048   if (StmtExprMayBindToTemp)
15049     return MaybeBindToTemporary(ResStmtExpr);
15050   return ResStmtExpr;
15051 }
15052 
15053 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15054   if (ER.isInvalid())
15055     return ExprError();
15056 
15057   // Do function/array conversion on the last expression, but not
15058   // lvalue-to-rvalue.  However, initialize an unqualified type.
15059   ER = DefaultFunctionArrayConversion(ER.get());
15060   if (ER.isInvalid())
15061     return ExprError();
15062   Expr *E = ER.get();
15063 
15064   if (E->isTypeDependent())
15065     return E;
15066 
15067   // In ARC, if the final expression ends in a consume, splice
15068   // the consume out and bind it later.  In the alternate case
15069   // (when dealing with a retainable type), the result
15070   // initialization will create a produce.  In both cases the
15071   // result will be +1, and we'll need to balance that out with
15072   // a bind.
15073   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15074   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15075     return Cast->getSubExpr();
15076 
15077   // FIXME: Provide a better location for the initialization.
15078   return PerformCopyInitialization(
15079       InitializedEntity::InitializeStmtExprResult(
15080           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15081       SourceLocation(), E);
15082 }
15083 
15084 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15085                                       TypeSourceInfo *TInfo,
15086                                       ArrayRef<OffsetOfComponent> Components,
15087                                       SourceLocation RParenLoc) {
15088   QualType ArgTy = TInfo->getType();
15089   bool Dependent = ArgTy->isDependentType();
15090   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15091 
15092   // We must have at least one component that refers to the type, and the first
15093   // one is known to be a field designator.  Verify that the ArgTy represents
15094   // a struct/union/class.
15095   if (!Dependent && !ArgTy->isRecordType())
15096     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15097                        << ArgTy << TypeRange);
15098 
15099   // Type must be complete per C99 7.17p3 because a declaring a variable
15100   // with an incomplete type would be ill-formed.
15101   if (!Dependent
15102       && RequireCompleteType(BuiltinLoc, ArgTy,
15103                              diag::err_offsetof_incomplete_type, TypeRange))
15104     return ExprError();
15105 
15106   bool DidWarnAboutNonPOD = false;
15107   QualType CurrentType = ArgTy;
15108   SmallVector<OffsetOfNode, 4> Comps;
15109   SmallVector<Expr*, 4> Exprs;
15110   for (const OffsetOfComponent &OC : Components) {
15111     if (OC.isBrackets) {
15112       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15113       if (!CurrentType->isDependentType()) {
15114         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15115         if(!AT)
15116           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15117                            << CurrentType);
15118         CurrentType = AT->getElementType();
15119       } else
15120         CurrentType = Context.DependentTy;
15121 
15122       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15123       if (IdxRval.isInvalid())
15124         return ExprError();
15125       Expr *Idx = IdxRval.get();
15126 
15127       // The expression must be an integral expression.
15128       // FIXME: An integral constant expression?
15129       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15130           !Idx->getType()->isIntegerType())
15131         return ExprError(
15132             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15133             << Idx->getSourceRange());
15134 
15135       // Record this array index.
15136       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15137       Exprs.push_back(Idx);
15138       continue;
15139     }
15140 
15141     // Offset of a field.
15142     if (CurrentType->isDependentType()) {
15143       // We have the offset of a field, but we can't look into the dependent
15144       // type. Just record the identifier of the field.
15145       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15146       CurrentType = Context.DependentTy;
15147       continue;
15148     }
15149 
15150     // We need to have a complete type to look into.
15151     if (RequireCompleteType(OC.LocStart, CurrentType,
15152                             diag::err_offsetof_incomplete_type))
15153       return ExprError();
15154 
15155     // Look for the designated field.
15156     const RecordType *RC = CurrentType->getAs<RecordType>();
15157     if (!RC)
15158       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15159                        << CurrentType);
15160     RecordDecl *RD = RC->getDecl();
15161 
15162     // C++ [lib.support.types]p5:
15163     //   The macro offsetof accepts a restricted set of type arguments in this
15164     //   International Standard. type shall be a POD structure or a POD union
15165     //   (clause 9).
15166     // C++11 [support.types]p4:
15167     //   If type is not a standard-layout class (Clause 9), the results are
15168     //   undefined.
15169     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15170       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15171       unsigned DiagID =
15172         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15173                             : diag::ext_offsetof_non_pod_type;
15174 
15175       if (!IsSafe && !DidWarnAboutNonPOD &&
15176           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15177                               PDiag(DiagID)
15178                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15179                               << CurrentType))
15180         DidWarnAboutNonPOD = true;
15181     }
15182 
15183     // Look for the field.
15184     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15185     LookupQualifiedName(R, RD);
15186     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15187     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15188     if (!MemberDecl) {
15189       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15190         MemberDecl = IndirectMemberDecl->getAnonField();
15191     }
15192 
15193     if (!MemberDecl)
15194       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15195                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15196                                                               OC.LocEnd));
15197 
15198     // C99 7.17p3:
15199     //   (If the specified member is a bit-field, the behavior is undefined.)
15200     //
15201     // We diagnose this as an error.
15202     if (MemberDecl->isBitField()) {
15203       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15204         << MemberDecl->getDeclName()
15205         << SourceRange(BuiltinLoc, RParenLoc);
15206       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15207       return ExprError();
15208     }
15209 
15210     RecordDecl *Parent = MemberDecl->getParent();
15211     if (IndirectMemberDecl)
15212       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15213 
15214     // If the member was found in a base class, introduce OffsetOfNodes for
15215     // the base class indirections.
15216     CXXBasePaths Paths;
15217     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15218                       Paths)) {
15219       if (Paths.getDetectedVirtual()) {
15220         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15221           << MemberDecl->getDeclName()
15222           << SourceRange(BuiltinLoc, RParenLoc);
15223         return ExprError();
15224       }
15225 
15226       CXXBasePath &Path = Paths.front();
15227       for (const CXXBasePathElement &B : Path)
15228         Comps.push_back(OffsetOfNode(B.Base));
15229     }
15230 
15231     if (IndirectMemberDecl) {
15232       for (auto *FI : IndirectMemberDecl->chain()) {
15233         assert(isa<FieldDecl>(FI));
15234         Comps.push_back(OffsetOfNode(OC.LocStart,
15235                                      cast<FieldDecl>(FI), OC.LocEnd));
15236       }
15237     } else
15238       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15239 
15240     CurrentType = MemberDecl->getType().getNonReferenceType();
15241   }
15242 
15243   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15244                               Comps, Exprs, RParenLoc);
15245 }
15246 
15247 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15248                                       SourceLocation BuiltinLoc,
15249                                       SourceLocation TypeLoc,
15250                                       ParsedType ParsedArgTy,
15251                                       ArrayRef<OffsetOfComponent> Components,
15252                                       SourceLocation RParenLoc) {
15253 
15254   TypeSourceInfo *ArgTInfo;
15255   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15256   if (ArgTy.isNull())
15257     return ExprError();
15258 
15259   if (!ArgTInfo)
15260     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15261 
15262   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15263 }
15264 
15265 
15266 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15267                                  Expr *CondExpr,
15268                                  Expr *LHSExpr, Expr *RHSExpr,
15269                                  SourceLocation RPLoc) {
15270   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15271 
15272   ExprValueKind VK = VK_RValue;
15273   ExprObjectKind OK = OK_Ordinary;
15274   QualType resType;
15275   bool CondIsTrue = false;
15276   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15277     resType = Context.DependentTy;
15278   } else {
15279     // The conditional expression is required to be a constant expression.
15280     llvm::APSInt condEval(32);
15281     ExprResult CondICE = VerifyIntegerConstantExpression(
15282         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15283     if (CondICE.isInvalid())
15284       return ExprError();
15285     CondExpr = CondICE.get();
15286     CondIsTrue = condEval.getZExtValue();
15287 
15288     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15289     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15290 
15291     resType = ActiveExpr->getType();
15292     VK = ActiveExpr->getValueKind();
15293     OK = ActiveExpr->getObjectKind();
15294   }
15295 
15296   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15297                                   resType, VK, OK, RPLoc, CondIsTrue);
15298 }
15299 
15300 //===----------------------------------------------------------------------===//
15301 // Clang Extensions.
15302 //===----------------------------------------------------------------------===//
15303 
15304 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15305 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15306   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15307 
15308   if (LangOpts.CPlusPlus) {
15309     MangleNumberingContext *MCtx;
15310     Decl *ManglingContextDecl;
15311     std::tie(MCtx, ManglingContextDecl) =
15312         getCurrentMangleNumberContext(Block->getDeclContext());
15313     if (MCtx) {
15314       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15315       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15316     }
15317   }
15318 
15319   PushBlockScope(CurScope, Block);
15320   CurContext->addDecl(Block);
15321   if (CurScope)
15322     PushDeclContext(CurScope, Block);
15323   else
15324     CurContext = Block;
15325 
15326   getCurBlock()->HasImplicitReturnType = true;
15327 
15328   // Enter a new evaluation context to insulate the block from any
15329   // cleanups from the enclosing full-expression.
15330   PushExpressionEvaluationContext(
15331       ExpressionEvaluationContext::PotentiallyEvaluated);
15332 }
15333 
15334 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15335                                Scope *CurScope) {
15336   assert(ParamInfo.getIdentifier() == nullptr &&
15337          "block-id should have no identifier!");
15338   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15339   BlockScopeInfo *CurBlock = getCurBlock();
15340 
15341   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15342   QualType T = Sig->getType();
15343 
15344   // FIXME: We should allow unexpanded parameter packs here, but that would,
15345   // in turn, make the block expression contain unexpanded parameter packs.
15346   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15347     // Drop the parameters.
15348     FunctionProtoType::ExtProtoInfo EPI;
15349     EPI.HasTrailingReturn = false;
15350     EPI.TypeQuals.addConst();
15351     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15352     Sig = Context.getTrivialTypeSourceInfo(T);
15353   }
15354 
15355   // GetTypeForDeclarator always produces a function type for a block
15356   // literal signature.  Furthermore, it is always a FunctionProtoType
15357   // unless the function was written with a typedef.
15358   assert(T->isFunctionType() &&
15359          "GetTypeForDeclarator made a non-function block signature");
15360 
15361   // Look for an explicit signature in that function type.
15362   FunctionProtoTypeLoc ExplicitSignature;
15363 
15364   if ((ExplicitSignature = Sig->getTypeLoc()
15365                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15366 
15367     // Check whether that explicit signature was synthesized by
15368     // GetTypeForDeclarator.  If so, don't save that as part of the
15369     // written signature.
15370     if (ExplicitSignature.getLocalRangeBegin() ==
15371         ExplicitSignature.getLocalRangeEnd()) {
15372       // This would be much cheaper if we stored TypeLocs instead of
15373       // TypeSourceInfos.
15374       TypeLoc Result = ExplicitSignature.getReturnLoc();
15375       unsigned Size = Result.getFullDataSize();
15376       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15377       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15378 
15379       ExplicitSignature = FunctionProtoTypeLoc();
15380     }
15381   }
15382 
15383   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15384   CurBlock->FunctionType = T;
15385 
15386   const auto *Fn = T->castAs<FunctionType>();
15387   QualType RetTy = Fn->getReturnType();
15388   bool isVariadic =
15389       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15390 
15391   CurBlock->TheDecl->setIsVariadic(isVariadic);
15392 
15393   // Context.DependentTy is used as a placeholder for a missing block
15394   // return type.  TODO:  what should we do with declarators like:
15395   //   ^ * { ... }
15396   // If the answer is "apply template argument deduction"....
15397   if (RetTy != Context.DependentTy) {
15398     CurBlock->ReturnType = RetTy;
15399     CurBlock->TheDecl->setBlockMissingReturnType(false);
15400     CurBlock->HasImplicitReturnType = false;
15401   }
15402 
15403   // Push block parameters from the declarator if we had them.
15404   SmallVector<ParmVarDecl*, 8> Params;
15405   if (ExplicitSignature) {
15406     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15407       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15408       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15409           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15410         // Diagnose this as an extension in C17 and earlier.
15411         if (!getLangOpts().C2x)
15412           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15413       }
15414       Params.push_back(Param);
15415     }
15416 
15417   // Fake up parameter variables if we have a typedef, like
15418   //   ^ fntype { ... }
15419   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15420     for (const auto &I : Fn->param_types()) {
15421       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15422           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15423       Params.push_back(Param);
15424     }
15425   }
15426 
15427   // Set the parameters on the block decl.
15428   if (!Params.empty()) {
15429     CurBlock->TheDecl->setParams(Params);
15430     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15431                              /*CheckParameterNames=*/false);
15432   }
15433 
15434   // Finally we can process decl attributes.
15435   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15436 
15437   // Put the parameter variables in scope.
15438   for (auto AI : CurBlock->TheDecl->parameters()) {
15439     AI->setOwningFunction(CurBlock->TheDecl);
15440 
15441     // If this has an identifier, add it to the scope stack.
15442     if (AI->getIdentifier()) {
15443       CheckShadow(CurBlock->TheScope, AI);
15444 
15445       PushOnScopeChains(AI, CurBlock->TheScope);
15446     }
15447   }
15448 }
15449 
15450 /// ActOnBlockError - If there is an error parsing a block, this callback
15451 /// is invoked to pop the information about the block from the action impl.
15452 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15453   // Leave the expression-evaluation context.
15454   DiscardCleanupsInEvaluationContext();
15455   PopExpressionEvaluationContext();
15456 
15457   // Pop off CurBlock, handle nested blocks.
15458   PopDeclContext();
15459   PopFunctionScopeInfo();
15460 }
15461 
15462 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15463 /// literal was successfully completed.  ^(int x){...}
15464 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15465                                     Stmt *Body, Scope *CurScope) {
15466   // If blocks are disabled, emit an error.
15467   if (!LangOpts.Blocks)
15468     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15469 
15470   // Leave the expression-evaluation context.
15471   if (hasAnyUnrecoverableErrorsInThisFunction())
15472     DiscardCleanupsInEvaluationContext();
15473   assert(!Cleanup.exprNeedsCleanups() &&
15474          "cleanups within block not correctly bound!");
15475   PopExpressionEvaluationContext();
15476 
15477   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15478   BlockDecl *BD = BSI->TheDecl;
15479 
15480   if (BSI->HasImplicitReturnType)
15481     deduceClosureReturnType(*BSI);
15482 
15483   QualType RetTy = Context.VoidTy;
15484   if (!BSI->ReturnType.isNull())
15485     RetTy = BSI->ReturnType;
15486 
15487   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15488   QualType BlockTy;
15489 
15490   // If the user wrote a function type in some form, try to use that.
15491   if (!BSI->FunctionType.isNull()) {
15492     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15493 
15494     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15495     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15496 
15497     // Turn protoless block types into nullary block types.
15498     if (isa<FunctionNoProtoType>(FTy)) {
15499       FunctionProtoType::ExtProtoInfo EPI;
15500       EPI.ExtInfo = Ext;
15501       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15502 
15503     // Otherwise, if we don't need to change anything about the function type,
15504     // preserve its sugar structure.
15505     } else if (FTy->getReturnType() == RetTy &&
15506                (!NoReturn || FTy->getNoReturnAttr())) {
15507       BlockTy = BSI->FunctionType;
15508 
15509     // Otherwise, make the minimal modifications to the function type.
15510     } else {
15511       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15512       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15513       EPI.TypeQuals = Qualifiers();
15514       EPI.ExtInfo = Ext;
15515       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15516     }
15517 
15518   // If we don't have a function type, just build one from nothing.
15519   } else {
15520     FunctionProtoType::ExtProtoInfo EPI;
15521     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15522     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15523   }
15524 
15525   DiagnoseUnusedParameters(BD->parameters());
15526   BlockTy = Context.getBlockPointerType(BlockTy);
15527 
15528   // If needed, diagnose invalid gotos and switches in the block.
15529   if (getCurFunction()->NeedsScopeChecking() &&
15530       !PP.isCodeCompletionEnabled())
15531     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15532 
15533   BD->setBody(cast<CompoundStmt>(Body));
15534 
15535   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15536     DiagnoseUnguardedAvailabilityViolations(BD);
15537 
15538   // Try to apply the named return value optimization. We have to check again
15539   // if we can do this, though, because blocks keep return statements around
15540   // to deduce an implicit return type.
15541   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15542       !BD->isDependentContext())
15543     computeNRVO(Body, BSI);
15544 
15545   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15546       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15547     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15548                           NTCUK_Destruct|NTCUK_Copy);
15549 
15550   PopDeclContext();
15551 
15552   // Set the captured variables on the block.
15553   SmallVector<BlockDecl::Capture, 4> Captures;
15554   for (Capture &Cap : BSI->Captures) {
15555     if (Cap.isInvalid() || Cap.isThisCapture())
15556       continue;
15557 
15558     VarDecl *Var = Cap.getVariable();
15559     Expr *CopyExpr = nullptr;
15560     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15561       if (const RecordType *Record =
15562               Cap.getCaptureType()->getAs<RecordType>()) {
15563         // The capture logic needs the destructor, so make sure we mark it.
15564         // Usually this is unnecessary because most local variables have
15565         // their destructors marked at declaration time, but parameters are
15566         // an exception because it's technically only the call site that
15567         // actually requires the destructor.
15568         if (isa<ParmVarDecl>(Var))
15569           FinalizeVarWithDestructor(Var, Record);
15570 
15571         // Enter a separate potentially-evaluated context while building block
15572         // initializers to isolate their cleanups from those of the block
15573         // itself.
15574         // FIXME: Is this appropriate even when the block itself occurs in an
15575         // unevaluated operand?
15576         EnterExpressionEvaluationContext EvalContext(
15577             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15578 
15579         SourceLocation Loc = Cap.getLocation();
15580 
15581         ExprResult Result = BuildDeclarationNameExpr(
15582             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15583 
15584         // According to the blocks spec, the capture of a variable from
15585         // the stack requires a const copy constructor.  This is not true
15586         // of the copy/move done to move a __block variable to the heap.
15587         if (!Result.isInvalid() &&
15588             !Result.get()->getType().isConstQualified()) {
15589           Result = ImpCastExprToType(Result.get(),
15590                                      Result.get()->getType().withConst(),
15591                                      CK_NoOp, VK_LValue);
15592         }
15593 
15594         if (!Result.isInvalid()) {
15595           Result = PerformCopyInitialization(
15596               InitializedEntity::InitializeBlock(Var->getLocation(),
15597                                                  Cap.getCaptureType(), false),
15598               Loc, Result.get());
15599         }
15600 
15601         // Build a full-expression copy expression if initialization
15602         // succeeded and used a non-trivial constructor.  Recover from
15603         // errors by pretending that the copy isn't necessary.
15604         if (!Result.isInvalid() &&
15605             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15606                 ->isTrivial()) {
15607           Result = MaybeCreateExprWithCleanups(Result);
15608           CopyExpr = Result.get();
15609         }
15610       }
15611     }
15612 
15613     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15614                               CopyExpr);
15615     Captures.push_back(NewCap);
15616   }
15617   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15618 
15619   // Pop the block scope now but keep it alive to the end of this function.
15620   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15621   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15622 
15623   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15624 
15625   // If the block isn't obviously global, i.e. it captures anything at
15626   // all, then we need to do a few things in the surrounding context:
15627   if (Result->getBlockDecl()->hasCaptures()) {
15628     // First, this expression has a new cleanup object.
15629     ExprCleanupObjects.push_back(Result->getBlockDecl());
15630     Cleanup.setExprNeedsCleanups(true);
15631 
15632     // It also gets a branch-protected scope if any of the captured
15633     // variables needs destruction.
15634     for (const auto &CI : Result->getBlockDecl()->captures()) {
15635       const VarDecl *var = CI.getVariable();
15636       if (var->getType().isDestructedType() != QualType::DK_none) {
15637         setFunctionHasBranchProtectedScope();
15638         break;
15639       }
15640     }
15641   }
15642 
15643   if (getCurFunction())
15644     getCurFunction()->addBlock(BD);
15645 
15646   return Result;
15647 }
15648 
15649 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15650                             SourceLocation RPLoc) {
15651   TypeSourceInfo *TInfo;
15652   GetTypeFromParser(Ty, &TInfo);
15653   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15654 }
15655 
15656 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15657                                 Expr *E, TypeSourceInfo *TInfo,
15658                                 SourceLocation RPLoc) {
15659   Expr *OrigExpr = E;
15660   bool IsMS = false;
15661 
15662   // CUDA device code does not support varargs.
15663   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15664     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15665       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15666       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15667         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15668     }
15669   }
15670 
15671   // NVPTX does not support va_arg expression.
15672   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15673       Context.getTargetInfo().getTriple().isNVPTX())
15674     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15675 
15676   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15677   // as Microsoft ABI on an actual Microsoft platform, where
15678   // __builtin_ms_va_list and __builtin_va_list are the same.)
15679   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15680       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15681     QualType MSVaListType = Context.getBuiltinMSVaListType();
15682     if (Context.hasSameType(MSVaListType, E->getType())) {
15683       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15684         return ExprError();
15685       IsMS = true;
15686     }
15687   }
15688 
15689   // Get the va_list type
15690   QualType VaListType = Context.getBuiltinVaListType();
15691   if (!IsMS) {
15692     if (VaListType->isArrayType()) {
15693       // Deal with implicit array decay; for example, on x86-64,
15694       // va_list is an array, but it's supposed to decay to
15695       // a pointer for va_arg.
15696       VaListType = Context.getArrayDecayedType(VaListType);
15697       // Make sure the input expression also decays appropriately.
15698       ExprResult Result = UsualUnaryConversions(E);
15699       if (Result.isInvalid())
15700         return ExprError();
15701       E = Result.get();
15702     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15703       // If va_list is a record type and we are compiling in C++ mode,
15704       // check the argument using reference binding.
15705       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15706           Context, Context.getLValueReferenceType(VaListType), false);
15707       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15708       if (Init.isInvalid())
15709         return ExprError();
15710       E = Init.getAs<Expr>();
15711     } else {
15712       // Otherwise, the va_list argument must be an l-value because
15713       // it is modified by va_arg.
15714       if (!E->isTypeDependent() &&
15715           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15716         return ExprError();
15717     }
15718   }
15719 
15720   if (!IsMS && !E->isTypeDependent() &&
15721       !Context.hasSameType(VaListType, E->getType()))
15722     return ExprError(
15723         Diag(E->getBeginLoc(),
15724              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15725         << OrigExpr->getType() << E->getSourceRange());
15726 
15727   if (!TInfo->getType()->isDependentType()) {
15728     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15729                             diag::err_second_parameter_to_va_arg_incomplete,
15730                             TInfo->getTypeLoc()))
15731       return ExprError();
15732 
15733     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15734                                TInfo->getType(),
15735                                diag::err_second_parameter_to_va_arg_abstract,
15736                                TInfo->getTypeLoc()))
15737       return ExprError();
15738 
15739     if (!TInfo->getType().isPODType(Context)) {
15740       Diag(TInfo->getTypeLoc().getBeginLoc(),
15741            TInfo->getType()->isObjCLifetimeType()
15742              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15743              : diag::warn_second_parameter_to_va_arg_not_pod)
15744         << TInfo->getType()
15745         << TInfo->getTypeLoc().getSourceRange();
15746     }
15747 
15748     // Check for va_arg where arguments of the given type will be promoted
15749     // (i.e. this va_arg is guaranteed to have undefined behavior).
15750     QualType PromoteType;
15751     if (TInfo->getType()->isPromotableIntegerType()) {
15752       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15753       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15754         PromoteType = QualType();
15755     }
15756     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15757       PromoteType = Context.DoubleTy;
15758     if (!PromoteType.isNull())
15759       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15760                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15761                           << TInfo->getType()
15762                           << PromoteType
15763                           << TInfo->getTypeLoc().getSourceRange());
15764   }
15765 
15766   QualType T = TInfo->getType().getNonLValueExprType(Context);
15767   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15768 }
15769 
15770 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15771   // The type of __null will be int or long, depending on the size of
15772   // pointers on the target.
15773   QualType Ty;
15774   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15775   if (pw == Context.getTargetInfo().getIntWidth())
15776     Ty = Context.IntTy;
15777   else if (pw == Context.getTargetInfo().getLongWidth())
15778     Ty = Context.LongTy;
15779   else if (pw == Context.getTargetInfo().getLongLongWidth())
15780     Ty = Context.LongLongTy;
15781   else {
15782     llvm_unreachable("I don't know size of pointer!");
15783   }
15784 
15785   return new (Context) GNUNullExpr(Ty, TokenLoc);
15786 }
15787 
15788 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15789                                     SourceLocation BuiltinLoc,
15790                                     SourceLocation RPLoc) {
15791   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15792 }
15793 
15794 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15795                                     SourceLocation BuiltinLoc,
15796                                     SourceLocation RPLoc,
15797                                     DeclContext *ParentContext) {
15798   return new (Context)
15799       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15800 }
15801 
15802 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15803                                         bool Diagnose) {
15804   if (!getLangOpts().ObjC)
15805     return false;
15806 
15807   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15808   if (!PT)
15809     return false;
15810   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15811 
15812   // Ignore any parens, implicit casts (should only be
15813   // array-to-pointer decays), and not-so-opaque values.  The last is
15814   // important for making this trigger for property assignments.
15815   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15816   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15817     if (OV->getSourceExpr())
15818       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15819 
15820   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15821     if (!PT->isObjCIdType() &&
15822         !(ID && ID->getIdentifier()->isStr("NSString")))
15823       return false;
15824     if (!SL->isAscii())
15825       return false;
15826 
15827     if (Diagnose) {
15828       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15829           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15830       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15831     }
15832     return true;
15833   }
15834 
15835   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15836       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15837       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15838       !SrcExpr->isNullPointerConstant(
15839           getASTContext(), Expr::NPC_NeverValueDependent)) {
15840     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15841       return false;
15842     if (Diagnose) {
15843       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15844           << /*number*/1
15845           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15846       Expr *NumLit =
15847           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15848       if (NumLit)
15849         Exp = NumLit;
15850     }
15851     return true;
15852   }
15853 
15854   return false;
15855 }
15856 
15857 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15858                                               const Expr *SrcExpr) {
15859   if (!DstType->isFunctionPointerType() ||
15860       !SrcExpr->getType()->isFunctionType())
15861     return false;
15862 
15863   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15864   if (!DRE)
15865     return false;
15866 
15867   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15868   if (!FD)
15869     return false;
15870 
15871   return !S.checkAddressOfFunctionIsAvailable(FD,
15872                                               /*Complain=*/true,
15873                                               SrcExpr->getBeginLoc());
15874 }
15875 
15876 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15877                                     SourceLocation Loc,
15878                                     QualType DstType, QualType SrcType,
15879                                     Expr *SrcExpr, AssignmentAction Action,
15880                                     bool *Complained) {
15881   if (Complained)
15882     *Complained = false;
15883 
15884   // Decode the result (notice that AST's are still created for extensions).
15885   bool CheckInferredResultType = false;
15886   bool isInvalid = false;
15887   unsigned DiagKind = 0;
15888   ConversionFixItGenerator ConvHints;
15889   bool MayHaveConvFixit = false;
15890   bool MayHaveFunctionDiff = false;
15891   const ObjCInterfaceDecl *IFace = nullptr;
15892   const ObjCProtocolDecl *PDecl = nullptr;
15893 
15894   switch (ConvTy) {
15895   case Compatible:
15896       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15897       return false;
15898 
15899   case PointerToInt:
15900     if (getLangOpts().CPlusPlus) {
15901       DiagKind = diag::err_typecheck_convert_pointer_int;
15902       isInvalid = true;
15903     } else {
15904       DiagKind = diag::ext_typecheck_convert_pointer_int;
15905     }
15906     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15907     MayHaveConvFixit = true;
15908     break;
15909   case IntToPointer:
15910     if (getLangOpts().CPlusPlus) {
15911       DiagKind = diag::err_typecheck_convert_int_pointer;
15912       isInvalid = true;
15913     } else {
15914       DiagKind = diag::ext_typecheck_convert_int_pointer;
15915     }
15916     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15917     MayHaveConvFixit = true;
15918     break;
15919   case IncompatibleFunctionPointer:
15920     if (getLangOpts().CPlusPlus) {
15921       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15922       isInvalid = true;
15923     } else {
15924       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15925     }
15926     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15927     MayHaveConvFixit = true;
15928     break;
15929   case IncompatiblePointer:
15930     if (Action == AA_Passing_CFAudited) {
15931       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15932     } else if (getLangOpts().CPlusPlus) {
15933       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15934       isInvalid = true;
15935     } else {
15936       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15937     }
15938     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15939       SrcType->isObjCObjectPointerType();
15940     if (!CheckInferredResultType) {
15941       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15942     } else if (CheckInferredResultType) {
15943       SrcType = SrcType.getUnqualifiedType();
15944       DstType = DstType.getUnqualifiedType();
15945     }
15946     MayHaveConvFixit = true;
15947     break;
15948   case IncompatiblePointerSign:
15949     if (getLangOpts().CPlusPlus) {
15950       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15951       isInvalid = true;
15952     } else {
15953       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15954     }
15955     break;
15956   case FunctionVoidPointer:
15957     if (getLangOpts().CPlusPlus) {
15958       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15959       isInvalid = true;
15960     } else {
15961       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15962     }
15963     break;
15964   case IncompatiblePointerDiscardsQualifiers: {
15965     // Perform array-to-pointer decay if necessary.
15966     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15967 
15968     isInvalid = true;
15969 
15970     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15971     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15972     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15973       DiagKind = diag::err_typecheck_incompatible_address_space;
15974       break;
15975 
15976     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15977       DiagKind = diag::err_typecheck_incompatible_ownership;
15978       break;
15979     }
15980 
15981     llvm_unreachable("unknown error case for discarding qualifiers!");
15982     // fallthrough
15983   }
15984   case CompatiblePointerDiscardsQualifiers:
15985     // If the qualifiers lost were because we were applying the
15986     // (deprecated) C++ conversion from a string literal to a char*
15987     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15988     // Ideally, this check would be performed in
15989     // checkPointerTypesForAssignment. However, that would require a
15990     // bit of refactoring (so that the second argument is an
15991     // expression, rather than a type), which should be done as part
15992     // of a larger effort to fix checkPointerTypesForAssignment for
15993     // C++ semantics.
15994     if (getLangOpts().CPlusPlus &&
15995         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15996       return false;
15997     if (getLangOpts().CPlusPlus) {
15998       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15999       isInvalid = true;
16000     } else {
16001       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16002     }
16003 
16004     break;
16005   case IncompatibleNestedPointerQualifiers:
16006     if (getLangOpts().CPlusPlus) {
16007       isInvalid = true;
16008       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16009     } else {
16010       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16011     }
16012     break;
16013   case IncompatibleNestedPointerAddressSpaceMismatch:
16014     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16015     isInvalid = true;
16016     break;
16017   case IntToBlockPointer:
16018     DiagKind = diag::err_int_to_block_pointer;
16019     isInvalid = true;
16020     break;
16021   case IncompatibleBlockPointer:
16022     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16023     isInvalid = true;
16024     break;
16025   case IncompatibleObjCQualifiedId: {
16026     if (SrcType->isObjCQualifiedIdType()) {
16027       const ObjCObjectPointerType *srcOPT =
16028                 SrcType->castAs<ObjCObjectPointerType>();
16029       for (auto *srcProto : srcOPT->quals()) {
16030         PDecl = srcProto;
16031         break;
16032       }
16033       if (const ObjCInterfaceType *IFaceT =
16034             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16035         IFace = IFaceT->getDecl();
16036     }
16037     else if (DstType->isObjCQualifiedIdType()) {
16038       const ObjCObjectPointerType *dstOPT =
16039         DstType->castAs<ObjCObjectPointerType>();
16040       for (auto *dstProto : dstOPT->quals()) {
16041         PDecl = dstProto;
16042         break;
16043       }
16044       if (const ObjCInterfaceType *IFaceT =
16045             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16046         IFace = IFaceT->getDecl();
16047     }
16048     if (getLangOpts().CPlusPlus) {
16049       DiagKind = diag::err_incompatible_qualified_id;
16050       isInvalid = true;
16051     } else {
16052       DiagKind = diag::warn_incompatible_qualified_id;
16053     }
16054     break;
16055   }
16056   case IncompatibleVectors:
16057     if (getLangOpts().CPlusPlus) {
16058       DiagKind = diag::err_incompatible_vectors;
16059       isInvalid = true;
16060     } else {
16061       DiagKind = diag::warn_incompatible_vectors;
16062     }
16063     break;
16064   case IncompatibleObjCWeakRef:
16065     DiagKind = diag::err_arc_weak_unavailable_assign;
16066     isInvalid = true;
16067     break;
16068   case Incompatible:
16069     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16070       if (Complained)
16071         *Complained = true;
16072       return true;
16073     }
16074 
16075     DiagKind = diag::err_typecheck_convert_incompatible;
16076     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16077     MayHaveConvFixit = true;
16078     isInvalid = true;
16079     MayHaveFunctionDiff = true;
16080     break;
16081   }
16082 
16083   QualType FirstType, SecondType;
16084   switch (Action) {
16085   case AA_Assigning:
16086   case AA_Initializing:
16087     // The destination type comes first.
16088     FirstType = DstType;
16089     SecondType = SrcType;
16090     break;
16091 
16092   case AA_Returning:
16093   case AA_Passing:
16094   case AA_Passing_CFAudited:
16095   case AA_Converting:
16096   case AA_Sending:
16097   case AA_Casting:
16098     // The source type comes first.
16099     FirstType = SrcType;
16100     SecondType = DstType;
16101     break;
16102   }
16103 
16104   PartialDiagnostic FDiag = PDiag(DiagKind);
16105   if (Action == AA_Passing_CFAudited)
16106     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16107   else
16108     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16109 
16110   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16111       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16112     auto isPlainChar = [](const clang::Type *Type) {
16113       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16114              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16115     };
16116     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16117               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16118   }
16119 
16120   // If we can fix the conversion, suggest the FixIts.
16121   if (!ConvHints.isNull()) {
16122     for (FixItHint &H : ConvHints.Hints)
16123       FDiag << H;
16124   }
16125 
16126   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16127 
16128   if (MayHaveFunctionDiff)
16129     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16130 
16131   Diag(Loc, FDiag);
16132   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16133        DiagKind == diag::err_incompatible_qualified_id) &&
16134       PDecl && IFace && !IFace->hasDefinition())
16135     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16136         << IFace << PDecl;
16137 
16138   if (SecondType == Context.OverloadTy)
16139     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16140                               FirstType, /*TakingAddress=*/true);
16141 
16142   if (CheckInferredResultType)
16143     EmitRelatedResultTypeNote(SrcExpr);
16144 
16145   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16146     EmitRelatedResultTypeNoteForReturn(DstType);
16147 
16148   if (Complained)
16149     *Complained = true;
16150   return isInvalid;
16151 }
16152 
16153 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16154                                                  llvm::APSInt *Result,
16155                                                  AllowFoldKind CanFold) {
16156   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16157   public:
16158     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16159                                              QualType T) override {
16160       return S.Diag(Loc, diag::err_ice_not_integral)
16161              << T << S.LangOpts.CPlusPlus;
16162     }
16163     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16164       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16165     }
16166   } Diagnoser;
16167 
16168   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16169 }
16170 
16171 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16172                                                  llvm::APSInt *Result,
16173                                                  unsigned DiagID,
16174                                                  AllowFoldKind CanFold) {
16175   class IDDiagnoser : public VerifyICEDiagnoser {
16176     unsigned DiagID;
16177 
16178   public:
16179     IDDiagnoser(unsigned DiagID)
16180       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16181 
16182     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16183       return S.Diag(Loc, DiagID);
16184     }
16185   } Diagnoser(DiagID);
16186 
16187   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16188 }
16189 
16190 Sema::SemaDiagnosticBuilder
16191 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16192                                              QualType T) {
16193   return diagnoseNotICE(S, Loc);
16194 }
16195 
16196 Sema::SemaDiagnosticBuilder
16197 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16198   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16199 }
16200 
16201 ExprResult
16202 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16203                                       VerifyICEDiagnoser &Diagnoser,
16204                                       AllowFoldKind CanFold) {
16205   SourceLocation DiagLoc = E->getBeginLoc();
16206 
16207   if (getLangOpts().CPlusPlus11) {
16208     // C++11 [expr.const]p5:
16209     //   If an expression of literal class type is used in a context where an
16210     //   integral constant expression is required, then that class type shall
16211     //   have a single non-explicit conversion function to an integral or
16212     //   unscoped enumeration type
16213     ExprResult Converted;
16214     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16215       VerifyICEDiagnoser &BaseDiagnoser;
16216     public:
16217       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16218           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16219                                 BaseDiagnoser.Suppress, true),
16220             BaseDiagnoser(BaseDiagnoser) {}
16221 
16222       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16223                                            QualType T) override {
16224         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16225       }
16226 
16227       SemaDiagnosticBuilder diagnoseIncomplete(
16228           Sema &S, SourceLocation Loc, QualType T) override {
16229         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16230       }
16231 
16232       SemaDiagnosticBuilder diagnoseExplicitConv(
16233           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16234         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16235       }
16236 
16237       SemaDiagnosticBuilder noteExplicitConv(
16238           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16239         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16240                  << ConvTy->isEnumeralType() << ConvTy;
16241       }
16242 
16243       SemaDiagnosticBuilder diagnoseAmbiguous(
16244           Sema &S, SourceLocation Loc, QualType T) override {
16245         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16246       }
16247 
16248       SemaDiagnosticBuilder noteAmbiguous(
16249           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16250         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16251                  << ConvTy->isEnumeralType() << ConvTy;
16252       }
16253 
16254       SemaDiagnosticBuilder diagnoseConversion(
16255           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16256         llvm_unreachable("conversion functions are permitted");
16257       }
16258     } ConvertDiagnoser(Diagnoser);
16259 
16260     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16261                                                     ConvertDiagnoser);
16262     if (Converted.isInvalid())
16263       return Converted;
16264     E = Converted.get();
16265     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16266       return ExprError();
16267   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16268     // An ICE must be of integral or unscoped enumeration type.
16269     if (!Diagnoser.Suppress)
16270       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16271           << E->getSourceRange();
16272     return ExprError();
16273   }
16274 
16275   ExprResult RValueExpr = DefaultLvalueConversion(E);
16276   if (RValueExpr.isInvalid())
16277     return ExprError();
16278 
16279   E = RValueExpr.get();
16280 
16281   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16282   // in the non-ICE case.
16283   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16284     if (Result)
16285       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16286     if (!isa<ConstantExpr>(E))
16287       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16288                  : ConstantExpr::Create(Context, E);
16289     return E;
16290   }
16291 
16292   Expr::EvalResult EvalResult;
16293   SmallVector<PartialDiagnosticAt, 8> Notes;
16294   EvalResult.Diag = &Notes;
16295 
16296   // Try to evaluate the expression, and produce diagnostics explaining why it's
16297   // not a constant expression as a side-effect.
16298   bool Folded =
16299       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16300       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16301 
16302   if (!isa<ConstantExpr>(E))
16303     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16304 
16305   // In C++11, we can rely on diagnostics being produced for any expression
16306   // which is not a constant expression. If no diagnostics were produced, then
16307   // this is a constant expression.
16308   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16309     if (Result)
16310       *Result = EvalResult.Val.getInt();
16311     return E;
16312   }
16313 
16314   // If our only note is the usual "invalid subexpression" note, just point
16315   // the caret at its location rather than producing an essentially
16316   // redundant note.
16317   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16318         diag::note_invalid_subexpr_in_const_expr) {
16319     DiagLoc = Notes[0].first;
16320     Notes.clear();
16321   }
16322 
16323   if (!Folded || !CanFold) {
16324     if (!Diagnoser.Suppress) {
16325       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16326       for (const PartialDiagnosticAt &Note : Notes)
16327         Diag(Note.first, Note.second);
16328     }
16329 
16330     return ExprError();
16331   }
16332 
16333   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16334   for (const PartialDiagnosticAt &Note : Notes)
16335     Diag(Note.first, Note.second);
16336 
16337   if (Result)
16338     *Result = EvalResult.Val.getInt();
16339   return E;
16340 }
16341 
16342 namespace {
16343   // Handle the case where we conclude a expression which we speculatively
16344   // considered to be unevaluated is actually evaluated.
16345   class TransformToPE : public TreeTransform<TransformToPE> {
16346     typedef TreeTransform<TransformToPE> BaseTransform;
16347 
16348   public:
16349     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16350 
16351     // Make sure we redo semantic analysis
16352     bool AlwaysRebuild() { return true; }
16353     bool ReplacingOriginal() { return true; }
16354 
16355     // We need to special-case DeclRefExprs referring to FieldDecls which
16356     // are not part of a member pointer formation; normal TreeTransforming
16357     // doesn't catch this case because of the way we represent them in the AST.
16358     // FIXME: This is a bit ugly; is it really the best way to handle this
16359     // case?
16360     //
16361     // Error on DeclRefExprs referring to FieldDecls.
16362     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16363       if (isa<FieldDecl>(E->getDecl()) &&
16364           !SemaRef.isUnevaluatedContext())
16365         return SemaRef.Diag(E->getLocation(),
16366                             diag::err_invalid_non_static_member_use)
16367             << E->getDecl() << E->getSourceRange();
16368 
16369       return BaseTransform::TransformDeclRefExpr(E);
16370     }
16371 
16372     // Exception: filter out member pointer formation
16373     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16374       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16375         return E;
16376 
16377       return BaseTransform::TransformUnaryOperator(E);
16378     }
16379 
16380     // The body of a lambda-expression is in a separate expression evaluation
16381     // context so never needs to be transformed.
16382     // FIXME: Ideally we wouldn't transform the closure type either, and would
16383     // just recreate the capture expressions and lambda expression.
16384     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16385       return SkipLambdaBody(E, Body);
16386     }
16387   };
16388 }
16389 
16390 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16391   assert(isUnevaluatedContext() &&
16392          "Should only transform unevaluated expressions");
16393   ExprEvalContexts.back().Context =
16394       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16395   if (isUnevaluatedContext())
16396     return E;
16397   return TransformToPE(*this).TransformExpr(E);
16398 }
16399 
16400 void
16401 Sema::PushExpressionEvaluationContext(
16402     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16403     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16404   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16405                                 LambdaContextDecl, ExprContext);
16406   Cleanup.reset();
16407   if (!MaybeODRUseExprs.empty())
16408     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16409 }
16410 
16411 void
16412 Sema::PushExpressionEvaluationContext(
16413     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16414     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16415   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16416   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16417 }
16418 
16419 namespace {
16420 
16421 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16422   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16423   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16424     if (E->getOpcode() == UO_Deref)
16425       return CheckPossibleDeref(S, E->getSubExpr());
16426   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16427     return CheckPossibleDeref(S, E->getBase());
16428   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16429     return CheckPossibleDeref(S, E->getBase());
16430   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16431     QualType Inner;
16432     QualType Ty = E->getType();
16433     if (const auto *Ptr = Ty->getAs<PointerType>())
16434       Inner = Ptr->getPointeeType();
16435     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16436       Inner = Arr->getElementType();
16437     else
16438       return nullptr;
16439 
16440     if (Inner->hasAttr(attr::NoDeref))
16441       return E;
16442   }
16443   return nullptr;
16444 }
16445 
16446 } // namespace
16447 
16448 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16449   for (const Expr *E : Rec.PossibleDerefs) {
16450     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16451     if (DeclRef) {
16452       const ValueDecl *Decl = DeclRef->getDecl();
16453       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16454           << Decl->getName() << E->getSourceRange();
16455       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16456     } else {
16457       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16458           << E->getSourceRange();
16459     }
16460   }
16461   Rec.PossibleDerefs.clear();
16462 }
16463 
16464 /// Check whether E, which is either a discarded-value expression or an
16465 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16466 /// and if so, remove it from the list of volatile-qualified assignments that
16467 /// we are going to warn are deprecated.
16468 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16469   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16470     return;
16471 
16472   // Note: ignoring parens here is not justified by the standard rules, but
16473   // ignoring parentheses seems like a more reasonable approach, and this only
16474   // drives a deprecation warning so doesn't affect conformance.
16475   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16476     if (BO->getOpcode() == BO_Assign) {
16477       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16478       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16479                  LHSs.end());
16480     }
16481   }
16482 }
16483 
16484 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16485   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16486       RebuildingImmediateInvocation)
16487     return E;
16488 
16489   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16490   /// It's OK if this fails; we'll also remove this in
16491   /// HandleImmediateInvocations, but catching it here allows us to avoid
16492   /// walking the AST looking for it in simple cases.
16493   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16494     if (auto *DeclRef =
16495             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16496       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16497 
16498   E = MaybeCreateExprWithCleanups(E);
16499 
16500   ConstantExpr *Res = ConstantExpr::Create(
16501       getASTContext(), E.get(),
16502       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16503                                    getASTContext()),
16504       /*IsImmediateInvocation*/ true);
16505   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16506   return Res;
16507 }
16508 
16509 static void EvaluateAndDiagnoseImmediateInvocation(
16510     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16511   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16512   Expr::EvalResult Eval;
16513   Eval.Diag = &Notes;
16514   ConstantExpr *CE = Candidate.getPointer();
16515   bool Result = CE->EvaluateAsConstantExpr(
16516       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16517   if (!Result || !Notes.empty()) {
16518     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16519     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16520       InnerExpr = FunctionalCast->getSubExpr();
16521     FunctionDecl *FD = nullptr;
16522     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16523       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16524     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16525       FD = Call->getConstructor();
16526     else
16527       llvm_unreachable("unhandled decl kind");
16528     assert(FD->isConsteval());
16529     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16530     for (auto &Note : Notes)
16531       SemaRef.Diag(Note.first, Note.second);
16532     return;
16533   }
16534   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16535 }
16536 
16537 static void RemoveNestedImmediateInvocation(
16538     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16539     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16540   struct ComplexRemove : TreeTransform<ComplexRemove> {
16541     using Base = TreeTransform<ComplexRemove>;
16542     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16543     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16544     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16545         CurrentII;
16546     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16547                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16548                   SmallVector<Sema::ImmediateInvocationCandidate,
16549                               4>::reverse_iterator Current)
16550         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16551     void RemoveImmediateInvocation(ConstantExpr* E) {
16552       auto It = std::find_if(CurrentII, IISet.rend(),
16553                              [E](Sema::ImmediateInvocationCandidate Elem) {
16554                                return Elem.getPointer() == E;
16555                              });
16556       assert(It != IISet.rend() &&
16557              "ConstantExpr marked IsImmediateInvocation should "
16558              "be present");
16559       It->setInt(1); // Mark as deleted
16560     }
16561     ExprResult TransformConstantExpr(ConstantExpr *E) {
16562       if (!E->isImmediateInvocation())
16563         return Base::TransformConstantExpr(E);
16564       RemoveImmediateInvocation(E);
16565       return Base::TransformExpr(E->getSubExpr());
16566     }
16567     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16568     /// we need to remove its DeclRefExpr from the DRSet.
16569     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16570       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16571       return Base::TransformCXXOperatorCallExpr(E);
16572     }
16573     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16574     /// here.
16575     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16576       if (!Init)
16577         return Init;
16578       /// ConstantExpr are the first layer of implicit node to be removed so if
16579       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16580       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16581         if (CE->isImmediateInvocation())
16582           RemoveImmediateInvocation(CE);
16583       return Base::TransformInitializer(Init, NotCopyInit);
16584     }
16585     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16586       DRSet.erase(E);
16587       return E;
16588     }
16589     bool AlwaysRebuild() { return false; }
16590     bool ReplacingOriginal() { return true; }
16591     bool AllowSkippingCXXConstructExpr() {
16592       bool Res = AllowSkippingFirstCXXConstructExpr;
16593       AllowSkippingFirstCXXConstructExpr = true;
16594       return Res;
16595     }
16596     bool AllowSkippingFirstCXXConstructExpr = true;
16597   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16598                 Rec.ImmediateInvocationCandidates, It);
16599 
16600   /// CXXConstructExpr with a single argument are getting skipped by
16601   /// TreeTransform in some situtation because they could be implicit. This
16602   /// can only occur for the top-level CXXConstructExpr because it is used
16603   /// nowhere in the expression being transformed therefore will not be rebuilt.
16604   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16605   /// skipping the first CXXConstructExpr.
16606   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16607     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16608 
16609   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16610   assert(Res.isUsable());
16611   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16612   It->getPointer()->setSubExpr(Res.get());
16613 }
16614 
16615 static void
16616 HandleImmediateInvocations(Sema &SemaRef,
16617                            Sema::ExpressionEvaluationContextRecord &Rec) {
16618   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16619        Rec.ReferenceToConsteval.size() == 0) ||
16620       SemaRef.RebuildingImmediateInvocation)
16621     return;
16622 
16623   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16624   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16625   /// need to remove ReferenceToConsteval in the immediate invocation.
16626   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16627 
16628     /// Prevent sema calls during the tree transform from adding pointers that
16629     /// are already in the sets.
16630     llvm::SaveAndRestore<bool> DisableIITracking(
16631         SemaRef.RebuildingImmediateInvocation, true);
16632 
16633     /// Prevent diagnostic during tree transfrom as they are duplicates
16634     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16635 
16636     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16637          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16638       if (!It->getInt())
16639         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16640   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16641              Rec.ReferenceToConsteval.size()) {
16642     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16643       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16644       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16645       bool VisitDeclRefExpr(DeclRefExpr *E) {
16646         DRSet.erase(E);
16647         return DRSet.size();
16648       }
16649     } Visitor(Rec.ReferenceToConsteval);
16650     Visitor.TraverseStmt(
16651         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16652   }
16653   for (auto CE : Rec.ImmediateInvocationCandidates)
16654     if (!CE.getInt())
16655       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16656   for (auto DR : Rec.ReferenceToConsteval) {
16657     auto *FD = cast<FunctionDecl>(DR->getDecl());
16658     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16659         << FD;
16660     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16661   }
16662 }
16663 
16664 void Sema::PopExpressionEvaluationContext() {
16665   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16666   unsigned NumTypos = Rec.NumTypos;
16667 
16668   if (!Rec.Lambdas.empty()) {
16669     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16670     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16671         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16672       unsigned D;
16673       if (Rec.isUnevaluated()) {
16674         // C++11 [expr.prim.lambda]p2:
16675         //   A lambda-expression shall not appear in an unevaluated operand
16676         //   (Clause 5).
16677         D = diag::err_lambda_unevaluated_operand;
16678       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16679         // C++1y [expr.const]p2:
16680         //   A conditional-expression e is a core constant expression unless the
16681         //   evaluation of e, following the rules of the abstract machine, would
16682         //   evaluate [...] a lambda-expression.
16683         D = diag::err_lambda_in_constant_expression;
16684       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16685         // C++17 [expr.prim.lamda]p2:
16686         // A lambda-expression shall not appear [...] in a template-argument.
16687         D = diag::err_lambda_in_invalid_context;
16688       } else
16689         llvm_unreachable("Couldn't infer lambda error message.");
16690 
16691       for (const auto *L : Rec.Lambdas)
16692         Diag(L->getBeginLoc(), D);
16693     }
16694   }
16695 
16696   WarnOnPendingNoDerefs(Rec);
16697   HandleImmediateInvocations(*this, Rec);
16698 
16699   // Warn on any volatile-qualified simple-assignments that are not discarded-
16700   // value expressions nor unevaluated operands (those cases get removed from
16701   // this list by CheckUnusedVolatileAssignment).
16702   for (auto *BO : Rec.VolatileAssignmentLHSs)
16703     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16704         << BO->getType();
16705 
16706   // When are coming out of an unevaluated context, clear out any
16707   // temporaries that we may have created as part of the evaluation of
16708   // the expression in that context: they aren't relevant because they
16709   // will never be constructed.
16710   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16711     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16712                              ExprCleanupObjects.end());
16713     Cleanup = Rec.ParentCleanup;
16714     CleanupVarDeclMarking();
16715     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16716   // Otherwise, merge the contexts together.
16717   } else {
16718     Cleanup.mergeFrom(Rec.ParentCleanup);
16719     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16720                             Rec.SavedMaybeODRUseExprs.end());
16721   }
16722 
16723   // Pop the current expression evaluation context off the stack.
16724   ExprEvalContexts.pop_back();
16725 
16726   // The global expression evaluation context record is never popped.
16727   ExprEvalContexts.back().NumTypos += NumTypos;
16728 }
16729 
16730 void Sema::DiscardCleanupsInEvaluationContext() {
16731   ExprCleanupObjects.erase(
16732          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16733          ExprCleanupObjects.end());
16734   Cleanup.reset();
16735   MaybeODRUseExprs.clear();
16736 }
16737 
16738 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16739   ExprResult Result = CheckPlaceholderExpr(E);
16740   if (Result.isInvalid())
16741     return ExprError();
16742   E = Result.get();
16743   if (!E->getType()->isVariablyModifiedType())
16744     return E;
16745   return TransformToPotentiallyEvaluated(E);
16746 }
16747 
16748 /// Are we in a context that is potentially constant evaluated per C++20
16749 /// [expr.const]p12?
16750 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16751   /// C++2a [expr.const]p12:
16752   //   An expression or conversion is potentially constant evaluated if it is
16753   switch (SemaRef.ExprEvalContexts.back().Context) {
16754     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16755       // -- a manifestly constant-evaluated expression,
16756     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16757     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16758     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16759       // -- a potentially-evaluated expression,
16760     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16761       // -- an immediate subexpression of a braced-init-list,
16762 
16763       // -- [FIXME] an expression of the form & cast-expression that occurs
16764       //    within a templated entity
16765       // -- a subexpression of one of the above that is not a subexpression of
16766       // a nested unevaluated operand.
16767       return true;
16768 
16769     case Sema::ExpressionEvaluationContext::Unevaluated:
16770     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16771       // Expressions in this context are never evaluated.
16772       return false;
16773   }
16774   llvm_unreachable("Invalid context");
16775 }
16776 
16777 /// Return true if this function has a calling convention that requires mangling
16778 /// in the size of the parameter pack.
16779 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16780   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16781   // we don't need parameter type sizes.
16782   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16783   if (!TT.isOSWindows() || !TT.isX86())
16784     return false;
16785 
16786   // If this is C++ and this isn't an extern "C" function, parameters do not
16787   // need to be complete. In this case, C++ mangling will apply, which doesn't
16788   // use the size of the parameters.
16789   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16790     return false;
16791 
16792   // Stdcall, fastcall, and vectorcall need this special treatment.
16793   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16794   switch (CC) {
16795   case CC_X86StdCall:
16796   case CC_X86FastCall:
16797   case CC_X86VectorCall:
16798     return true;
16799   default:
16800     break;
16801   }
16802   return false;
16803 }
16804 
16805 /// Require that all of the parameter types of function be complete. Normally,
16806 /// parameter types are only required to be complete when a function is called
16807 /// or defined, but to mangle functions with certain calling conventions, the
16808 /// mangler needs to know the size of the parameter list. In this situation,
16809 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16810 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16811 /// result in a linker error. Clang doesn't implement this behavior, and instead
16812 /// attempts to error at compile time.
16813 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16814                                                   SourceLocation Loc) {
16815   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16816     FunctionDecl *FD;
16817     ParmVarDecl *Param;
16818 
16819   public:
16820     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16821         : FD(FD), Param(Param) {}
16822 
16823     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16824       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16825       StringRef CCName;
16826       switch (CC) {
16827       case CC_X86StdCall:
16828         CCName = "stdcall";
16829         break;
16830       case CC_X86FastCall:
16831         CCName = "fastcall";
16832         break;
16833       case CC_X86VectorCall:
16834         CCName = "vectorcall";
16835         break;
16836       default:
16837         llvm_unreachable("CC does not need mangling");
16838       }
16839 
16840       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16841           << Param->getDeclName() << FD->getDeclName() << CCName;
16842     }
16843   };
16844 
16845   for (ParmVarDecl *Param : FD->parameters()) {
16846     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16847     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16848   }
16849 }
16850 
16851 namespace {
16852 enum class OdrUseContext {
16853   /// Declarations in this context are not odr-used.
16854   None,
16855   /// Declarations in this context are formally odr-used, but this is a
16856   /// dependent context.
16857   Dependent,
16858   /// Declarations in this context are odr-used but not actually used (yet).
16859   FormallyOdrUsed,
16860   /// Declarations in this context are used.
16861   Used
16862 };
16863 }
16864 
16865 /// Are we within a context in which references to resolved functions or to
16866 /// variables result in odr-use?
16867 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16868   OdrUseContext Result;
16869 
16870   switch (SemaRef.ExprEvalContexts.back().Context) {
16871     case Sema::ExpressionEvaluationContext::Unevaluated:
16872     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16873     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16874       return OdrUseContext::None;
16875 
16876     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16877     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16878       Result = OdrUseContext::Used;
16879       break;
16880 
16881     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16882       Result = OdrUseContext::FormallyOdrUsed;
16883       break;
16884 
16885     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16886       // A default argument formally results in odr-use, but doesn't actually
16887       // result in a use in any real sense until it itself is used.
16888       Result = OdrUseContext::FormallyOdrUsed;
16889       break;
16890   }
16891 
16892   if (SemaRef.CurContext->isDependentContext())
16893     return OdrUseContext::Dependent;
16894 
16895   return Result;
16896 }
16897 
16898 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16899   if (!Func->isConstexpr())
16900     return false;
16901 
16902   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16903     return true;
16904   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16905   return CCD && CCD->getInheritedConstructor();
16906 }
16907 
16908 /// Mark a function referenced, and check whether it is odr-used
16909 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16910 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16911                                   bool MightBeOdrUse) {
16912   assert(Func && "No function?");
16913 
16914   Func->setReferenced();
16915 
16916   // Recursive functions aren't really used until they're used from some other
16917   // context.
16918   bool IsRecursiveCall = CurContext == Func;
16919 
16920   // C++11 [basic.def.odr]p3:
16921   //   A function whose name appears as a potentially-evaluated expression is
16922   //   odr-used if it is the unique lookup result or the selected member of a
16923   //   set of overloaded functions [...].
16924   //
16925   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16926   // can just check that here.
16927   OdrUseContext OdrUse =
16928       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16929   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16930     OdrUse = OdrUseContext::FormallyOdrUsed;
16931 
16932   // Trivial default constructors and destructors are never actually used.
16933   // FIXME: What about other special members?
16934   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16935       OdrUse == OdrUseContext::Used) {
16936     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16937       if (Constructor->isDefaultConstructor())
16938         OdrUse = OdrUseContext::FormallyOdrUsed;
16939     if (isa<CXXDestructorDecl>(Func))
16940       OdrUse = OdrUseContext::FormallyOdrUsed;
16941   }
16942 
16943   // C++20 [expr.const]p12:
16944   //   A function [...] is needed for constant evaluation if it is [...] a
16945   //   constexpr function that is named by an expression that is potentially
16946   //   constant evaluated
16947   bool NeededForConstantEvaluation =
16948       isPotentiallyConstantEvaluatedContext(*this) &&
16949       isImplicitlyDefinableConstexprFunction(Func);
16950 
16951   // Determine whether we require a function definition to exist, per
16952   // C++11 [temp.inst]p3:
16953   //   Unless a function template specialization has been explicitly
16954   //   instantiated or explicitly specialized, the function template
16955   //   specialization is implicitly instantiated when the specialization is
16956   //   referenced in a context that requires a function definition to exist.
16957   // C++20 [temp.inst]p7:
16958   //   The existence of a definition of a [...] function is considered to
16959   //   affect the semantics of the program if the [...] function is needed for
16960   //   constant evaluation by an expression
16961   // C++20 [basic.def.odr]p10:
16962   //   Every program shall contain exactly one definition of every non-inline
16963   //   function or variable that is odr-used in that program outside of a
16964   //   discarded statement
16965   // C++20 [special]p1:
16966   //   The implementation will implicitly define [defaulted special members]
16967   //   if they are odr-used or needed for constant evaluation.
16968   //
16969   // Note that we skip the implicit instantiation of templates that are only
16970   // used in unused default arguments or by recursive calls to themselves.
16971   // This is formally non-conforming, but seems reasonable in practice.
16972   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16973                                              NeededForConstantEvaluation);
16974 
16975   // C++14 [temp.expl.spec]p6:
16976   //   If a template [...] is explicitly specialized then that specialization
16977   //   shall be declared before the first use of that specialization that would
16978   //   cause an implicit instantiation to take place, in every translation unit
16979   //   in which such a use occurs
16980   if (NeedDefinition &&
16981       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16982        Func->getMemberSpecializationInfo()))
16983     checkSpecializationVisibility(Loc, Func);
16984 
16985   if (getLangOpts().CUDA)
16986     CheckCUDACall(Loc, Func);
16987 
16988   if (getLangOpts().SYCLIsDevice)
16989     checkSYCLDeviceFunction(Loc, Func);
16990 
16991   // If we need a definition, try to create one.
16992   if (NeedDefinition && !Func->getBody()) {
16993     runWithSufficientStackSpace(Loc, [&] {
16994       if (CXXConstructorDecl *Constructor =
16995               dyn_cast<CXXConstructorDecl>(Func)) {
16996         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16997         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16998           if (Constructor->isDefaultConstructor()) {
16999             if (Constructor->isTrivial() &&
17000                 !Constructor->hasAttr<DLLExportAttr>())
17001               return;
17002             DefineImplicitDefaultConstructor(Loc, Constructor);
17003           } else if (Constructor->isCopyConstructor()) {
17004             DefineImplicitCopyConstructor(Loc, Constructor);
17005           } else if (Constructor->isMoveConstructor()) {
17006             DefineImplicitMoveConstructor(Loc, Constructor);
17007           }
17008         } else if (Constructor->getInheritedConstructor()) {
17009           DefineInheritingConstructor(Loc, Constructor);
17010         }
17011       } else if (CXXDestructorDecl *Destructor =
17012                      dyn_cast<CXXDestructorDecl>(Func)) {
17013         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17014         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17015           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17016             return;
17017           DefineImplicitDestructor(Loc, Destructor);
17018         }
17019         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17020           MarkVTableUsed(Loc, Destructor->getParent());
17021       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17022         if (MethodDecl->isOverloadedOperator() &&
17023             MethodDecl->getOverloadedOperator() == OO_Equal) {
17024           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17025           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17026             if (MethodDecl->isCopyAssignmentOperator())
17027               DefineImplicitCopyAssignment(Loc, MethodDecl);
17028             else if (MethodDecl->isMoveAssignmentOperator())
17029               DefineImplicitMoveAssignment(Loc, MethodDecl);
17030           }
17031         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17032                    MethodDecl->getParent()->isLambda()) {
17033           CXXConversionDecl *Conversion =
17034               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17035           if (Conversion->isLambdaToBlockPointerConversion())
17036             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17037           else
17038             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17039         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17040           MarkVTableUsed(Loc, MethodDecl->getParent());
17041       }
17042 
17043       if (Func->isDefaulted() && !Func->isDeleted()) {
17044         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17045         if (DCK != DefaultedComparisonKind::None)
17046           DefineDefaultedComparison(Loc, Func, DCK);
17047       }
17048 
17049       // Implicit instantiation of function templates and member functions of
17050       // class templates.
17051       if (Func->isImplicitlyInstantiable()) {
17052         TemplateSpecializationKind TSK =
17053             Func->getTemplateSpecializationKindForInstantiation();
17054         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17055         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17056         if (FirstInstantiation) {
17057           PointOfInstantiation = Loc;
17058           if (auto *MSI = Func->getMemberSpecializationInfo())
17059             MSI->setPointOfInstantiation(Loc);
17060             // FIXME: Notify listener.
17061           else
17062             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17063         } else if (TSK != TSK_ImplicitInstantiation) {
17064           // Use the point of use as the point of instantiation, instead of the
17065           // point of explicit instantiation (which we track as the actual point
17066           // of instantiation). This gives better backtraces in diagnostics.
17067           PointOfInstantiation = Loc;
17068         }
17069 
17070         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17071             Func->isConstexpr()) {
17072           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17073               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17074               CodeSynthesisContexts.size())
17075             PendingLocalImplicitInstantiations.push_back(
17076                 std::make_pair(Func, PointOfInstantiation));
17077           else if (Func->isConstexpr())
17078             // Do not defer instantiations of constexpr functions, to avoid the
17079             // expression evaluator needing to call back into Sema if it sees a
17080             // call to such a function.
17081             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17082           else {
17083             Func->setInstantiationIsPending(true);
17084             PendingInstantiations.push_back(
17085                 std::make_pair(Func, PointOfInstantiation));
17086             // Notify the consumer that a function was implicitly instantiated.
17087             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17088           }
17089         }
17090       } else {
17091         // Walk redefinitions, as some of them may be instantiable.
17092         for (auto i : Func->redecls()) {
17093           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17094             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17095         }
17096       }
17097     });
17098   }
17099 
17100   // C++14 [except.spec]p17:
17101   //   An exception-specification is considered to be needed when:
17102   //   - the function is odr-used or, if it appears in an unevaluated operand,
17103   //     would be odr-used if the expression were potentially-evaluated;
17104   //
17105   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17106   // function is a pure virtual function we're calling, and in that case the
17107   // function was selected by overload resolution and we need to resolve its
17108   // exception specification for a different reason.
17109   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17110   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17111     ResolveExceptionSpec(Loc, FPT);
17112 
17113   // If this is the first "real" use, act on that.
17114   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17115     // Keep track of used but undefined functions.
17116     if (!Func->isDefined()) {
17117       if (mightHaveNonExternalLinkage(Func))
17118         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17119       else if (Func->getMostRecentDecl()->isInlined() &&
17120                !LangOpts.GNUInline &&
17121                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17122         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17123       else if (isExternalWithNoLinkageType(Func))
17124         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17125     }
17126 
17127     // Some x86 Windows calling conventions mangle the size of the parameter
17128     // pack into the name. Computing the size of the parameters requires the
17129     // parameter types to be complete. Check that now.
17130     if (funcHasParameterSizeMangling(*this, Func))
17131       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17132 
17133     // In the MS C++ ABI, the compiler emits destructor variants where they are
17134     // used. If the destructor is used here but defined elsewhere, mark the
17135     // virtual base destructors referenced. If those virtual base destructors
17136     // are inline, this will ensure they are defined when emitting the complete
17137     // destructor variant. This checking may be redundant if the destructor is
17138     // provided later in this TU.
17139     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17140       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17141         CXXRecordDecl *Parent = Dtor->getParent();
17142         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17143           CheckCompleteDestructorVariant(Loc, Dtor);
17144       }
17145     }
17146 
17147     Func->markUsed(Context);
17148   }
17149 }
17150 
17151 /// Directly mark a variable odr-used. Given a choice, prefer to use
17152 /// MarkVariableReferenced since it does additional checks and then
17153 /// calls MarkVarDeclODRUsed.
17154 /// If the variable must be captured:
17155 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17156 ///  - else capture it in the DeclContext that maps to the
17157 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17158 static void
17159 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17160                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17161   // Keep track of used but undefined variables.
17162   // FIXME: We shouldn't suppress this warning for static data members.
17163   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17164       (!Var->isExternallyVisible() || Var->isInline() ||
17165        SemaRef.isExternalWithNoLinkageType(Var)) &&
17166       !(Var->isStaticDataMember() && Var->hasInit())) {
17167     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17168     if (old.isInvalid())
17169       old = Loc;
17170   }
17171   QualType CaptureType, DeclRefType;
17172   if (SemaRef.LangOpts.OpenMP)
17173     SemaRef.tryCaptureOpenMPLambdas(Var);
17174   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17175     /*EllipsisLoc*/ SourceLocation(),
17176     /*BuildAndDiagnose*/ true,
17177     CaptureType, DeclRefType,
17178     FunctionScopeIndexToStopAt);
17179 
17180   if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17181     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17182     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17183     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17184     if (VarTarget == Sema::CVT_Host &&
17185         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17186          UserTarget == Sema::CFT_Global)) {
17187       // Diagnose ODR-use of host global variables in device functions.
17188       // Reference of device global variables in host functions is allowed
17189       // through shadow variables therefore it is not diagnosed.
17190       if (SemaRef.LangOpts.CUDAIsDevice) {
17191         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17192             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17193         SemaRef.targetDiag(Var->getLocation(),
17194                            Var->getType().isConstQualified()
17195                                ? diag::note_cuda_const_var_unpromoted
17196                                : diag::note_cuda_host_var);
17197       }
17198     } else if (VarTarget == Sema::CVT_Device &&
17199                (UserTarget == Sema::CFT_Host ||
17200                 UserTarget == Sema::CFT_HostDevice) &&
17201                !Var->hasExternalStorage()) {
17202       // Record a CUDA/HIP device side variable if it is ODR-used
17203       // by host code. This is done conservatively, when the variable is
17204       // referenced in any of the following contexts:
17205       //   - a non-function context
17206       //   - a host function
17207       //   - a host device function
17208       // This makes the ODR-use of the device side variable by host code to
17209       // be visible in the device compilation for the compiler to be able to
17210       // emit template variables instantiated by host code only and to
17211       // externalize the static device side variable ODR-used by host code.
17212       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17213     }
17214   }
17215 
17216   Var->markUsed(SemaRef.Context);
17217 }
17218 
17219 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17220                                              SourceLocation Loc,
17221                                              unsigned CapturingScopeIndex) {
17222   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17223 }
17224 
17225 static void
17226 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17227                                    ValueDecl *var, DeclContext *DC) {
17228   DeclContext *VarDC = var->getDeclContext();
17229 
17230   //  If the parameter still belongs to the translation unit, then
17231   //  we're actually just using one parameter in the declaration of
17232   //  the next.
17233   if (isa<ParmVarDecl>(var) &&
17234       isa<TranslationUnitDecl>(VarDC))
17235     return;
17236 
17237   // For C code, don't diagnose about capture if we're not actually in code
17238   // right now; it's impossible to write a non-constant expression outside of
17239   // function context, so we'll get other (more useful) diagnostics later.
17240   //
17241   // For C++, things get a bit more nasty... it would be nice to suppress this
17242   // diagnostic for certain cases like using a local variable in an array bound
17243   // for a member of a local class, but the correct predicate is not obvious.
17244   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17245     return;
17246 
17247   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17248   unsigned ContextKind = 3; // unknown
17249   if (isa<CXXMethodDecl>(VarDC) &&
17250       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17251     ContextKind = 2;
17252   } else if (isa<FunctionDecl>(VarDC)) {
17253     ContextKind = 0;
17254   } else if (isa<BlockDecl>(VarDC)) {
17255     ContextKind = 1;
17256   }
17257 
17258   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17259     << var << ValueKind << ContextKind << VarDC;
17260   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17261       << var;
17262 
17263   // FIXME: Add additional diagnostic info about class etc. which prevents
17264   // capture.
17265 }
17266 
17267 
17268 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17269                                       bool &SubCapturesAreNested,
17270                                       QualType &CaptureType,
17271                                       QualType &DeclRefType) {
17272    // Check whether we've already captured it.
17273   if (CSI->CaptureMap.count(Var)) {
17274     // If we found a capture, any subcaptures are nested.
17275     SubCapturesAreNested = true;
17276 
17277     // Retrieve the capture type for this variable.
17278     CaptureType = CSI->getCapture(Var).getCaptureType();
17279 
17280     // Compute the type of an expression that refers to this variable.
17281     DeclRefType = CaptureType.getNonReferenceType();
17282 
17283     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17284     // are mutable in the sense that user can change their value - they are
17285     // private instances of the captured declarations.
17286     const Capture &Cap = CSI->getCapture(Var);
17287     if (Cap.isCopyCapture() &&
17288         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17289         !(isa<CapturedRegionScopeInfo>(CSI) &&
17290           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17291       DeclRefType.addConst();
17292     return true;
17293   }
17294   return false;
17295 }
17296 
17297 // Only block literals, captured statements, and lambda expressions can
17298 // capture; other scopes don't work.
17299 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17300                                  SourceLocation Loc,
17301                                  const bool Diagnose, Sema &S) {
17302   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17303     return getLambdaAwareParentOfDeclContext(DC);
17304   else if (Var->hasLocalStorage()) {
17305     if (Diagnose)
17306        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17307   }
17308   return nullptr;
17309 }
17310 
17311 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17312 // certain types of variables (unnamed, variably modified types etc.)
17313 // so check for eligibility.
17314 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17315                                  SourceLocation Loc,
17316                                  const bool Diagnose, Sema &S) {
17317 
17318   bool IsBlock = isa<BlockScopeInfo>(CSI);
17319   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17320 
17321   // Lambdas are not allowed to capture unnamed variables
17322   // (e.g. anonymous unions).
17323   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17324   // assuming that's the intent.
17325   if (IsLambda && !Var->getDeclName()) {
17326     if (Diagnose) {
17327       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17328       S.Diag(Var->getLocation(), diag::note_declared_at);
17329     }
17330     return false;
17331   }
17332 
17333   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17334   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17335     if (Diagnose) {
17336       S.Diag(Loc, diag::err_ref_vm_type);
17337       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17338     }
17339     return false;
17340   }
17341   // Prohibit structs with flexible array members too.
17342   // We cannot capture what is in the tail end of the struct.
17343   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17344     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17345       if (Diagnose) {
17346         if (IsBlock)
17347           S.Diag(Loc, diag::err_ref_flexarray_type);
17348         else
17349           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17350         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17351       }
17352       return false;
17353     }
17354   }
17355   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17356   // Lambdas and captured statements are not allowed to capture __block
17357   // variables; they don't support the expected semantics.
17358   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17359     if (Diagnose) {
17360       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17361       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17362     }
17363     return false;
17364   }
17365   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17366   if (S.getLangOpts().OpenCL && IsBlock &&
17367       Var->getType()->isBlockPointerType()) {
17368     if (Diagnose)
17369       S.Diag(Loc, diag::err_opencl_block_ref_block);
17370     return false;
17371   }
17372 
17373   return true;
17374 }
17375 
17376 // Returns true if the capture by block was successful.
17377 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17378                                  SourceLocation Loc,
17379                                  const bool BuildAndDiagnose,
17380                                  QualType &CaptureType,
17381                                  QualType &DeclRefType,
17382                                  const bool Nested,
17383                                  Sema &S, bool Invalid) {
17384   bool ByRef = false;
17385 
17386   // Blocks are not allowed to capture arrays, excepting OpenCL.
17387   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17388   // (decayed to pointers).
17389   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17390     if (BuildAndDiagnose) {
17391       S.Diag(Loc, diag::err_ref_array_type);
17392       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17393       Invalid = true;
17394     } else {
17395       return false;
17396     }
17397   }
17398 
17399   // Forbid the block-capture of autoreleasing variables.
17400   if (!Invalid &&
17401       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17402     if (BuildAndDiagnose) {
17403       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17404         << /*block*/ 0;
17405       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17406       Invalid = true;
17407     } else {
17408       return false;
17409     }
17410   }
17411 
17412   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17413   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17414     QualType PointeeTy = PT->getPointeeType();
17415 
17416     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17417         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17418         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17419       if (BuildAndDiagnose) {
17420         SourceLocation VarLoc = Var->getLocation();
17421         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17422         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17423       }
17424     }
17425   }
17426 
17427   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17428   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17429       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17430     // Block capture by reference does not change the capture or
17431     // declaration reference types.
17432     ByRef = true;
17433   } else {
17434     // Block capture by copy introduces 'const'.
17435     CaptureType = CaptureType.getNonReferenceType().withConst();
17436     DeclRefType = CaptureType;
17437   }
17438 
17439   // Actually capture the variable.
17440   if (BuildAndDiagnose)
17441     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17442                     CaptureType, Invalid);
17443 
17444   return !Invalid;
17445 }
17446 
17447 
17448 /// Capture the given variable in the captured region.
17449 static bool captureInCapturedRegion(
17450     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17451     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17452     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17453     bool IsTopScope, Sema &S, bool Invalid) {
17454   // By default, capture variables by reference.
17455   bool ByRef = true;
17456   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17457     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17458   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17459     // Using an LValue reference type is consistent with Lambdas (see below).
17460     if (S.isOpenMPCapturedDecl(Var)) {
17461       bool HasConst = DeclRefType.isConstQualified();
17462       DeclRefType = DeclRefType.getUnqualifiedType();
17463       // Don't lose diagnostics about assignments to const.
17464       if (HasConst)
17465         DeclRefType.addConst();
17466     }
17467     // Do not capture firstprivates in tasks.
17468     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17469         OMPC_unknown)
17470       return true;
17471     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17472                                     RSI->OpenMPCaptureLevel);
17473   }
17474 
17475   if (ByRef)
17476     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17477   else
17478     CaptureType = DeclRefType;
17479 
17480   // Actually capture the variable.
17481   if (BuildAndDiagnose)
17482     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17483                     Loc, SourceLocation(), CaptureType, Invalid);
17484 
17485   return !Invalid;
17486 }
17487 
17488 /// Capture the given variable in the lambda.
17489 static bool captureInLambda(LambdaScopeInfo *LSI,
17490                             VarDecl *Var,
17491                             SourceLocation Loc,
17492                             const bool BuildAndDiagnose,
17493                             QualType &CaptureType,
17494                             QualType &DeclRefType,
17495                             const bool RefersToCapturedVariable,
17496                             const Sema::TryCaptureKind Kind,
17497                             SourceLocation EllipsisLoc,
17498                             const bool IsTopScope,
17499                             Sema &S, bool Invalid) {
17500   // Determine whether we are capturing by reference or by value.
17501   bool ByRef = false;
17502   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17503     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17504   } else {
17505     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17506   }
17507 
17508   // Compute the type of the field that will capture this variable.
17509   if (ByRef) {
17510     // C++11 [expr.prim.lambda]p15:
17511     //   An entity is captured by reference if it is implicitly or
17512     //   explicitly captured but not captured by copy. It is
17513     //   unspecified whether additional unnamed non-static data
17514     //   members are declared in the closure type for entities
17515     //   captured by reference.
17516     //
17517     // FIXME: It is not clear whether we want to build an lvalue reference
17518     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17519     // to do the former, while EDG does the latter. Core issue 1249 will
17520     // clarify, but for now we follow GCC because it's a more permissive and
17521     // easily defensible position.
17522     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17523   } else {
17524     // C++11 [expr.prim.lambda]p14:
17525     //   For each entity captured by copy, an unnamed non-static
17526     //   data member is declared in the closure type. The
17527     //   declaration order of these members is unspecified. The type
17528     //   of such a data member is the type of the corresponding
17529     //   captured entity if the entity is not a reference to an
17530     //   object, or the referenced type otherwise. [Note: If the
17531     //   captured entity is a reference to a function, the
17532     //   corresponding data member is also a reference to a
17533     //   function. - end note ]
17534     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17535       if (!RefType->getPointeeType()->isFunctionType())
17536         CaptureType = RefType->getPointeeType();
17537     }
17538 
17539     // Forbid the lambda copy-capture of autoreleasing variables.
17540     if (!Invalid &&
17541         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17542       if (BuildAndDiagnose) {
17543         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17544         S.Diag(Var->getLocation(), diag::note_previous_decl)
17545           << Var->getDeclName();
17546         Invalid = true;
17547       } else {
17548         return false;
17549       }
17550     }
17551 
17552     // Make sure that by-copy captures are of a complete and non-abstract type.
17553     if (!Invalid && BuildAndDiagnose) {
17554       if (!CaptureType->isDependentType() &&
17555           S.RequireCompleteSizedType(
17556               Loc, CaptureType,
17557               diag::err_capture_of_incomplete_or_sizeless_type,
17558               Var->getDeclName()))
17559         Invalid = true;
17560       else if (S.RequireNonAbstractType(Loc, CaptureType,
17561                                         diag::err_capture_of_abstract_type))
17562         Invalid = true;
17563     }
17564   }
17565 
17566   // Compute the type of a reference to this captured variable.
17567   if (ByRef)
17568     DeclRefType = CaptureType.getNonReferenceType();
17569   else {
17570     // C++ [expr.prim.lambda]p5:
17571     //   The closure type for a lambda-expression has a public inline
17572     //   function call operator [...]. This function call operator is
17573     //   declared const (9.3.1) if and only if the lambda-expression's
17574     //   parameter-declaration-clause is not followed by mutable.
17575     DeclRefType = CaptureType.getNonReferenceType();
17576     if (!LSI->Mutable && !CaptureType->isReferenceType())
17577       DeclRefType.addConst();
17578   }
17579 
17580   // Add the capture.
17581   if (BuildAndDiagnose)
17582     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17583                     Loc, EllipsisLoc, CaptureType, Invalid);
17584 
17585   return !Invalid;
17586 }
17587 
17588 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17589   // Offer a Copy fix even if the type is dependent.
17590   if (Var->getType()->isDependentType())
17591     return true;
17592   QualType T = Var->getType().getNonReferenceType();
17593   if (T.isTriviallyCopyableType(Context))
17594     return true;
17595   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17596 
17597     if (!(RD = RD->getDefinition()))
17598       return false;
17599     if (RD->hasSimpleCopyConstructor())
17600       return true;
17601     if (RD->hasUserDeclaredCopyConstructor())
17602       for (CXXConstructorDecl *Ctor : RD->ctors())
17603         if (Ctor->isCopyConstructor())
17604           return !Ctor->isDeleted();
17605   }
17606   return false;
17607 }
17608 
17609 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17610 /// default capture. Fixes may be omitted if they aren't allowed by the
17611 /// standard, for example we can't emit a default copy capture fix-it if we
17612 /// already explicitly copy capture capture another variable.
17613 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17614                                     VarDecl *Var) {
17615   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17616   // Don't offer Capture by copy of default capture by copy fixes if Var is
17617   // known not to be copy constructible.
17618   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17619 
17620   SmallString<32> FixBuffer;
17621   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17622   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17623     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17624     if (ShouldOfferCopyFix) {
17625       // Offer fixes to insert an explicit capture for the variable.
17626       // [] -> [VarName]
17627       // [OtherCapture] -> [OtherCapture, VarName]
17628       FixBuffer.assign({Separator, Var->getName()});
17629       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17630           << Var << /*value*/ 0
17631           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17632     }
17633     // As above but capture by reference.
17634     FixBuffer.assign({Separator, "&", Var->getName()});
17635     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17636         << Var << /*reference*/ 1
17637         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17638   }
17639 
17640   // Only try to offer default capture if there are no captures excluding this
17641   // and init captures.
17642   // [this]: OK.
17643   // [X = Y]: OK.
17644   // [&A, &B]: Don't offer.
17645   // [A, B]: Don't offer.
17646   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17647         return !C.isThisCapture() && !C.isInitCapture();
17648       }))
17649     return;
17650 
17651   // The default capture specifiers, '=' or '&', must appear first in the
17652   // capture body.
17653   SourceLocation DefaultInsertLoc =
17654       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17655 
17656   if (ShouldOfferCopyFix) {
17657     bool CanDefaultCopyCapture = true;
17658     // [=, *this] OK since c++17
17659     // [=, this] OK since c++20
17660     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17661       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17662                                   ? LSI->getCXXThisCapture().isCopyCapture()
17663                                   : false;
17664     // We can't use default capture by copy if any captures already specified
17665     // capture by copy.
17666     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17667           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17668         })) {
17669       FixBuffer.assign({"=", Separator});
17670       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17671           << /*value*/ 0
17672           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17673     }
17674   }
17675 
17676   // We can't use default capture by reference if any captures already specified
17677   // capture by reference.
17678   if (llvm::none_of(LSI->Captures, [](Capture &C) {
17679         return !C.isInitCapture() && C.isReferenceCapture() &&
17680                !C.isThisCapture();
17681       })) {
17682     FixBuffer.assign({"&", Separator});
17683     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17684         << /*reference*/ 1
17685         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17686   }
17687 }
17688 
17689 bool Sema::tryCaptureVariable(
17690     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17691     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17692     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17693   // An init-capture is notionally from the context surrounding its
17694   // declaration, but its parent DC is the lambda class.
17695   DeclContext *VarDC = Var->getDeclContext();
17696   if (Var->isInitCapture())
17697     VarDC = VarDC->getParent();
17698 
17699   DeclContext *DC = CurContext;
17700   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17701       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17702   // We need to sync up the Declaration Context with the
17703   // FunctionScopeIndexToStopAt
17704   if (FunctionScopeIndexToStopAt) {
17705     unsigned FSIndex = FunctionScopes.size() - 1;
17706     while (FSIndex != MaxFunctionScopesIndex) {
17707       DC = getLambdaAwareParentOfDeclContext(DC);
17708       --FSIndex;
17709     }
17710   }
17711 
17712 
17713   // If the variable is declared in the current context, there is no need to
17714   // capture it.
17715   if (VarDC == DC) return true;
17716 
17717   // Capture global variables if it is required to use private copy of this
17718   // variable.
17719   bool IsGlobal = !Var->hasLocalStorage();
17720   if (IsGlobal &&
17721       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17722                                                 MaxFunctionScopesIndex)))
17723     return true;
17724   Var = Var->getCanonicalDecl();
17725 
17726   // Walk up the stack to determine whether we can capture the variable,
17727   // performing the "simple" checks that don't depend on type. We stop when
17728   // we've either hit the declared scope of the variable or find an existing
17729   // capture of that variable.  We start from the innermost capturing-entity
17730   // (the DC) and ensure that all intervening capturing-entities
17731   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17732   // declcontext can either capture the variable or have already captured
17733   // the variable.
17734   CaptureType = Var->getType();
17735   DeclRefType = CaptureType.getNonReferenceType();
17736   bool Nested = false;
17737   bool Explicit = (Kind != TryCapture_Implicit);
17738   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17739   do {
17740     // Only block literals, captured statements, and lambda expressions can
17741     // capture; other scopes don't work.
17742     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17743                                                               ExprLoc,
17744                                                               BuildAndDiagnose,
17745                                                               *this);
17746     // We need to check for the parent *first* because, if we *have*
17747     // private-captured a global variable, we need to recursively capture it in
17748     // intermediate blocks, lambdas, etc.
17749     if (!ParentDC) {
17750       if (IsGlobal) {
17751         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17752         break;
17753       }
17754       return true;
17755     }
17756 
17757     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17758     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17759 
17760 
17761     // Check whether we've already captured it.
17762     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17763                                              DeclRefType)) {
17764       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17765       break;
17766     }
17767     // If we are instantiating a generic lambda call operator body,
17768     // we do not want to capture new variables.  What was captured
17769     // during either a lambdas transformation or initial parsing
17770     // should be used.
17771     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17772       if (BuildAndDiagnose) {
17773         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17774         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17775           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17776           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17777           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17778           buildLambdaCaptureFixit(*this, LSI, Var);
17779         } else
17780           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17781       }
17782       return true;
17783     }
17784 
17785     // Try to capture variable-length arrays types.
17786     if (Var->getType()->isVariablyModifiedType()) {
17787       // We're going to walk down into the type and look for VLA
17788       // expressions.
17789       QualType QTy = Var->getType();
17790       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17791         QTy = PVD->getOriginalType();
17792       captureVariablyModifiedType(Context, QTy, CSI);
17793     }
17794 
17795     if (getLangOpts().OpenMP) {
17796       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17797         // OpenMP private variables should not be captured in outer scope, so
17798         // just break here. Similarly, global variables that are captured in a
17799         // target region should not be captured outside the scope of the region.
17800         if (RSI->CapRegionKind == CR_OpenMP) {
17801           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17802               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17803           // If the variable is private (i.e. not captured) and has variably
17804           // modified type, we still need to capture the type for correct
17805           // codegen in all regions, associated with the construct. Currently,
17806           // it is captured in the innermost captured region only.
17807           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17808               Var->getType()->isVariablyModifiedType()) {
17809             QualType QTy = Var->getType();
17810             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17811               QTy = PVD->getOriginalType();
17812             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17813                  I < E; ++I) {
17814               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17815                   FunctionScopes[FunctionScopesIndex - I]);
17816               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17817                      "Wrong number of captured regions associated with the "
17818                      "OpenMP construct.");
17819               captureVariablyModifiedType(Context, QTy, OuterRSI);
17820             }
17821           }
17822           bool IsTargetCap =
17823               IsOpenMPPrivateDecl != OMPC_private &&
17824               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17825                                          RSI->OpenMPCaptureLevel);
17826           // Do not capture global if it is not privatized in outer regions.
17827           bool IsGlobalCap =
17828               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17829                                                      RSI->OpenMPCaptureLevel);
17830 
17831           // When we detect target captures we are looking from inside the
17832           // target region, therefore we need to propagate the capture from the
17833           // enclosing region. Therefore, the capture is not initially nested.
17834           if (IsTargetCap)
17835             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17836 
17837           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17838               (IsGlobal && !IsGlobalCap)) {
17839             Nested = !IsTargetCap;
17840             bool HasConst = DeclRefType.isConstQualified();
17841             DeclRefType = DeclRefType.getUnqualifiedType();
17842             // Don't lose diagnostics about assignments to const.
17843             if (HasConst)
17844               DeclRefType.addConst();
17845             CaptureType = Context.getLValueReferenceType(DeclRefType);
17846             break;
17847           }
17848         }
17849       }
17850     }
17851     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17852       // No capture-default, and this is not an explicit capture
17853       // so cannot capture this variable.
17854       if (BuildAndDiagnose) {
17855         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17856         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17857         auto *LSI = cast<LambdaScopeInfo>(CSI);
17858         if (LSI->Lambda) {
17859           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17860           buildLambdaCaptureFixit(*this, LSI, Var);
17861         }
17862         // FIXME: If we error out because an outer lambda can not implicitly
17863         // capture a variable that an inner lambda explicitly captures, we
17864         // should have the inner lambda do the explicit capture - because
17865         // it makes for cleaner diagnostics later.  This would purely be done
17866         // so that the diagnostic does not misleadingly claim that a variable
17867         // can not be captured by a lambda implicitly even though it is captured
17868         // explicitly.  Suggestion:
17869         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17870         //    at the function head
17871         //  - cache the StartingDeclContext - this must be a lambda
17872         //  - captureInLambda in the innermost lambda the variable.
17873       }
17874       return true;
17875     }
17876 
17877     FunctionScopesIndex--;
17878     DC = ParentDC;
17879     Explicit = false;
17880   } while (!VarDC->Equals(DC));
17881 
17882   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17883   // computing the type of the capture at each step, checking type-specific
17884   // requirements, and adding captures if requested.
17885   // If the variable had already been captured previously, we start capturing
17886   // at the lambda nested within that one.
17887   bool Invalid = false;
17888   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17889        ++I) {
17890     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17891 
17892     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17893     // certain types of variables (unnamed, variably modified types etc.)
17894     // so check for eligibility.
17895     if (!Invalid)
17896       Invalid =
17897           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17898 
17899     // After encountering an error, if we're actually supposed to capture, keep
17900     // capturing in nested contexts to suppress any follow-on diagnostics.
17901     if (Invalid && !BuildAndDiagnose)
17902       return true;
17903 
17904     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17905       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17906                                DeclRefType, Nested, *this, Invalid);
17907       Nested = true;
17908     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17909       Invalid = !captureInCapturedRegion(
17910           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
17911           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
17912       Nested = true;
17913     } else {
17914       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17915       Invalid =
17916           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17917                            DeclRefType, Nested, Kind, EllipsisLoc,
17918                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17919       Nested = true;
17920     }
17921 
17922     if (Invalid && !BuildAndDiagnose)
17923       return true;
17924   }
17925   return Invalid;
17926 }
17927 
17928 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17929                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17930   QualType CaptureType;
17931   QualType DeclRefType;
17932   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17933                             /*BuildAndDiagnose=*/true, CaptureType,
17934                             DeclRefType, nullptr);
17935 }
17936 
17937 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17938   QualType CaptureType;
17939   QualType DeclRefType;
17940   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17941                              /*BuildAndDiagnose=*/false, CaptureType,
17942                              DeclRefType, nullptr);
17943 }
17944 
17945 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17946   QualType CaptureType;
17947   QualType DeclRefType;
17948 
17949   // Determine whether we can capture this variable.
17950   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17951                          /*BuildAndDiagnose=*/false, CaptureType,
17952                          DeclRefType, nullptr))
17953     return QualType();
17954 
17955   return DeclRefType;
17956 }
17957 
17958 namespace {
17959 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17960 // The produced TemplateArgumentListInfo* points to data stored within this
17961 // object, so should only be used in contexts where the pointer will not be
17962 // used after the CopiedTemplateArgs object is destroyed.
17963 class CopiedTemplateArgs {
17964   bool HasArgs;
17965   TemplateArgumentListInfo TemplateArgStorage;
17966 public:
17967   template<typename RefExpr>
17968   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17969     if (HasArgs)
17970       E->copyTemplateArgumentsInto(TemplateArgStorage);
17971   }
17972   operator TemplateArgumentListInfo*()
17973 #ifdef __has_cpp_attribute
17974 #if __has_cpp_attribute(clang::lifetimebound)
17975   [[clang::lifetimebound]]
17976 #endif
17977 #endif
17978   {
17979     return HasArgs ? &TemplateArgStorage : nullptr;
17980   }
17981 };
17982 }
17983 
17984 /// Walk the set of potential results of an expression and mark them all as
17985 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17986 ///
17987 /// \return A new expression if we found any potential results, ExprEmpty() if
17988 ///         not, and ExprError() if we diagnosed an error.
17989 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17990                                                       NonOdrUseReason NOUR) {
17991   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17992   // an object that satisfies the requirements for appearing in a
17993   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17994   // is immediately applied."  This function handles the lvalue-to-rvalue
17995   // conversion part.
17996   //
17997   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17998   // transform it into the relevant kind of non-odr-use node and rebuild the
17999   // tree of nodes leading to it.
18000   //
18001   // This is a mini-TreeTransform that only transforms a restricted subset of
18002   // nodes (and only certain operands of them).
18003 
18004   // Rebuild a subexpression.
18005   auto Rebuild = [&](Expr *Sub) {
18006     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18007   };
18008 
18009   // Check whether a potential result satisfies the requirements of NOUR.
18010   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18011     // Any entity other than a VarDecl is always odr-used whenever it's named
18012     // in a potentially-evaluated expression.
18013     auto *VD = dyn_cast<VarDecl>(D);
18014     if (!VD)
18015       return true;
18016 
18017     // C++2a [basic.def.odr]p4:
18018     //   A variable x whose name appears as a potentially-evalauted expression
18019     //   e is odr-used by e unless
18020     //   -- x is a reference that is usable in constant expressions, or
18021     //   -- x is a variable of non-reference type that is usable in constant
18022     //      expressions and has no mutable subobjects, and e is an element of
18023     //      the set of potential results of an expression of
18024     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18025     //      conversion is applied, or
18026     //   -- x is a variable of non-reference type, and e is an element of the
18027     //      set of potential results of a discarded-value expression to which
18028     //      the lvalue-to-rvalue conversion is not applied
18029     //
18030     // We check the first bullet and the "potentially-evaluated" condition in
18031     // BuildDeclRefExpr. We check the type requirements in the second bullet
18032     // in CheckLValueToRValueConversionOperand below.
18033     switch (NOUR) {
18034     case NOUR_None:
18035     case NOUR_Unevaluated:
18036       llvm_unreachable("unexpected non-odr-use-reason");
18037 
18038     case NOUR_Constant:
18039       // Constant references were handled when they were built.
18040       if (VD->getType()->isReferenceType())
18041         return true;
18042       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18043         if (RD->hasMutableFields())
18044           return true;
18045       if (!VD->isUsableInConstantExpressions(S.Context))
18046         return true;
18047       break;
18048 
18049     case NOUR_Discarded:
18050       if (VD->getType()->isReferenceType())
18051         return true;
18052       break;
18053     }
18054     return false;
18055   };
18056 
18057   // Mark that this expression does not constitute an odr-use.
18058   auto MarkNotOdrUsed = [&] {
18059     S.MaybeODRUseExprs.remove(E);
18060     if (LambdaScopeInfo *LSI = S.getCurLambda())
18061       LSI->markVariableExprAsNonODRUsed(E);
18062   };
18063 
18064   // C++2a [basic.def.odr]p2:
18065   //   The set of potential results of an expression e is defined as follows:
18066   switch (E->getStmtClass()) {
18067   //   -- If e is an id-expression, ...
18068   case Expr::DeclRefExprClass: {
18069     auto *DRE = cast<DeclRefExpr>(E);
18070     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18071       break;
18072 
18073     // Rebuild as a non-odr-use DeclRefExpr.
18074     MarkNotOdrUsed();
18075     return DeclRefExpr::Create(
18076         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18077         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18078         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18079         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18080   }
18081 
18082   case Expr::FunctionParmPackExprClass: {
18083     auto *FPPE = cast<FunctionParmPackExpr>(E);
18084     // If any of the declarations in the pack is odr-used, then the expression
18085     // as a whole constitutes an odr-use.
18086     for (VarDecl *D : *FPPE)
18087       if (IsPotentialResultOdrUsed(D))
18088         return ExprEmpty();
18089 
18090     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18091     // nothing cares about whether we marked this as an odr-use, but it might
18092     // be useful for non-compiler tools.
18093     MarkNotOdrUsed();
18094     break;
18095   }
18096 
18097   //   -- If e is a subscripting operation with an array operand...
18098   case Expr::ArraySubscriptExprClass: {
18099     auto *ASE = cast<ArraySubscriptExpr>(E);
18100     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18101     if (!OldBase->getType()->isArrayType())
18102       break;
18103     ExprResult Base = Rebuild(OldBase);
18104     if (!Base.isUsable())
18105       return Base;
18106     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18107     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18108     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18109     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18110                                      ASE->getRBracketLoc());
18111   }
18112 
18113   case Expr::MemberExprClass: {
18114     auto *ME = cast<MemberExpr>(E);
18115     // -- If e is a class member access expression [...] naming a non-static
18116     //    data member...
18117     if (isa<FieldDecl>(ME->getMemberDecl())) {
18118       ExprResult Base = Rebuild(ME->getBase());
18119       if (!Base.isUsable())
18120         return Base;
18121       return MemberExpr::Create(
18122           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18123           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18124           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18125           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18126           ME->getObjectKind(), ME->isNonOdrUse());
18127     }
18128 
18129     if (ME->getMemberDecl()->isCXXInstanceMember())
18130       break;
18131 
18132     // -- If e is a class member access expression naming a static data member,
18133     //    ...
18134     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18135       break;
18136 
18137     // Rebuild as a non-odr-use MemberExpr.
18138     MarkNotOdrUsed();
18139     return MemberExpr::Create(
18140         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18141         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18142         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18143         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18144     return ExprEmpty();
18145   }
18146 
18147   case Expr::BinaryOperatorClass: {
18148     auto *BO = cast<BinaryOperator>(E);
18149     Expr *LHS = BO->getLHS();
18150     Expr *RHS = BO->getRHS();
18151     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18152     if (BO->getOpcode() == BO_PtrMemD) {
18153       ExprResult Sub = Rebuild(LHS);
18154       if (!Sub.isUsable())
18155         return Sub;
18156       LHS = Sub.get();
18157     //   -- If e is a comma expression, ...
18158     } else if (BO->getOpcode() == BO_Comma) {
18159       ExprResult Sub = Rebuild(RHS);
18160       if (!Sub.isUsable())
18161         return Sub;
18162       RHS = Sub.get();
18163     } else {
18164       break;
18165     }
18166     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18167                         LHS, RHS);
18168   }
18169 
18170   //   -- If e has the form (e1)...
18171   case Expr::ParenExprClass: {
18172     auto *PE = cast<ParenExpr>(E);
18173     ExprResult Sub = Rebuild(PE->getSubExpr());
18174     if (!Sub.isUsable())
18175       return Sub;
18176     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18177   }
18178 
18179   //   -- If e is a glvalue conditional expression, ...
18180   // We don't apply this to a binary conditional operator. FIXME: Should we?
18181   case Expr::ConditionalOperatorClass: {
18182     auto *CO = cast<ConditionalOperator>(E);
18183     ExprResult LHS = Rebuild(CO->getLHS());
18184     if (LHS.isInvalid())
18185       return ExprError();
18186     ExprResult RHS = Rebuild(CO->getRHS());
18187     if (RHS.isInvalid())
18188       return ExprError();
18189     if (!LHS.isUsable() && !RHS.isUsable())
18190       return ExprEmpty();
18191     if (!LHS.isUsable())
18192       LHS = CO->getLHS();
18193     if (!RHS.isUsable())
18194       RHS = CO->getRHS();
18195     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18196                                 CO->getCond(), LHS.get(), RHS.get());
18197   }
18198 
18199   // [Clang extension]
18200   //   -- If e has the form __extension__ e1...
18201   case Expr::UnaryOperatorClass: {
18202     auto *UO = cast<UnaryOperator>(E);
18203     if (UO->getOpcode() != UO_Extension)
18204       break;
18205     ExprResult Sub = Rebuild(UO->getSubExpr());
18206     if (!Sub.isUsable())
18207       return Sub;
18208     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18209                           Sub.get());
18210   }
18211 
18212   // [Clang extension]
18213   //   -- If e has the form _Generic(...), the set of potential results is the
18214   //      union of the sets of potential results of the associated expressions.
18215   case Expr::GenericSelectionExprClass: {
18216     auto *GSE = cast<GenericSelectionExpr>(E);
18217 
18218     SmallVector<Expr *, 4> AssocExprs;
18219     bool AnyChanged = false;
18220     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18221       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18222       if (AssocExpr.isInvalid())
18223         return ExprError();
18224       if (AssocExpr.isUsable()) {
18225         AssocExprs.push_back(AssocExpr.get());
18226         AnyChanged = true;
18227       } else {
18228         AssocExprs.push_back(OrigAssocExpr);
18229       }
18230     }
18231 
18232     return AnyChanged ? S.CreateGenericSelectionExpr(
18233                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18234                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18235                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18236                       : ExprEmpty();
18237   }
18238 
18239   // [Clang extension]
18240   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18241   //      results is the union of the sets of potential results of the
18242   //      second and third subexpressions.
18243   case Expr::ChooseExprClass: {
18244     auto *CE = cast<ChooseExpr>(E);
18245 
18246     ExprResult LHS = Rebuild(CE->getLHS());
18247     if (LHS.isInvalid())
18248       return ExprError();
18249 
18250     ExprResult RHS = Rebuild(CE->getLHS());
18251     if (RHS.isInvalid())
18252       return ExprError();
18253 
18254     if (!LHS.get() && !RHS.get())
18255       return ExprEmpty();
18256     if (!LHS.isUsable())
18257       LHS = CE->getLHS();
18258     if (!RHS.isUsable())
18259       RHS = CE->getRHS();
18260 
18261     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18262                              RHS.get(), CE->getRParenLoc());
18263   }
18264 
18265   // Step through non-syntactic nodes.
18266   case Expr::ConstantExprClass: {
18267     auto *CE = cast<ConstantExpr>(E);
18268     ExprResult Sub = Rebuild(CE->getSubExpr());
18269     if (!Sub.isUsable())
18270       return Sub;
18271     return ConstantExpr::Create(S.Context, Sub.get());
18272   }
18273 
18274   // We could mostly rely on the recursive rebuilding to rebuild implicit
18275   // casts, but not at the top level, so rebuild them here.
18276   case Expr::ImplicitCastExprClass: {
18277     auto *ICE = cast<ImplicitCastExpr>(E);
18278     // Only step through the narrow set of cast kinds we expect to encounter.
18279     // Anything else suggests we've left the region in which potential results
18280     // can be found.
18281     switch (ICE->getCastKind()) {
18282     case CK_NoOp:
18283     case CK_DerivedToBase:
18284     case CK_UncheckedDerivedToBase: {
18285       ExprResult Sub = Rebuild(ICE->getSubExpr());
18286       if (!Sub.isUsable())
18287         return Sub;
18288       CXXCastPath Path(ICE->path());
18289       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18290                                  ICE->getValueKind(), &Path);
18291     }
18292 
18293     default:
18294       break;
18295     }
18296     break;
18297   }
18298 
18299   default:
18300     break;
18301   }
18302 
18303   // Can't traverse through this node. Nothing to do.
18304   return ExprEmpty();
18305 }
18306 
18307 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18308   // Check whether the operand is or contains an object of non-trivial C union
18309   // type.
18310   if (E->getType().isVolatileQualified() &&
18311       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18312        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18313     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18314                           Sema::NTCUC_LValueToRValueVolatile,
18315                           NTCUK_Destruct|NTCUK_Copy);
18316 
18317   // C++2a [basic.def.odr]p4:
18318   //   [...] an expression of non-volatile-qualified non-class type to which
18319   //   the lvalue-to-rvalue conversion is applied [...]
18320   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18321     return E;
18322 
18323   ExprResult Result =
18324       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18325   if (Result.isInvalid())
18326     return ExprError();
18327   return Result.get() ? Result : E;
18328 }
18329 
18330 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18331   Res = CorrectDelayedTyposInExpr(Res);
18332 
18333   if (!Res.isUsable())
18334     return Res;
18335 
18336   // If a constant-expression is a reference to a variable where we delay
18337   // deciding whether it is an odr-use, just assume we will apply the
18338   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18339   // (a non-type template argument), we have special handling anyway.
18340   return CheckLValueToRValueConversionOperand(Res.get());
18341 }
18342 
18343 void Sema::CleanupVarDeclMarking() {
18344   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18345   // call.
18346   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18347   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18348 
18349   for (Expr *E : LocalMaybeODRUseExprs) {
18350     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18351       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18352                          DRE->getLocation(), *this);
18353     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18354       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18355                          *this);
18356     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18357       for (VarDecl *VD : *FP)
18358         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18359     } else {
18360       llvm_unreachable("Unexpected expression");
18361     }
18362   }
18363 
18364   assert(MaybeODRUseExprs.empty() &&
18365          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18366 }
18367 
18368 static void DoMarkVarDeclReferenced(
18369     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18370     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18371   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18372           isa<FunctionParmPackExpr>(E)) &&
18373          "Invalid Expr argument to DoMarkVarDeclReferenced");
18374   Var->setReferenced();
18375 
18376   if (Var->isInvalidDecl())
18377     return;
18378 
18379   auto *MSI = Var->getMemberSpecializationInfo();
18380   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18381                                        : Var->getTemplateSpecializationKind();
18382 
18383   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18384   bool UsableInConstantExpr =
18385       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18386 
18387   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18388     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18389   }
18390 
18391   // C++20 [expr.const]p12:
18392   //   A variable [...] is needed for constant evaluation if it is [...] a
18393   //   variable whose name appears as a potentially constant evaluated
18394   //   expression that is either a contexpr variable or is of non-volatile
18395   //   const-qualified integral type or of reference type
18396   bool NeededForConstantEvaluation =
18397       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18398 
18399   bool NeedDefinition =
18400       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18401 
18402   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18403          "Can't instantiate a partial template specialization.");
18404 
18405   // If this might be a member specialization of a static data member, check
18406   // the specialization is visible. We already did the checks for variable
18407   // template specializations when we created them.
18408   if (NeedDefinition && TSK != TSK_Undeclared &&
18409       !isa<VarTemplateSpecializationDecl>(Var))
18410     SemaRef.checkSpecializationVisibility(Loc, Var);
18411 
18412   // Perform implicit instantiation of static data members, static data member
18413   // templates of class templates, and variable template specializations. Delay
18414   // instantiations of variable templates, except for those that could be used
18415   // in a constant expression.
18416   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18417     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18418     // instantiation declaration if a variable is usable in a constant
18419     // expression (among other cases).
18420     bool TryInstantiating =
18421         TSK == TSK_ImplicitInstantiation ||
18422         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18423 
18424     if (TryInstantiating) {
18425       SourceLocation PointOfInstantiation =
18426           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18427       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18428       if (FirstInstantiation) {
18429         PointOfInstantiation = Loc;
18430         if (MSI)
18431           MSI->setPointOfInstantiation(PointOfInstantiation);
18432           // FIXME: Notify listener.
18433         else
18434           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18435       }
18436 
18437       if (UsableInConstantExpr) {
18438         // Do not defer instantiations of variables that could be used in a
18439         // constant expression.
18440         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18441           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18442         });
18443 
18444         // Re-set the member to trigger a recomputation of the dependence bits
18445         // for the expression.
18446         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18447           DRE->setDecl(DRE->getDecl());
18448         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18449           ME->setMemberDecl(ME->getMemberDecl());
18450       } else if (FirstInstantiation ||
18451                  isa<VarTemplateSpecializationDecl>(Var)) {
18452         // FIXME: For a specialization of a variable template, we don't
18453         // distinguish between "declaration and type implicitly instantiated"
18454         // and "implicit instantiation of definition requested", so we have
18455         // no direct way to avoid enqueueing the pending instantiation
18456         // multiple times.
18457         SemaRef.PendingInstantiations
18458             .push_back(std::make_pair(Var, PointOfInstantiation));
18459       }
18460     }
18461   }
18462 
18463   // C++2a [basic.def.odr]p4:
18464   //   A variable x whose name appears as a potentially-evaluated expression e
18465   //   is odr-used by e unless
18466   //   -- x is a reference that is usable in constant expressions
18467   //   -- x is a variable of non-reference type that is usable in constant
18468   //      expressions and has no mutable subobjects [FIXME], and e is an
18469   //      element of the set of potential results of an expression of
18470   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18471   //      conversion is applied
18472   //   -- x is a variable of non-reference type, and e is an element of the set
18473   //      of potential results of a discarded-value expression to which the
18474   //      lvalue-to-rvalue conversion is not applied [FIXME]
18475   //
18476   // We check the first part of the second bullet here, and
18477   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18478   // FIXME: To get the third bullet right, we need to delay this even for
18479   // variables that are not usable in constant expressions.
18480 
18481   // If we already know this isn't an odr-use, there's nothing more to do.
18482   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18483     if (DRE->isNonOdrUse())
18484       return;
18485   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18486     if (ME->isNonOdrUse())
18487       return;
18488 
18489   switch (OdrUse) {
18490   case OdrUseContext::None:
18491     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18492            "missing non-odr-use marking for unevaluated decl ref");
18493     break;
18494 
18495   case OdrUseContext::FormallyOdrUsed:
18496     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18497     // behavior.
18498     break;
18499 
18500   case OdrUseContext::Used:
18501     // If we might later find that this expression isn't actually an odr-use,
18502     // delay the marking.
18503     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18504       SemaRef.MaybeODRUseExprs.insert(E);
18505     else
18506       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18507     break;
18508 
18509   case OdrUseContext::Dependent:
18510     // If this is a dependent context, we don't need to mark variables as
18511     // odr-used, but we may still need to track them for lambda capture.
18512     // FIXME: Do we also need to do this inside dependent typeid expressions
18513     // (which are modeled as unevaluated at this point)?
18514     const bool RefersToEnclosingScope =
18515         (SemaRef.CurContext != Var->getDeclContext() &&
18516          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18517     if (RefersToEnclosingScope) {
18518       LambdaScopeInfo *const LSI =
18519           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18520       if (LSI && (!LSI->CallOperator ||
18521                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18522         // If a variable could potentially be odr-used, defer marking it so
18523         // until we finish analyzing the full expression for any
18524         // lvalue-to-rvalue
18525         // or discarded value conversions that would obviate odr-use.
18526         // Add it to the list of potential captures that will be analyzed
18527         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18528         // unless the variable is a reference that was initialized by a constant
18529         // expression (this will never need to be captured or odr-used).
18530         //
18531         // FIXME: We can simplify this a lot after implementing P0588R1.
18532         assert(E && "Capture variable should be used in an expression.");
18533         if (!Var->getType()->isReferenceType() ||
18534             !Var->isUsableInConstantExpressions(SemaRef.Context))
18535           LSI->addPotentialCapture(E->IgnoreParens());
18536       }
18537     }
18538     break;
18539   }
18540 }
18541 
18542 /// Mark a variable referenced, and check whether it is odr-used
18543 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18544 /// used directly for normal expressions referring to VarDecl.
18545 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18546   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18547 }
18548 
18549 static void
18550 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18551                    bool MightBeOdrUse,
18552                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18553   if (SemaRef.isInOpenMPDeclareTargetContext())
18554     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18555 
18556   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18557     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18558     return;
18559   }
18560 
18561   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18562 
18563   // If this is a call to a method via a cast, also mark the method in the
18564   // derived class used in case codegen can devirtualize the call.
18565   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18566   if (!ME)
18567     return;
18568   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18569   if (!MD)
18570     return;
18571   // Only attempt to devirtualize if this is truly a virtual call.
18572   bool IsVirtualCall = MD->isVirtual() &&
18573                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18574   if (!IsVirtualCall)
18575     return;
18576 
18577   // If it's possible to devirtualize the call, mark the called function
18578   // referenced.
18579   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18580       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18581   if (DM)
18582     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18583 }
18584 
18585 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18586 ///
18587 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18588 /// handled with care if the DeclRefExpr is not newly-created.
18589 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18590   // TODO: update this with DR# once a defect report is filed.
18591   // C++11 defect. The address of a pure member should not be an ODR use, even
18592   // if it's a qualified reference.
18593   bool OdrUse = true;
18594   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18595     if (Method->isVirtual() &&
18596         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18597       OdrUse = false;
18598 
18599   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18600     if (!isConstantEvaluated() && FD->isConsteval() &&
18601         !RebuildingImmediateInvocation)
18602       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18603   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18604                      RefsMinusAssignments);
18605 }
18606 
18607 /// Perform reference-marking and odr-use handling for a MemberExpr.
18608 void Sema::MarkMemberReferenced(MemberExpr *E) {
18609   // C++11 [basic.def.odr]p2:
18610   //   A non-overloaded function whose name appears as a potentially-evaluated
18611   //   expression or a member of a set of candidate functions, if selected by
18612   //   overload resolution when referred to from a potentially-evaluated
18613   //   expression, is odr-used, unless it is a pure virtual function and its
18614   //   name is not explicitly qualified.
18615   bool MightBeOdrUse = true;
18616   if (E->performsVirtualDispatch(getLangOpts())) {
18617     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18618       if (Method->isPure())
18619         MightBeOdrUse = false;
18620   }
18621   SourceLocation Loc =
18622       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18623   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18624                      RefsMinusAssignments);
18625 }
18626 
18627 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18628 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18629   for (VarDecl *VD : *E)
18630     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18631                        RefsMinusAssignments);
18632 }
18633 
18634 /// Perform marking for a reference to an arbitrary declaration.  It
18635 /// marks the declaration referenced, and performs odr-use checking for
18636 /// functions and variables. This method should not be used when building a
18637 /// normal expression which refers to a variable.
18638 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18639                                  bool MightBeOdrUse) {
18640   if (MightBeOdrUse) {
18641     if (auto *VD = dyn_cast<VarDecl>(D)) {
18642       MarkVariableReferenced(Loc, VD);
18643       return;
18644     }
18645   }
18646   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18647     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18648     return;
18649   }
18650   D->setReferenced();
18651 }
18652 
18653 namespace {
18654   // Mark all of the declarations used by a type as referenced.
18655   // FIXME: Not fully implemented yet! We need to have a better understanding
18656   // of when we're entering a context we should not recurse into.
18657   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18658   // TreeTransforms rebuilding the type in a new context. Rather than
18659   // duplicating the TreeTransform logic, we should consider reusing it here.
18660   // Currently that causes problems when rebuilding LambdaExprs.
18661   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18662     Sema &S;
18663     SourceLocation Loc;
18664 
18665   public:
18666     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18667 
18668     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18669 
18670     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18671   };
18672 }
18673 
18674 bool MarkReferencedDecls::TraverseTemplateArgument(
18675     const TemplateArgument &Arg) {
18676   {
18677     // A non-type template argument is a constant-evaluated context.
18678     EnterExpressionEvaluationContext Evaluated(
18679         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18680     if (Arg.getKind() == TemplateArgument::Declaration) {
18681       if (Decl *D = Arg.getAsDecl())
18682         S.MarkAnyDeclReferenced(Loc, D, true);
18683     } else if (Arg.getKind() == TemplateArgument::Expression) {
18684       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18685     }
18686   }
18687 
18688   return Inherited::TraverseTemplateArgument(Arg);
18689 }
18690 
18691 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18692   MarkReferencedDecls Marker(*this, Loc);
18693   Marker.TraverseType(T);
18694 }
18695 
18696 namespace {
18697 /// Helper class that marks all of the declarations referenced by
18698 /// potentially-evaluated subexpressions as "referenced".
18699 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18700 public:
18701   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18702   bool SkipLocalVariables;
18703 
18704   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18705       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18706 
18707   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18708     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18709   }
18710 
18711   void VisitDeclRefExpr(DeclRefExpr *E) {
18712     // If we were asked not to visit local variables, don't.
18713     if (SkipLocalVariables) {
18714       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18715         if (VD->hasLocalStorage())
18716           return;
18717     }
18718 
18719     // FIXME: This can trigger the instantiation of the initializer of a
18720     // variable, which can cause the expression to become value-dependent
18721     // or error-dependent. Do we need to propagate the new dependence bits?
18722     S.MarkDeclRefReferenced(E);
18723   }
18724 
18725   void VisitMemberExpr(MemberExpr *E) {
18726     S.MarkMemberReferenced(E);
18727     Visit(E->getBase());
18728   }
18729 };
18730 } // namespace
18731 
18732 /// Mark any declarations that appear within this expression or any
18733 /// potentially-evaluated subexpressions as "referenced".
18734 ///
18735 /// \param SkipLocalVariables If true, don't mark local variables as
18736 /// 'referenced'.
18737 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18738                                             bool SkipLocalVariables) {
18739   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18740 }
18741 
18742 /// Emit a diagnostic that describes an effect on the run-time behavior
18743 /// of the program being compiled.
18744 ///
18745 /// This routine emits the given diagnostic when the code currently being
18746 /// type-checked is "potentially evaluated", meaning that there is a
18747 /// possibility that the code will actually be executable. Code in sizeof()
18748 /// expressions, code used only during overload resolution, etc., are not
18749 /// potentially evaluated. This routine will suppress such diagnostics or,
18750 /// in the absolutely nutty case of potentially potentially evaluated
18751 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18752 /// later.
18753 ///
18754 /// This routine should be used for all diagnostics that describe the run-time
18755 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18756 /// Failure to do so will likely result in spurious diagnostics or failures
18757 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18758 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18759                                const PartialDiagnostic &PD) {
18760   switch (ExprEvalContexts.back().Context) {
18761   case ExpressionEvaluationContext::Unevaluated:
18762   case ExpressionEvaluationContext::UnevaluatedList:
18763   case ExpressionEvaluationContext::UnevaluatedAbstract:
18764   case ExpressionEvaluationContext::DiscardedStatement:
18765     // The argument will never be evaluated, so don't complain.
18766     break;
18767 
18768   case ExpressionEvaluationContext::ConstantEvaluated:
18769     // Relevant diagnostics should be produced by constant evaluation.
18770     break;
18771 
18772   case ExpressionEvaluationContext::PotentiallyEvaluated:
18773   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18774     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18775       FunctionScopes.back()->PossiblyUnreachableDiags.
18776         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18777       return true;
18778     }
18779 
18780     // The initializer of a constexpr variable or of the first declaration of a
18781     // static data member is not syntactically a constant evaluated constant,
18782     // but nonetheless is always required to be a constant expression, so we
18783     // can skip diagnosing.
18784     // FIXME: Using the mangling context here is a hack.
18785     if (auto *VD = dyn_cast_or_null<VarDecl>(
18786             ExprEvalContexts.back().ManglingContextDecl)) {
18787       if (VD->isConstexpr() ||
18788           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18789         break;
18790       // FIXME: For any other kind of variable, we should build a CFG for its
18791       // initializer and check whether the context in question is reachable.
18792     }
18793 
18794     Diag(Loc, PD);
18795     return true;
18796   }
18797 
18798   return false;
18799 }
18800 
18801 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18802                                const PartialDiagnostic &PD) {
18803   return DiagRuntimeBehavior(
18804       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18805 }
18806 
18807 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18808                                CallExpr *CE, FunctionDecl *FD) {
18809   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18810     return false;
18811 
18812   // If we're inside a decltype's expression, don't check for a valid return
18813   // type or construct temporaries until we know whether this is the last call.
18814   if (ExprEvalContexts.back().ExprContext ==
18815       ExpressionEvaluationContextRecord::EK_Decltype) {
18816     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18817     return false;
18818   }
18819 
18820   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18821     FunctionDecl *FD;
18822     CallExpr *CE;
18823 
18824   public:
18825     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18826       : FD(FD), CE(CE) { }
18827 
18828     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18829       if (!FD) {
18830         S.Diag(Loc, diag::err_call_incomplete_return)
18831           << T << CE->getSourceRange();
18832         return;
18833       }
18834 
18835       S.Diag(Loc, diag::err_call_function_incomplete_return)
18836           << CE->getSourceRange() << FD << T;
18837       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18838           << FD->getDeclName();
18839     }
18840   } Diagnoser(FD, CE);
18841 
18842   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18843     return true;
18844 
18845   return false;
18846 }
18847 
18848 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18849 // will prevent this condition from triggering, which is what we want.
18850 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18851   SourceLocation Loc;
18852 
18853   unsigned diagnostic = diag::warn_condition_is_assignment;
18854   bool IsOrAssign = false;
18855 
18856   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18857     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18858       return;
18859 
18860     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18861 
18862     // Greylist some idioms by putting them into a warning subcategory.
18863     if (ObjCMessageExpr *ME
18864           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18865       Selector Sel = ME->getSelector();
18866 
18867       // self = [<foo> init...]
18868       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18869         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18870 
18871       // <foo> = [<bar> nextObject]
18872       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18873         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18874     }
18875 
18876     Loc = Op->getOperatorLoc();
18877   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18878     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18879       return;
18880 
18881     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18882     Loc = Op->getOperatorLoc();
18883   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18884     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18885   else {
18886     // Not an assignment.
18887     return;
18888   }
18889 
18890   Diag(Loc, diagnostic) << E->getSourceRange();
18891 
18892   SourceLocation Open = E->getBeginLoc();
18893   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18894   Diag(Loc, diag::note_condition_assign_silence)
18895         << FixItHint::CreateInsertion(Open, "(")
18896         << FixItHint::CreateInsertion(Close, ")");
18897 
18898   if (IsOrAssign)
18899     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18900       << FixItHint::CreateReplacement(Loc, "!=");
18901   else
18902     Diag(Loc, diag::note_condition_assign_to_comparison)
18903       << FixItHint::CreateReplacement(Loc, "==");
18904 }
18905 
18906 /// Redundant parentheses over an equality comparison can indicate
18907 /// that the user intended an assignment used as condition.
18908 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18909   // Don't warn if the parens came from a macro.
18910   SourceLocation parenLoc = ParenE->getBeginLoc();
18911   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18912     return;
18913   // Don't warn for dependent expressions.
18914   if (ParenE->isTypeDependent())
18915     return;
18916 
18917   Expr *E = ParenE->IgnoreParens();
18918 
18919   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18920     if (opE->getOpcode() == BO_EQ &&
18921         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18922                                                            == Expr::MLV_Valid) {
18923       SourceLocation Loc = opE->getOperatorLoc();
18924 
18925       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18926       SourceRange ParenERange = ParenE->getSourceRange();
18927       Diag(Loc, diag::note_equality_comparison_silence)
18928         << FixItHint::CreateRemoval(ParenERange.getBegin())
18929         << FixItHint::CreateRemoval(ParenERange.getEnd());
18930       Diag(Loc, diag::note_equality_comparison_to_assign)
18931         << FixItHint::CreateReplacement(Loc, "=");
18932     }
18933 }
18934 
18935 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18936                                        bool IsConstexpr) {
18937   DiagnoseAssignmentAsCondition(E);
18938   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18939     DiagnoseEqualityWithExtraParens(parenE);
18940 
18941   ExprResult result = CheckPlaceholderExpr(E);
18942   if (result.isInvalid()) return ExprError();
18943   E = result.get();
18944 
18945   if (!E->isTypeDependent()) {
18946     if (getLangOpts().CPlusPlus)
18947       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18948 
18949     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18950     if (ERes.isInvalid())
18951       return ExprError();
18952     E = ERes.get();
18953 
18954     QualType T = E->getType();
18955     if (!T->isScalarType()) { // C99 6.8.4.1p1
18956       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18957         << T << E->getSourceRange();
18958       return ExprError();
18959     }
18960     CheckBoolLikeConversion(E, Loc);
18961   }
18962 
18963   return E;
18964 }
18965 
18966 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18967                                            Expr *SubExpr, ConditionKind CK) {
18968   // Empty conditions are valid in for-statements.
18969   if (!SubExpr)
18970     return ConditionResult();
18971 
18972   ExprResult Cond;
18973   switch (CK) {
18974   case ConditionKind::Boolean:
18975     Cond = CheckBooleanCondition(Loc, SubExpr);
18976     break;
18977 
18978   case ConditionKind::ConstexprIf:
18979     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18980     break;
18981 
18982   case ConditionKind::Switch:
18983     Cond = CheckSwitchCondition(Loc, SubExpr);
18984     break;
18985   }
18986   if (Cond.isInvalid()) {
18987     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18988                               {SubExpr});
18989     if (!Cond.get())
18990       return ConditionError();
18991   }
18992   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18993   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18994   if (!FullExpr.get())
18995     return ConditionError();
18996 
18997   return ConditionResult(*this, nullptr, FullExpr,
18998                          CK == ConditionKind::ConstexprIf);
18999 }
19000 
19001 namespace {
19002   /// A visitor for rebuilding a call to an __unknown_any expression
19003   /// to have an appropriate type.
19004   struct RebuildUnknownAnyFunction
19005     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19006 
19007     Sema &S;
19008 
19009     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19010 
19011     ExprResult VisitStmt(Stmt *S) {
19012       llvm_unreachable("unexpected statement!");
19013     }
19014 
19015     ExprResult VisitExpr(Expr *E) {
19016       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19017         << E->getSourceRange();
19018       return ExprError();
19019     }
19020 
19021     /// Rebuild an expression which simply semantically wraps another
19022     /// expression which it shares the type and value kind of.
19023     template <class T> ExprResult rebuildSugarExpr(T *E) {
19024       ExprResult SubResult = Visit(E->getSubExpr());
19025       if (SubResult.isInvalid()) return ExprError();
19026 
19027       Expr *SubExpr = SubResult.get();
19028       E->setSubExpr(SubExpr);
19029       E->setType(SubExpr->getType());
19030       E->setValueKind(SubExpr->getValueKind());
19031       assert(E->getObjectKind() == OK_Ordinary);
19032       return E;
19033     }
19034 
19035     ExprResult VisitParenExpr(ParenExpr *E) {
19036       return rebuildSugarExpr(E);
19037     }
19038 
19039     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19040       return rebuildSugarExpr(E);
19041     }
19042 
19043     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19044       ExprResult SubResult = Visit(E->getSubExpr());
19045       if (SubResult.isInvalid()) return ExprError();
19046 
19047       Expr *SubExpr = SubResult.get();
19048       E->setSubExpr(SubExpr);
19049       E->setType(S.Context.getPointerType(SubExpr->getType()));
19050       assert(E->getValueKind() == VK_RValue);
19051       assert(E->getObjectKind() == OK_Ordinary);
19052       return E;
19053     }
19054 
19055     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19056       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19057 
19058       E->setType(VD->getType());
19059 
19060       assert(E->getValueKind() == VK_RValue);
19061       if (S.getLangOpts().CPlusPlus &&
19062           !(isa<CXXMethodDecl>(VD) &&
19063             cast<CXXMethodDecl>(VD)->isInstance()))
19064         E->setValueKind(VK_LValue);
19065 
19066       return E;
19067     }
19068 
19069     ExprResult VisitMemberExpr(MemberExpr *E) {
19070       return resolveDecl(E, E->getMemberDecl());
19071     }
19072 
19073     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19074       return resolveDecl(E, E->getDecl());
19075     }
19076   };
19077 }
19078 
19079 /// Given a function expression of unknown-any type, try to rebuild it
19080 /// to have a function type.
19081 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19082   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19083   if (Result.isInvalid()) return ExprError();
19084   return S.DefaultFunctionArrayConversion(Result.get());
19085 }
19086 
19087 namespace {
19088   /// A visitor for rebuilding an expression of type __unknown_anytype
19089   /// into one which resolves the type directly on the referring
19090   /// expression.  Strict preservation of the original source
19091   /// structure is not a goal.
19092   struct RebuildUnknownAnyExpr
19093     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19094 
19095     Sema &S;
19096 
19097     /// The current destination type.
19098     QualType DestType;
19099 
19100     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19101       : S(S), DestType(CastType) {}
19102 
19103     ExprResult VisitStmt(Stmt *S) {
19104       llvm_unreachable("unexpected statement!");
19105     }
19106 
19107     ExprResult VisitExpr(Expr *E) {
19108       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19109         << E->getSourceRange();
19110       return ExprError();
19111     }
19112 
19113     ExprResult VisitCallExpr(CallExpr *E);
19114     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19115 
19116     /// Rebuild an expression which simply semantically wraps another
19117     /// expression which it shares the type and value kind of.
19118     template <class T> ExprResult rebuildSugarExpr(T *E) {
19119       ExprResult SubResult = Visit(E->getSubExpr());
19120       if (SubResult.isInvalid()) return ExprError();
19121       Expr *SubExpr = SubResult.get();
19122       E->setSubExpr(SubExpr);
19123       E->setType(SubExpr->getType());
19124       E->setValueKind(SubExpr->getValueKind());
19125       assert(E->getObjectKind() == OK_Ordinary);
19126       return E;
19127     }
19128 
19129     ExprResult VisitParenExpr(ParenExpr *E) {
19130       return rebuildSugarExpr(E);
19131     }
19132 
19133     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19134       return rebuildSugarExpr(E);
19135     }
19136 
19137     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19138       const PointerType *Ptr = DestType->getAs<PointerType>();
19139       if (!Ptr) {
19140         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19141           << E->getSourceRange();
19142         return ExprError();
19143       }
19144 
19145       if (isa<CallExpr>(E->getSubExpr())) {
19146         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19147           << E->getSourceRange();
19148         return ExprError();
19149       }
19150 
19151       assert(E->getValueKind() == VK_RValue);
19152       assert(E->getObjectKind() == OK_Ordinary);
19153       E->setType(DestType);
19154 
19155       // Build the sub-expression as if it were an object of the pointee type.
19156       DestType = Ptr->getPointeeType();
19157       ExprResult SubResult = Visit(E->getSubExpr());
19158       if (SubResult.isInvalid()) return ExprError();
19159       E->setSubExpr(SubResult.get());
19160       return E;
19161     }
19162 
19163     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19164 
19165     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19166 
19167     ExprResult VisitMemberExpr(MemberExpr *E) {
19168       return resolveDecl(E, E->getMemberDecl());
19169     }
19170 
19171     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19172       return resolveDecl(E, E->getDecl());
19173     }
19174   };
19175 }
19176 
19177 /// Rebuilds a call expression which yielded __unknown_anytype.
19178 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19179   Expr *CalleeExpr = E->getCallee();
19180 
19181   enum FnKind {
19182     FK_MemberFunction,
19183     FK_FunctionPointer,
19184     FK_BlockPointer
19185   };
19186 
19187   FnKind Kind;
19188   QualType CalleeType = CalleeExpr->getType();
19189   if (CalleeType == S.Context.BoundMemberTy) {
19190     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19191     Kind = FK_MemberFunction;
19192     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19193   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19194     CalleeType = Ptr->getPointeeType();
19195     Kind = FK_FunctionPointer;
19196   } else {
19197     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19198     Kind = FK_BlockPointer;
19199   }
19200   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19201 
19202   // Verify that this is a legal result type of a function.
19203   if (DestType->isArrayType() || DestType->isFunctionType()) {
19204     unsigned diagID = diag::err_func_returning_array_function;
19205     if (Kind == FK_BlockPointer)
19206       diagID = diag::err_block_returning_array_function;
19207 
19208     S.Diag(E->getExprLoc(), diagID)
19209       << DestType->isFunctionType() << DestType;
19210     return ExprError();
19211   }
19212 
19213   // Otherwise, go ahead and set DestType as the call's result.
19214   E->setType(DestType.getNonLValueExprType(S.Context));
19215   E->setValueKind(Expr::getValueKindForType(DestType));
19216   assert(E->getObjectKind() == OK_Ordinary);
19217 
19218   // Rebuild the function type, replacing the result type with DestType.
19219   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19220   if (Proto) {
19221     // __unknown_anytype(...) is a special case used by the debugger when
19222     // it has no idea what a function's signature is.
19223     //
19224     // We want to build this call essentially under the K&R
19225     // unprototyped rules, but making a FunctionNoProtoType in C++
19226     // would foul up all sorts of assumptions.  However, we cannot
19227     // simply pass all arguments as variadic arguments, nor can we
19228     // portably just call the function under a non-variadic type; see
19229     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19230     // However, it turns out that in practice it is generally safe to
19231     // call a function declared as "A foo(B,C,D);" under the prototype
19232     // "A foo(B,C,D,...);".  The only known exception is with the
19233     // Windows ABI, where any variadic function is implicitly cdecl
19234     // regardless of its normal CC.  Therefore we change the parameter
19235     // types to match the types of the arguments.
19236     //
19237     // This is a hack, but it is far superior to moving the
19238     // corresponding target-specific code from IR-gen to Sema/AST.
19239 
19240     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19241     SmallVector<QualType, 8> ArgTypes;
19242     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19243       ArgTypes.reserve(E->getNumArgs());
19244       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19245         Expr *Arg = E->getArg(i);
19246         QualType ArgType = Arg->getType();
19247         if (E->isLValue()) {
19248           ArgType = S.Context.getLValueReferenceType(ArgType);
19249         } else if (E->isXValue()) {
19250           ArgType = S.Context.getRValueReferenceType(ArgType);
19251         }
19252         ArgTypes.push_back(ArgType);
19253       }
19254       ParamTypes = ArgTypes;
19255     }
19256     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19257                                          Proto->getExtProtoInfo());
19258   } else {
19259     DestType = S.Context.getFunctionNoProtoType(DestType,
19260                                                 FnType->getExtInfo());
19261   }
19262 
19263   // Rebuild the appropriate pointer-to-function type.
19264   switch (Kind) {
19265   case FK_MemberFunction:
19266     // Nothing to do.
19267     break;
19268 
19269   case FK_FunctionPointer:
19270     DestType = S.Context.getPointerType(DestType);
19271     break;
19272 
19273   case FK_BlockPointer:
19274     DestType = S.Context.getBlockPointerType(DestType);
19275     break;
19276   }
19277 
19278   // Finally, we can recurse.
19279   ExprResult CalleeResult = Visit(CalleeExpr);
19280   if (!CalleeResult.isUsable()) return ExprError();
19281   E->setCallee(CalleeResult.get());
19282 
19283   // Bind a temporary if necessary.
19284   return S.MaybeBindToTemporary(E);
19285 }
19286 
19287 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19288   // Verify that this is a legal result type of a call.
19289   if (DestType->isArrayType() || DestType->isFunctionType()) {
19290     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19291       << DestType->isFunctionType() << DestType;
19292     return ExprError();
19293   }
19294 
19295   // Rewrite the method result type if available.
19296   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19297     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19298     Method->setReturnType(DestType);
19299   }
19300 
19301   // Change the type of the message.
19302   E->setType(DestType.getNonReferenceType());
19303   E->setValueKind(Expr::getValueKindForType(DestType));
19304 
19305   return S.MaybeBindToTemporary(E);
19306 }
19307 
19308 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19309   // The only case we should ever see here is a function-to-pointer decay.
19310   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19311     assert(E->getValueKind() == VK_RValue);
19312     assert(E->getObjectKind() == OK_Ordinary);
19313 
19314     E->setType(DestType);
19315 
19316     // Rebuild the sub-expression as the pointee (function) type.
19317     DestType = DestType->castAs<PointerType>()->getPointeeType();
19318 
19319     ExprResult Result = Visit(E->getSubExpr());
19320     if (!Result.isUsable()) return ExprError();
19321 
19322     E->setSubExpr(Result.get());
19323     return E;
19324   } else if (E->getCastKind() == CK_LValueToRValue) {
19325     assert(E->getValueKind() == VK_RValue);
19326     assert(E->getObjectKind() == OK_Ordinary);
19327 
19328     assert(isa<BlockPointerType>(E->getType()));
19329 
19330     E->setType(DestType);
19331 
19332     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19333     DestType = S.Context.getLValueReferenceType(DestType);
19334 
19335     ExprResult Result = Visit(E->getSubExpr());
19336     if (!Result.isUsable()) return ExprError();
19337 
19338     E->setSubExpr(Result.get());
19339     return E;
19340   } else {
19341     llvm_unreachable("Unhandled cast type!");
19342   }
19343 }
19344 
19345 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19346   ExprValueKind ValueKind = VK_LValue;
19347   QualType Type = DestType;
19348 
19349   // We know how to make this work for certain kinds of decls:
19350 
19351   //  - functions
19352   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19353     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19354       DestType = Ptr->getPointeeType();
19355       ExprResult Result = resolveDecl(E, VD);
19356       if (Result.isInvalid()) return ExprError();
19357       return S.ImpCastExprToType(Result.get(), Type,
19358                                  CK_FunctionToPointerDecay, VK_RValue);
19359     }
19360 
19361     if (!Type->isFunctionType()) {
19362       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19363         << VD << E->getSourceRange();
19364       return ExprError();
19365     }
19366     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19367       // We must match the FunctionDecl's type to the hack introduced in
19368       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19369       // type. See the lengthy commentary in that routine.
19370       QualType FDT = FD->getType();
19371       const FunctionType *FnType = FDT->castAs<FunctionType>();
19372       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19373       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19374       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19375         SourceLocation Loc = FD->getLocation();
19376         FunctionDecl *NewFD = FunctionDecl::Create(
19377             S.Context, FD->getDeclContext(), Loc, Loc,
19378             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19379             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19380             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19381 
19382         if (FD->getQualifier())
19383           NewFD->setQualifierInfo(FD->getQualifierLoc());
19384 
19385         SmallVector<ParmVarDecl*, 16> Params;
19386         for (const auto &AI : FT->param_types()) {
19387           ParmVarDecl *Param =
19388             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19389           Param->setScopeInfo(0, Params.size());
19390           Params.push_back(Param);
19391         }
19392         NewFD->setParams(Params);
19393         DRE->setDecl(NewFD);
19394         VD = DRE->getDecl();
19395       }
19396     }
19397 
19398     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19399       if (MD->isInstance()) {
19400         ValueKind = VK_RValue;
19401         Type = S.Context.BoundMemberTy;
19402       }
19403 
19404     // Function references aren't l-values in C.
19405     if (!S.getLangOpts().CPlusPlus)
19406       ValueKind = VK_RValue;
19407 
19408   //  - variables
19409   } else if (isa<VarDecl>(VD)) {
19410     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19411       Type = RefTy->getPointeeType();
19412     } else if (Type->isFunctionType()) {
19413       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19414         << VD << E->getSourceRange();
19415       return ExprError();
19416     }
19417 
19418   //  - nothing else
19419   } else {
19420     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19421       << VD << E->getSourceRange();
19422     return ExprError();
19423   }
19424 
19425   // Modifying the declaration like this is friendly to IR-gen but
19426   // also really dangerous.
19427   VD->setType(DestType);
19428   E->setType(Type);
19429   E->setValueKind(ValueKind);
19430   return E;
19431 }
19432 
19433 /// Check a cast of an unknown-any type.  We intentionally only
19434 /// trigger this for C-style casts.
19435 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19436                                      Expr *CastExpr, CastKind &CastKind,
19437                                      ExprValueKind &VK, CXXCastPath &Path) {
19438   // The type we're casting to must be either void or complete.
19439   if (!CastType->isVoidType() &&
19440       RequireCompleteType(TypeRange.getBegin(), CastType,
19441                           diag::err_typecheck_cast_to_incomplete))
19442     return ExprError();
19443 
19444   // Rewrite the casted expression from scratch.
19445   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19446   if (!result.isUsable()) return ExprError();
19447 
19448   CastExpr = result.get();
19449   VK = CastExpr->getValueKind();
19450   CastKind = CK_NoOp;
19451 
19452   return CastExpr;
19453 }
19454 
19455 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19456   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19457 }
19458 
19459 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19460                                     Expr *arg, QualType &paramType) {
19461   // If the syntactic form of the argument is not an explicit cast of
19462   // any sort, just do default argument promotion.
19463   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19464   if (!castArg) {
19465     ExprResult result = DefaultArgumentPromotion(arg);
19466     if (result.isInvalid()) return ExprError();
19467     paramType = result.get()->getType();
19468     return result;
19469   }
19470 
19471   // Otherwise, use the type that was written in the explicit cast.
19472   assert(!arg->hasPlaceholderType());
19473   paramType = castArg->getTypeAsWritten();
19474 
19475   // Copy-initialize a parameter of that type.
19476   InitializedEntity entity =
19477     InitializedEntity::InitializeParameter(Context, paramType,
19478                                            /*consumed*/ false);
19479   return PerformCopyInitialization(entity, callLoc, arg);
19480 }
19481 
19482 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19483   Expr *orig = E;
19484   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19485   while (true) {
19486     E = E->IgnoreParenImpCasts();
19487     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19488       E = call->getCallee();
19489       diagID = diag::err_uncasted_call_of_unknown_any;
19490     } else {
19491       break;
19492     }
19493   }
19494 
19495   SourceLocation loc;
19496   NamedDecl *d;
19497   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19498     loc = ref->getLocation();
19499     d = ref->getDecl();
19500   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19501     loc = mem->getMemberLoc();
19502     d = mem->getMemberDecl();
19503   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19504     diagID = diag::err_uncasted_call_of_unknown_any;
19505     loc = msg->getSelectorStartLoc();
19506     d = msg->getMethodDecl();
19507     if (!d) {
19508       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19509         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19510         << orig->getSourceRange();
19511       return ExprError();
19512     }
19513   } else {
19514     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19515       << E->getSourceRange();
19516     return ExprError();
19517   }
19518 
19519   S.Diag(loc, diagID) << d << orig->getSourceRange();
19520 
19521   // Never recoverable.
19522   return ExprError();
19523 }
19524 
19525 /// Check for operands with placeholder types and complain if found.
19526 /// Returns ExprError() if there was an error and no recovery was possible.
19527 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19528   if (!Context.isDependenceAllowed()) {
19529     // C cannot handle TypoExpr nodes on either side of a binop because it
19530     // doesn't handle dependent types properly, so make sure any TypoExprs have
19531     // been dealt with before checking the operands.
19532     ExprResult Result = CorrectDelayedTyposInExpr(E);
19533     if (!Result.isUsable()) return ExprError();
19534     E = Result.get();
19535   }
19536 
19537   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19538   if (!placeholderType) return E;
19539 
19540   switch (placeholderType->getKind()) {
19541 
19542   // Overloaded expressions.
19543   case BuiltinType::Overload: {
19544     // Try to resolve a single function template specialization.
19545     // This is obligatory.
19546     ExprResult Result = E;
19547     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19548       return Result;
19549 
19550     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19551     // leaves Result unchanged on failure.
19552     Result = E;
19553     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19554       return Result;
19555 
19556     // If that failed, try to recover with a call.
19557     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19558                          /*complain*/ true);
19559     return Result;
19560   }
19561 
19562   // Bound member functions.
19563   case BuiltinType::BoundMember: {
19564     ExprResult result = E;
19565     const Expr *BME = E->IgnoreParens();
19566     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19567     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19568     if (isa<CXXPseudoDestructorExpr>(BME)) {
19569       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19570     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19571       if (ME->getMemberNameInfo().getName().getNameKind() ==
19572           DeclarationName::CXXDestructorName)
19573         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19574     }
19575     tryToRecoverWithCall(result, PD,
19576                          /*complain*/ true);
19577     return result;
19578   }
19579 
19580   // ARC unbridged casts.
19581   case BuiltinType::ARCUnbridgedCast: {
19582     Expr *realCast = stripARCUnbridgedCast(E);
19583     diagnoseARCUnbridgedCast(realCast);
19584     return realCast;
19585   }
19586 
19587   // Expressions of unknown type.
19588   case BuiltinType::UnknownAny:
19589     return diagnoseUnknownAnyExpr(*this, E);
19590 
19591   // Pseudo-objects.
19592   case BuiltinType::PseudoObject:
19593     return checkPseudoObjectRValue(E);
19594 
19595   case BuiltinType::BuiltinFn: {
19596     // Accept __noop without parens by implicitly converting it to a call expr.
19597     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19598     if (DRE) {
19599       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19600       if (FD->getBuiltinID() == Builtin::BI__noop) {
19601         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19602                               CK_BuiltinFnToFnPtr)
19603                 .get();
19604         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19605                                 VK_RValue, SourceLocation(),
19606                                 FPOptionsOverride());
19607       }
19608     }
19609 
19610     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19611     return ExprError();
19612   }
19613 
19614   case BuiltinType::IncompleteMatrixIdx:
19615     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19616              ->getRowIdx()
19617              ->getBeginLoc(),
19618          diag::err_matrix_incomplete_index);
19619     return ExprError();
19620 
19621   // Expressions of unknown type.
19622   case BuiltinType::OMPArraySection:
19623     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19624     return ExprError();
19625 
19626   // Expressions of unknown type.
19627   case BuiltinType::OMPArrayShaping:
19628     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19629 
19630   case BuiltinType::OMPIterator:
19631     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19632 
19633   // Everything else should be impossible.
19634 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19635   case BuiltinType::Id:
19636 #include "clang/Basic/OpenCLImageTypes.def"
19637 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19638   case BuiltinType::Id:
19639 #include "clang/Basic/OpenCLExtensionTypes.def"
19640 #define SVE_TYPE(Name, Id, SingletonId) \
19641   case BuiltinType::Id:
19642 #include "clang/Basic/AArch64SVEACLETypes.def"
19643 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19644   case BuiltinType::Id:
19645 #include "clang/Basic/PPCTypes.def"
19646 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19647 #include "clang/Basic/RISCVVTypes.def"
19648 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19649 #define PLACEHOLDER_TYPE(Id, SingletonId)
19650 #include "clang/AST/BuiltinTypes.def"
19651     break;
19652   }
19653 
19654   llvm_unreachable("invalid placeholder type!");
19655 }
19656 
19657 bool Sema::CheckCaseExpression(Expr *E) {
19658   if (E->isTypeDependent())
19659     return true;
19660   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19661     return E->getType()->isIntegralOrEnumerationType();
19662   return false;
19663 }
19664 
19665 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19666 ExprResult
19667 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19668   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19669          "Unknown Objective-C Boolean value!");
19670   QualType BoolT = Context.ObjCBuiltinBoolTy;
19671   if (!Context.getBOOLDecl()) {
19672     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19673                         Sema::LookupOrdinaryName);
19674     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19675       NamedDecl *ND = Result.getFoundDecl();
19676       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19677         Context.setBOOLDecl(TD);
19678     }
19679   }
19680   if (Context.getBOOLDecl())
19681     BoolT = Context.getBOOLType();
19682   return new (Context)
19683       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19684 }
19685 
19686 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19687     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19688     SourceLocation RParen) {
19689 
19690   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19691 
19692   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19693     return Spec.getPlatform() == Platform;
19694   });
19695 
19696   VersionTuple Version;
19697   if (Spec != AvailSpecs.end())
19698     Version = Spec->getVersion();
19699 
19700   // The use of `@available` in the enclosing context should be analyzed to
19701   // warn when it's used inappropriately (i.e. not if(@available)).
19702   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19703     Context->HasPotentialAvailabilityViolations = true;
19704 
19705   return new (Context)
19706       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19707 }
19708 
19709 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19710                                     ArrayRef<Expr *> SubExprs, QualType T) {
19711   if (!Context.getLangOpts().RecoveryAST)
19712     return ExprError();
19713 
19714   if (isSFINAEContext())
19715     return ExprError();
19716 
19717   if (T.isNull() || T->isUndeducedType() ||
19718       !Context.getLangOpts().RecoveryASTType)
19719     // We don't know the concrete type, fallback to dependent type.
19720     T = Context.DependentTy;
19721 
19722   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19723 }
19724