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/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/DiagnosticSema.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/LiteralSupport.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/AnalysisBasedWarnings.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Designator.h"
42 #include "clang/Sema/Initialization.h"
43 #include "clang/Sema/Lookup.h"
44 #include "clang/Sema/Overload.h"
45 #include "clang/Sema/ParsedTemplate.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaFixItUtils.h"
49 #include "clang/Sema/SemaInternal.h"
50 #include "clang/Sema/Template.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/ConvertUTF.h"
55 #include "llvm/Support/SaveAndRestore.h"
56 #include "llvm/Support/TypeSize.h"
57 
58 using namespace clang;
59 using namespace sema;
60 
61 /// Determine whether the use of this declaration is valid, without
62 /// emitting diagnostics.
63 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
64   // See if this is an auto-typed variable whose initializer we are parsing.
65   if (ParsingInitForAutoVars.count(D))
66     return false;
67 
68   // See if this is a deleted function.
69   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
70     if (FD->isDeleted())
71       return false;
72 
73     // If the function has a deduced return type, and we can't deduce it,
74     // then we can't use it either.
75     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
76         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
77       return false;
78 
79     // See if this is an aligned allocation/deallocation function that is
80     // unavailable.
81     if (TreatUnavailableAsInvalid &&
82         isUnavailableAlignedAllocationFunction(*FD))
83       return false;
84   }
85 
86   // See if this function is unavailable.
87   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
88       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
89     return false;
90 
91   if (isa<UnresolvedUsingIfExistsDecl>(D))
92     return false;
93 
94   return true;
95 }
96 
97 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
98   // Warn if this is used but marked unused.
99   if (const auto *A = D->getAttr<UnusedAttr>()) {
100     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
101     // should diagnose them.
102     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
103         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
104       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
105       if (DC && !DC->hasAttr<UnusedAttr>())
106         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
107     }
108   }
109 }
110 
111 /// Emit a note explaining that this function is deleted.
112 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113   assert(Decl && Decl->isDeleted());
114 
115   if (Decl->isDefaulted()) {
116     // If the method was explicitly defaulted, point at that declaration.
117     if (!Decl->isImplicit())
118       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119 
120     // Try to diagnose why this special member function was implicitly
121     // deleted. This might fail, if that reason no longer applies.
122     DiagnoseDeletedDefaultedFunction(Decl);
123     return;
124   }
125 
126   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
127   if (Ctor && Ctor->isInheritingConstructor())
128     return NoteDeletedInheritingConstructor(Ctor);
129 
130   Diag(Decl->getLocation(), diag::note_availability_specified_here)
131     << Decl << 1;
132 }
133 
134 /// Determine whether a FunctionDecl was ever declared with an
135 /// explicit storage class.
136 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
137   for (auto I : D->redecls()) {
138     if (I->getStorageClass() != SC_None)
139       return true;
140   }
141   return false;
142 }
143 
144 /// Check whether we're in an extern inline function and referring to a
145 /// variable or function with internal linkage (C11 6.7.4p3).
146 ///
147 /// This is only a warning because we used to silently accept this code, but
148 /// in many cases it will not behave correctly. This is not enabled in C++ mode
149 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
150 /// and so while there may still be user mistakes, most of the time we can't
151 /// prove that there are errors.
152 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
153                                                       const NamedDecl *D,
154                                                       SourceLocation Loc) {
155   // This is disabled under C++; there are too many ways for this to fire in
156   // contexts where the warning is a false positive, or where it is technically
157   // correct but benign.
158   if (S.getLangOpts().CPlusPlus)
159     return;
160 
161   // Check if this is an inlined function or method.
162   FunctionDecl *Current = S.getCurFunctionDecl();
163   if (!Current)
164     return;
165   if (!Current->isInlined())
166     return;
167   if (!Current->isExternallyVisible())
168     return;
169 
170   // Check if the decl has internal linkage.
171   if (D->getFormalLinkage() != InternalLinkage)
172     return;
173 
174   // Downgrade from ExtWarn to Extension if
175   //  (1) the supposedly external inline function is in the main file,
176   //      and probably won't be included anywhere else.
177   //  (2) the thing we're referencing is a pure function.
178   //  (3) the thing we're referencing is another inline function.
179   // This last can give us false negatives, but it's better than warning on
180   // wrappers for simple C library functions.
181   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
182   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
183   if (!DowngradeWarning && UsedFn)
184     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
185 
186   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
187                                : diag::ext_internal_in_extern_inline)
188     << /*IsVar=*/!UsedFn << D;
189 
190   S.MaybeSuggestAddingStaticToDecl(Current);
191 
192   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
193       << D;
194 }
195 
196 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
197   const FunctionDecl *First = Cur->getFirstDecl();
198 
199   // Suggest "static" on the function, if possible.
200   if (!hasAnyExplicitStorageClass(First)) {
201     SourceLocation DeclBegin = First->getSourceRange().getBegin();
202     Diag(DeclBegin, diag::note_convert_inline_to_static)
203       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
204   }
205 }
206 
207 /// Determine whether the use of this declaration is valid, and
208 /// emit any corresponding diagnostics.
209 ///
210 /// This routine diagnoses various problems with referencing
211 /// declarations that can occur when using a declaration. For example,
212 /// it might warn if a deprecated or unavailable declaration is being
213 /// used, or produce an error (and return true) if a C++0x deleted
214 /// function is being used.
215 ///
216 /// \returns true if there was an error (this declaration cannot be
217 /// referenced), false otherwise.
218 ///
219 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
220                              const ObjCInterfaceDecl *UnknownObjCClass,
221                              bool ObjCPropertyAccess,
222                              bool AvoidPartialAvailabilityChecks,
223                              ObjCInterfaceDecl *ClassReceiver) {
224   SourceLocation Loc = Locs.front();
225   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
226     // If there were any diagnostics suppressed by template argument deduction,
227     // emit them now.
228     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
229     if (Pos != SuppressedDiagnostics.end()) {
230       for (const PartialDiagnosticAt &Suppressed : Pos->second)
231         Diag(Suppressed.first, Suppressed.second);
232 
233       // Clear out the list of suppressed diagnostics, so that we don't emit
234       // them again for this specialization. However, we don't obsolete this
235       // entry from the table, because we want to avoid ever emitting these
236       // diagnostics again.
237       Pos->second.clear();
238     }
239 
240     // C++ [basic.start.main]p3:
241     //   The function 'main' shall not be used within a program.
242     if (cast<FunctionDecl>(D)->isMain())
243       Diag(Loc, diag::ext_main_used);
244 
245     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
246   }
247 
248   // See if this is an auto-typed variable whose initializer we are parsing.
249   if (ParsingInitForAutoVars.count(D)) {
250     if (isa<BindingDecl>(D)) {
251       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
252         << D->getDeclName();
253     } else {
254       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
255         << D->getDeclName() << cast<VarDecl>(D)->getType();
256     }
257     return true;
258   }
259 
260   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
261     // See if this is a deleted function.
262     if (FD->isDeleted()) {
263       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
264       if (Ctor && Ctor->isInheritingConstructor())
265         Diag(Loc, diag::err_deleted_inherited_ctor_use)
266             << Ctor->getParent()
267             << Ctor->getInheritedConstructor().getConstructor()->getParent();
268       else
269         Diag(Loc, diag::err_deleted_function_use);
270       NoteDeletedFunction(FD);
271       return true;
272     }
273 
274     // [expr.prim.id]p4
275     //   A program that refers explicitly or implicitly to a function with a
276     //   trailing requires-clause whose constraint-expression is not satisfied,
277     //   other than to declare it, is ill-formed. [...]
278     //
279     // See if this is a function with constraints that need to be satisfied.
280     // Check this before deducing the return type, as it might instantiate the
281     // definition.
282     if (FD->getTrailingRequiresClause()) {
283       ConstraintSatisfaction Satisfaction;
284       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
285         // A diagnostic will have already been generated (non-constant
286         // constraint expression, for example)
287         return true;
288       if (!Satisfaction.IsSatisfied) {
289         Diag(Loc,
290              diag::err_reference_to_function_with_unsatisfied_constraints)
291             << D;
292         DiagnoseUnsatisfiedConstraint(Satisfaction);
293         return true;
294       }
295     }
296 
297     // If the function has a deduced return type, and we can't deduce it,
298     // then we can't use it either.
299     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
300         DeduceReturnType(FD, Loc))
301       return true;
302 
303     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
304       return true;
305 
306     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
307       return true;
308   }
309 
310   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
311     // Lambdas are only default-constructible or assignable in C++2a onwards.
312     if (MD->getParent()->isLambda() &&
313         ((isa<CXXConstructorDecl>(MD) &&
314           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
315          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
316       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
317         << !isa<CXXConstructorDecl>(MD);
318     }
319   }
320 
321   auto getReferencedObjCProp = [](const NamedDecl *D) ->
322                                       const ObjCPropertyDecl * {
323     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
324       return MD->findPropertyDecl();
325     return nullptr;
326   };
327   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
328     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
329       return true;
330   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
331       return true;
332   }
333 
334   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
335   // Only the variables omp_in and omp_out are allowed in the combiner.
336   // Only the variables omp_priv and omp_orig are allowed in the
337   // initializer-clause.
338   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
339   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
340       isa<VarDecl>(D)) {
341     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
342         << getCurFunction()->HasOMPDeclareReductionCombiner;
343     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
344     return true;
345   }
346 
347   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
348   //  List-items in map clauses on this construct may only refer to the declared
349   //  variable var and entities that could be referenced by a procedure defined
350   //  at the same location
351   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
352       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
353     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
354         << getOpenMPDeclareMapperVarName();
355     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
356     return true;
357   }
358 
359   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
360     Diag(Loc, diag::err_use_of_empty_using_if_exists);
361     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
362     return true;
363   }
364 
365   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
366                              AvoidPartialAvailabilityChecks, ClassReceiver);
367 
368   DiagnoseUnusedOfDecl(*this, D, Loc);
369 
370   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
371 
372   if (auto *VD = dyn_cast<ValueDecl>(D))
373     checkTypeSupport(VD->getType(), Loc, VD);
374 
375   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
376     if (!Context.getTargetInfo().isTLSSupported())
377       if (const auto *VD = dyn_cast<VarDecl>(D))
378         if (VD->getTLSKind() != VarDecl::TLS_None)
379           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
380   }
381 
382   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
383       !isUnevaluatedContext()) {
384     // C++ [expr.prim.req.nested] p3
385     //   A local parameter shall only appear as an unevaluated operand
386     //   (Clause 8) within the constraint-expression.
387     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
388         << D;
389     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
390     return true;
391   }
392 
393   return false;
394 }
395 
396 /// DiagnoseSentinelCalls - This routine checks whether a call or
397 /// message-send is to a declaration with the sentinel attribute, and
398 /// if so, it checks that the requirements of the sentinel are
399 /// satisfied.
400 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
401                                  ArrayRef<Expr *> Args) {
402   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
403   if (!attr)
404     return;
405 
406   // The number of formal parameters of the declaration.
407   unsigned numFormalParams;
408 
409   // The kind of declaration.  This is also an index into a %select in
410   // the diagnostic.
411   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
412 
413   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
414     numFormalParams = MD->param_size();
415     calleeType = CT_Method;
416   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
417     numFormalParams = FD->param_size();
418     calleeType = CT_Function;
419   } else if (isa<VarDecl>(D)) {
420     QualType type = cast<ValueDecl>(D)->getType();
421     const FunctionType *fn = nullptr;
422     if (const PointerType *ptr = type->getAs<PointerType>()) {
423       fn = ptr->getPointeeType()->getAs<FunctionType>();
424       if (!fn) return;
425       calleeType = CT_Function;
426     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
427       fn = ptr->getPointeeType()->castAs<FunctionType>();
428       calleeType = CT_Block;
429     } else {
430       return;
431     }
432 
433     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
434       numFormalParams = proto->getNumParams();
435     } else {
436       numFormalParams = 0;
437     }
438   } else {
439     return;
440   }
441 
442   // "nullPos" is the number of formal parameters at the end which
443   // effectively count as part of the variadic arguments.  This is
444   // useful if you would prefer to not have *any* formal parameters,
445   // but the language forces you to have at least one.
446   unsigned nullPos = attr->getNullPos();
447   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
448   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
449 
450   // The number of arguments which should follow the sentinel.
451   unsigned numArgsAfterSentinel = attr->getSentinel();
452 
453   // If there aren't enough arguments for all the formal parameters,
454   // the sentinel, and the args after the sentinel, complain.
455   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
456     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
457     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
458     return;
459   }
460 
461   // Otherwise, find the sentinel expression.
462   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
463   if (!sentinelExpr) return;
464   if (sentinelExpr->isValueDependent()) return;
465   if (Context.isSentinelNullExpr(sentinelExpr)) return;
466 
467   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
468   // or 'NULL' if those are actually defined in the context.  Only use
469   // 'nil' for ObjC methods, where it's much more likely that the
470   // variadic arguments form a list of object pointers.
471   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
472   std::string NullValue;
473   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
474     NullValue = "nil";
475   else if (getLangOpts().CPlusPlus11)
476     NullValue = "nullptr";
477   else if (PP.isMacroDefined("NULL"))
478     NullValue = "NULL";
479   else
480     NullValue = "(void*) 0";
481 
482   if (MissingNilLoc.isInvalid())
483     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
484   else
485     Diag(MissingNilLoc, diag::warn_missing_sentinel)
486       << int(calleeType)
487       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
488   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
489 }
490 
491 SourceRange Sema::getExprRange(Expr *E) const {
492   return E ? E->getSourceRange() : SourceRange();
493 }
494 
495 //===----------------------------------------------------------------------===//
496 //  Standard Promotions and Conversions
497 //===----------------------------------------------------------------------===//
498 
499 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
500 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
501   // Handle any placeholder expressions which made it here.
502   if (E->hasPlaceholderType()) {
503     ExprResult result = CheckPlaceholderExpr(E);
504     if (result.isInvalid()) return ExprError();
505     E = result.get();
506   }
507 
508   QualType Ty = E->getType();
509   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
510 
511   if (Ty->isFunctionType()) {
512     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
513       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
514         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
515           return ExprError();
516 
517     E = ImpCastExprToType(E, Context.getPointerType(Ty),
518                           CK_FunctionToPointerDecay).get();
519   } else if (Ty->isArrayType()) {
520     // In C90 mode, arrays only promote to pointers if the array expression is
521     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
522     // type 'array of type' is converted to an expression that has type 'pointer
523     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
524     // that has type 'array of type' ...".  The relevant change is "an lvalue"
525     // (C90) to "an expression" (C99).
526     //
527     // C++ 4.2p1:
528     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
529     // T" can be converted to an rvalue of type "pointer to T".
530     //
531     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
532       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
533                                          CK_ArrayToPointerDecay);
534       if (Res.isInvalid())
535         return ExprError();
536       E = Res.get();
537     }
538   }
539   return E;
540 }
541 
542 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
543   // Check to see if we are dereferencing a null pointer.  If so,
544   // and if not volatile-qualified, this is undefined behavior that the
545   // optimizer will delete, so warn about it.  People sometimes try to use this
546   // to get a deterministic trap and are surprised by clang's behavior.  This
547   // only handles the pattern "*null", which is a very syntactic check.
548   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
549   if (UO && UO->getOpcode() == UO_Deref &&
550       UO->getSubExpr()->getType()->isPointerType()) {
551     const LangAS AS =
552         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
553     if ((!isTargetAddressSpace(AS) ||
554          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
555         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
556             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
557         !UO->getType().isVolatileQualified()) {
558       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
559                             S.PDiag(diag::warn_indirection_through_null)
560                                 << UO->getSubExpr()->getSourceRange());
561       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
562                             S.PDiag(diag::note_indirection_through_null));
563     }
564   }
565 }
566 
567 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
568                                     SourceLocation AssignLoc,
569                                     const Expr* RHS) {
570   const ObjCIvarDecl *IV = OIRE->getDecl();
571   if (!IV)
572     return;
573 
574   DeclarationName MemberName = IV->getDeclName();
575   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
576   if (!Member || !Member->isStr("isa"))
577     return;
578 
579   const Expr *Base = OIRE->getBase();
580   QualType BaseType = Base->getType();
581   if (OIRE->isArrow())
582     BaseType = BaseType->getPointeeType();
583   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
584     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
585       ObjCInterfaceDecl *ClassDeclared = nullptr;
586       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
587       if (!ClassDeclared->getSuperClass()
588           && (*ClassDeclared->ivar_begin()) == IV) {
589         if (RHS) {
590           NamedDecl *ObjectSetClass =
591             S.LookupSingleName(S.TUScope,
592                                &S.Context.Idents.get("object_setClass"),
593                                SourceLocation(), S.LookupOrdinaryName);
594           if (ObjectSetClass) {
595             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
596             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
597                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
598                                               "object_setClass(")
599                 << FixItHint::CreateReplacement(
600                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
601                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
602           }
603           else
604             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
605         } else {
606           NamedDecl *ObjectGetClass =
607             S.LookupSingleName(S.TUScope,
608                                &S.Context.Idents.get("object_getClass"),
609                                SourceLocation(), S.LookupOrdinaryName);
610           if (ObjectGetClass)
611             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
612                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
613                                               "object_getClass(")
614                 << FixItHint::CreateReplacement(
615                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
616           else
617             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
618         }
619         S.Diag(IV->getLocation(), diag::note_ivar_decl);
620       }
621     }
622 }
623 
624 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
625   // Handle any placeholder expressions which made it here.
626   if (E->hasPlaceholderType()) {
627     ExprResult result = CheckPlaceholderExpr(E);
628     if (result.isInvalid()) return ExprError();
629     E = result.get();
630   }
631 
632   // C++ [conv.lval]p1:
633   //   A glvalue of a non-function, non-array type T can be
634   //   converted to a prvalue.
635   if (!E->isGLValue()) return E;
636 
637   QualType T = E->getType();
638   assert(!T.isNull() && "r-value conversion on typeless expression?");
639 
640   // lvalue-to-rvalue conversion cannot be applied to function or array types.
641   if (T->isFunctionType() || T->isArrayType())
642     return E;
643 
644   // We don't want to throw lvalue-to-rvalue casts on top of
645   // expressions of certain types in C++.
646   if (getLangOpts().CPlusPlus &&
647       (E->getType() == Context.OverloadTy ||
648        T->isDependentType() ||
649        T->isRecordType()))
650     return E;
651 
652   // The C standard is actually really unclear on this point, and
653   // DR106 tells us what the result should be but not why.  It's
654   // generally best to say that void types just doesn't undergo
655   // lvalue-to-rvalue at all.  Note that expressions of unqualified
656   // 'void' type are never l-values, but qualified void can be.
657   if (T->isVoidType())
658     return E;
659 
660   // OpenCL usually rejects direct accesses to values of 'half' type.
661   if (getLangOpts().OpenCL &&
662       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
663       T->isHalfType()) {
664     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
665       << 0 << T;
666     return ExprError();
667   }
668 
669   CheckForNullPointerDereference(*this, E);
670   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
671     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
672                                      &Context.Idents.get("object_getClass"),
673                                      SourceLocation(), LookupOrdinaryName);
674     if (ObjectGetClass)
675       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
676           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
677           << FixItHint::CreateReplacement(
678                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
679     else
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
681   }
682   else if (const ObjCIvarRefExpr *OIRE =
683             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
684     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
685 
686   // C++ [conv.lval]p1:
687   //   [...] If T is a non-class type, the type of the prvalue is the
688   //   cv-unqualified version of T. Otherwise, the type of the
689   //   rvalue is T.
690   //
691   // C99 6.3.2.1p2:
692   //   If the lvalue has qualified type, the value has the unqualified
693   //   version of the type of the lvalue; otherwise, the value has the
694   //   type of the lvalue.
695   if (T.hasQualifiers())
696     T = T.getUnqualifiedType();
697 
698   // Under the MS ABI, lock down the inheritance model now.
699   if (T->isMemberPointerType() &&
700       Context.getTargetInfo().getCXXABI().isMicrosoft())
701     (void)isCompleteType(E->getExprLoc(), T);
702 
703   ExprResult Res = CheckLValueToRValueConversionOperand(E);
704   if (Res.isInvalid())
705     return Res;
706   E = Res.get();
707 
708   // Loading a __weak object implicitly retains the value, so we need a cleanup to
709   // balance that.
710   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711     Cleanup.setExprNeedsCleanups(true);
712 
713   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
714     Cleanup.setExprNeedsCleanups(true);
715 
716   // C++ [conv.lval]p3:
717   //   If T is cv std::nullptr_t, the result is a null pointer constant.
718   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
719   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
720                                  CurFPFeatureOverrides());
721 
722   // C11 6.3.2.1p2:
723   //   ... if the lvalue has atomic type, the value has the non-atomic version
724   //   of the type of the lvalue ...
725   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
726     T = Atomic->getValueType().getUnqualifiedType();
727     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
728                                    nullptr, VK_PRValue, FPOptionsOverride());
729   }
730 
731   return Res;
732 }
733 
734 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
735   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
736   if (Res.isInvalid())
737     return ExprError();
738   Res = DefaultLvalueConversion(Res.get());
739   if (Res.isInvalid())
740     return ExprError();
741   return Res;
742 }
743 
744 /// CallExprUnaryConversions - a special case of an unary conversion
745 /// performed on a function designator of a call expression.
746 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
747   QualType Ty = E->getType();
748   ExprResult Res = E;
749   // Only do implicit cast for a function type, but not for a pointer
750   // to function type.
751   if (Ty->isFunctionType()) {
752     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
753                             CK_FunctionToPointerDecay);
754     if (Res.isInvalid())
755       return ExprError();
756   }
757   Res = DefaultLvalueConversion(Res.get());
758   if (Res.isInvalid())
759     return ExprError();
760   return Res.get();
761 }
762 
763 /// UsualUnaryConversions - Performs various conversions that are common to most
764 /// operators (C99 6.3). The conversions of array and function types are
765 /// sometimes suppressed. For example, the array->pointer conversion doesn't
766 /// apply if the array is an argument to the sizeof or address (&) operators.
767 /// In these instances, this routine should *not* be called.
768 ExprResult Sema::UsualUnaryConversions(Expr *E) {
769   // First, convert to an r-value.
770   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
771   if (Res.isInvalid())
772     return ExprError();
773   E = Res.get();
774 
775   QualType Ty = E->getType();
776   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
777 
778   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
779   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
780       (getLangOpts().getFPEvalMethod() !=
781            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
782        PP.getLastFPEvalPragmaLocation().isValid())) {
783     switch (EvalMethod) {
784     default:
785       llvm_unreachable("Unrecognized float evaluation method");
786       break;
787     case LangOptions::FEM_UnsetOnCommandLine:
788       llvm_unreachable("Float evaluation method should be set by now");
789       break;
790     case LangOptions::FEM_Double:
791       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
792         // Widen the expression to double.
793         return Ty->isComplexType()
794                    ? ImpCastExprToType(E,
795                                        Context.getComplexType(Context.DoubleTy),
796                                        CK_FloatingComplexCast)
797                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
798       break;
799     case LangOptions::FEM_Extended:
800       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
801         // Widen the expression to long double.
802         return Ty->isComplexType()
803                    ? ImpCastExprToType(
804                          E, Context.getComplexType(Context.LongDoubleTy),
805                          CK_FloatingComplexCast)
806                    : ImpCastExprToType(E, Context.LongDoubleTy,
807                                        CK_FloatingCast);
808       break;
809     }
810   }
811 
812   // Half FP have to be promoted to float unless it is natively supported
813   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
814     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
815 
816   // Try to perform integral promotions if the object has a theoretically
817   // promotable type.
818   if (Ty->isIntegralOrUnscopedEnumerationType()) {
819     // C99 6.3.1.1p2:
820     //
821     //   The following may be used in an expression wherever an int or
822     //   unsigned int may be used:
823     //     - an object or expression with an integer type whose integer
824     //       conversion rank is less than or equal to the rank of int
825     //       and unsigned int.
826     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
827     //
828     //   If an int can represent all values of the original type, the
829     //   value is converted to an int; otherwise, it is converted to an
830     //   unsigned int. These are called the integer promotions. All
831     //   other types are unchanged by the integer promotions.
832 
833     QualType PTy = Context.isPromotableBitField(E);
834     if (!PTy.isNull()) {
835       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
836       return E;
837     }
838     if (Ty->isPromotableIntegerType()) {
839       QualType PT = Context.getPromotedIntegerType(Ty);
840       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
841       return E;
842     }
843   }
844   return E;
845 }
846 
847 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
848 /// do not have a prototype. Arguments that have type float or __fp16
849 /// are promoted to double. All other argument types are converted by
850 /// UsualUnaryConversions().
851 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
852   QualType Ty = E->getType();
853   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
854 
855   ExprResult Res = UsualUnaryConversions(E);
856   if (Res.isInvalid())
857     return ExprError();
858   E = Res.get();
859 
860   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
861   // promote to double.
862   // Note that default argument promotion applies only to float (and
863   // half/fp16); it does not apply to _Float16.
864   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
865   if (BTy && (BTy->getKind() == BuiltinType::Half ||
866               BTy->getKind() == BuiltinType::Float)) {
867     if (getLangOpts().OpenCL &&
868         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
869       if (BTy->getKind() == BuiltinType::Half) {
870         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
871       }
872     } else {
873       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
874     }
875   }
876   if (BTy &&
877       getLangOpts().getExtendIntArgs() ==
878           LangOptions::ExtendArgsKind::ExtendTo64 &&
879       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
880       Context.getTypeSizeInChars(BTy) <
881           Context.getTypeSizeInChars(Context.LongLongTy)) {
882     E = (Ty->isUnsignedIntegerType())
883             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
884                   .get()
885             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
886     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
887            "Unexpected typesize for LongLongTy");
888   }
889 
890   // C++ performs lvalue-to-rvalue conversion as a default argument
891   // promotion, even on class types, but note:
892   //   C++11 [conv.lval]p2:
893   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
894   //     operand or a subexpression thereof the value contained in the
895   //     referenced object is not accessed. Otherwise, if the glvalue
896   //     has a class type, the conversion copy-initializes a temporary
897   //     of type T from the glvalue and the result of the conversion
898   //     is a prvalue for the temporary.
899   // FIXME: add some way to gate this entire thing for correctness in
900   // potentially potentially evaluated contexts.
901   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
902     ExprResult Temp = PerformCopyInitialization(
903                        InitializedEntity::InitializeTemporary(E->getType()),
904                                                 E->getExprLoc(), E);
905     if (Temp.isInvalid())
906       return ExprError();
907     E = Temp.get();
908   }
909 
910   return E;
911 }
912 
913 /// Determine the degree of POD-ness for an expression.
914 /// Incomplete types are considered POD, since this check can be performed
915 /// when we're in an unevaluated context.
916 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
917   if (Ty->isIncompleteType()) {
918     // C++11 [expr.call]p7:
919     //   After these conversions, if the argument does not have arithmetic,
920     //   enumeration, pointer, pointer to member, or class type, the program
921     //   is ill-formed.
922     //
923     // Since we've already performed array-to-pointer and function-to-pointer
924     // decay, the only such type in C++ is cv void. This also handles
925     // initializer lists as variadic arguments.
926     if (Ty->isVoidType())
927       return VAK_Invalid;
928 
929     if (Ty->isObjCObjectType())
930       return VAK_Invalid;
931     return VAK_Valid;
932   }
933 
934   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
935     return VAK_Invalid;
936 
937   if (Ty.isCXX98PODType(Context))
938     return VAK_Valid;
939 
940   // C++11 [expr.call]p7:
941   //   Passing a potentially-evaluated argument of class type (Clause 9)
942   //   having a non-trivial copy constructor, a non-trivial move constructor,
943   //   or a non-trivial destructor, with no corresponding parameter,
944   //   is conditionally-supported with implementation-defined semantics.
945   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
946     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
947       if (!Record->hasNonTrivialCopyConstructor() &&
948           !Record->hasNonTrivialMoveConstructor() &&
949           !Record->hasNonTrivialDestructor())
950         return VAK_ValidInCXX11;
951 
952   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
953     return VAK_Valid;
954 
955   if (Ty->isObjCObjectType())
956     return VAK_Invalid;
957 
958   if (getLangOpts().MSVCCompat)
959     return VAK_MSVCUndefined;
960 
961   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
962   // permitted to reject them. We should consider doing so.
963   return VAK_Undefined;
964 }
965 
966 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
967   // Don't allow one to pass an Objective-C interface to a vararg.
968   const QualType &Ty = E->getType();
969   VarArgKind VAK = isValidVarArgType(Ty);
970 
971   // Complain about passing non-POD types through varargs.
972   switch (VAK) {
973   case VAK_ValidInCXX11:
974     DiagRuntimeBehavior(
975         E->getBeginLoc(), nullptr,
976         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
977     LLVM_FALLTHROUGH;
978   case VAK_Valid:
979     if (Ty->isRecordType()) {
980       // This is unlikely to be what the user intended. If the class has a
981       // 'c_str' member function, the user probably meant to call that.
982       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
983                           PDiag(diag::warn_pass_class_arg_to_vararg)
984                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
985     }
986     break;
987 
988   case VAK_Undefined:
989   case VAK_MSVCUndefined:
990     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
991                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
992                             << getLangOpts().CPlusPlus11 << Ty << CT);
993     break;
994 
995   case VAK_Invalid:
996     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
997       Diag(E->getBeginLoc(),
998            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
999           << Ty << CT;
1000     else if (Ty->isObjCObjectType())
1001       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1002                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1003                               << Ty << CT);
1004     else
1005       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1006           << isa<InitListExpr>(E) << Ty << CT;
1007     break;
1008   }
1009 }
1010 
1011 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1012 /// will create a trap if the resulting type is not a POD type.
1013 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1014                                                   FunctionDecl *FDecl) {
1015   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1016     // Strip the unbridged-cast placeholder expression off, if applicable.
1017     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1018         (CT == VariadicMethod ||
1019          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1020       E = stripARCUnbridgedCast(E);
1021 
1022     // Otherwise, do normal placeholder checking.
1023     } else {
1024       ExprResult ExprRes = CheckPlaceholderExpr(E);
1025       if (ExprRes.isInvalid())
1026         return ExprError();
1027       E = ExprRes.get();
1028     }
1029   }
1030 
1031   ExprResult ExprRes = DefaultArgumentPromotion(E);
1032   if (ExprRes.isInvalid())
1033     return ExprError();
1034 
1035   // Copy blocks to the heap.
1036   if (ExprRes.get()->getType()->isBlockPointerType())
1037     maybeExtendBlockObject(ExprRes);
1038 
1039   E = ExprRes.get();
1040 
1041   // Diagnostics regarding non-POD argument types are
1042   // emitted along with format string checking in Sema::CheckFunctionCall().
1043   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1044     // Turn this into a trap.
1045     CXXScopeSpec SS;
1046     SourceLocation TemplateKWLoc;
1047     UnqualifiedId Name;
1048     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1049                        E->getBeginLoc());
1050     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1051                                           /*HasTrailingLParen=*/true,
1052                                           /*IsAddressOfOperand=*/false);
1053     if (TrapFn.isInvalid())
1054       return ExprError();
1055 
1056     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1057                                     None, E->getEndLoc());
1058     if (Call.isInvalid())
1059       return ExprError();
1060 
1061     ExprResult Comma =
1062         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1063     if (Comma.isInvalid())
1064       return ExprError();
1065     return Comma.get();
1066   }
1067 
1068   if (!getLangOpts().CPlusPlus &&
1069       RequireCompleteType(E->getExprLoc(), E->getType(),
1070                           diag::err_call_incomplete_argument))
1071     return ExprError();
1072 
1073   return E;
1074 }
1075 
1076 /// Converts an integer to complex float type.  Helper function of
1077 /// UsualArithmeticConversions()
1078 ///
1079 /// \return false if the integer expression is an integer type and is
1080 /// successfully converted to the complex type.
1081 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1082                                                   ExprResult &ComplexExpr,
1083                                                   QualType IntTy,
1084                                                   QualType ComplexTy,
1085                                                   bool SkipCast) {
1086   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1087   if (SkipCast) return false;
1088   if (IntTy->isIntegerType()) {
1089     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1090     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1091     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1092                                   CK_FloatingRealToComplex);
1093   } else {
1094     assert(IntTy->isComplexIntegerType());
1095     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1096                                   CK_IntegralComplexToFloatingComplex);
1097   }
1098   return false;
1099 }
1100 
1101 /// Handle arithmetic conversion with complex types.  Helper function of
1102 /// UsualArithmeticConversions()
1103 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1104                                              ExprResult &RHS, QualType LHSType,
1105                                              QualType RHSType,
1106                                              bool IsCompAssign) {
1107   // if we have an integer operand, the result is the complex type.
1108   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1109                                              /*skipCast*/false))
1110     return LHSType;
1111   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1112                                              /*skipCast*/IsCompAssign))
1113     return RHSType;
1114 
1115   // This handles complex/complex, complex/float, or float/complex.
1116   // When both operands are complex, the shorter operand is converted to the
1117   // type of the longer, and that is the type of the result. This corresponds
1118   // to what is done when combining two real floating-point operands.
1119   // The fun begins when size promotion occur across type domains.
1120   // From H&S 6.3.4: When one operand is complex and the other is a real
1121   // floating-point type, the less precise type is converted, within it's
1122   // real or complex domain, to the precision of the other type. For example,
1123   // when combining a "long double" with a "double _Complex", the
1124   // "double _Complex" is promoted to "long double _Complex".
1125 
1126   // Compute the rank of the two types, regardless of whether they are complex.
1127   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1128 
1129   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1130   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1131   QualType LHSElementType =
1132       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1133   QualType RHSElementType =
1134       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1135 
1136   QualType ResultType = S.Context.getComplexType(LHSElementType);
1137   if (Order < 0) {
1138     // Promote the precision of the LHS if not an assignment.
1139     ResultType = S.Context.getComplexType(RHSElementType);
1140     if (!IsCompAssign) {
1141       if (LHSComplexType)
1142         LHS =
1143             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1144       else
1145         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1146     }
1147   } else if (Order > 0) {
1148     // Promote the precision of the RHS.
1149     if (RHSComplexType)
1150       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1151     else
1152       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1153   }
1154   return ResultType;
1155 }
1156 
1157 /// Handle arithmetic conversion from integer to float.  Helper function
1158 /// of UsualArithmeticConversions()
1159 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1160                                            ExprResult &IntExpr,
1161                                            QualType FloatTy, QualType IntTy,
1162                                            bool ConvertFloat, bool ConvertInt) {
1163   if (IntTy->isIntegerType()) {
1164     if (ConvertInt)
1165       // Convert intExpr to the lhs floating point type.
1166       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1167                                     CK_IntegralToFloating);
1168     return FloatTy;
1169   }
1170 
1171   // Convert both sides to the appropriate complex float.
1172   assert(IntTy->isComplexIntegerType());
1173   QualType result = S.Context.getComplexType(FloatTy);
1174 
1175   // _Complex int -> _Complex float
1176   if (ConvertInt)
1177     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1178                                   CK_IntegralComplexToFloatingComplex);
1179 
1180   // float -> _Complex float
1181   if (ConvertFloat)
1182     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1183                                     CK_FloatingRealToComplex);
1184 
1185   return result;
1186 }
1187 
1188 /// Handle arithmethic conversion with floating point types.  Helper
1189 /// function of UsualArithmeticConversions()
1190 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1191                                       ExprResult &RHS, QualType LHSType,
1192                                       QualType RHSType, bool IsCompAssign) {
1193   bool LHSFloat = LHSType->isRealFloatingType();
1194   bool RHSFloat = RHSType->isRealFloatingType();
1195 
1196   // N1169 4.1.4: If one of the operands has a floating type and the other
1197   //              operand has a fixed-point type, the fixed-point operand
1198   //              is converted to the floating type [...]
1199   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1200     if (LHSFloat)
1201       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1202     else if (!IsCompAssign)
1203       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1204     return LHSFloat ? LHSType : RHSType;
1205   }
1206 
1207   // If we have two real floating types, convert the smaller operand
1208   // to the bigger result.
1209   if (LHSFloat && RHSFloat) {
1210     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1211     if (order > 0) {
1212       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1213       return LHSType;
1214     }
1215 
1216     assert(order < 0 && "illegal float comparison");
1217     if (!IsCompAssign)
1218       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1219     return RHSType;
1220   }
1221 
1222   if (LHSFloat) {
1223     // Half FP has to be promoted to float unless it is natively supported
1224     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1225       LHSType = S.Context.FloatTy;
1226 
1227     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1228                                       /*ConvertFloat=*/!IsCompAssign,
1229                                       /*ConvertInt=*/ true);
1230   }
1231   assert(RHSFloat);
1232   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1233                                     /*ConvertFloat=*/ true,
1234                                     /*ConvertInt=*/!IsCompAssign);
1235 }
1236 
1237 /// Diagnose attempts to convert between __float128, __ibm128 and
1238 /// long double if there is no support for such conversion.
1239 /// Helper function of UsualArithmeticConversions().
1240 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1241                                       QualType RHSType) {
1242   // No issue if either is not a floating point type.
1243   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1244     return false;
1245 
1246   // No issue if both have the same 128-bit float semantics.
1247   auto *LHSComplex = LHSType->getAs<ComplexType>();
1248   auto *RHSComplex = RHSType->getAs<ComplexType>();
1249 
1250   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1251   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1252 
1253   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1254   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1255 
1256   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1257        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1258       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1259        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1260     return false;
1261 
1262   return true;
1263 }
1264 
1265 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1266 
1267 namespace {
1268 /// These helper callbacks are placed in an anonymous namespace to
1269 /// permit their use as function template parameters.
1270 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1271   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1272 }
1273 
1274 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1275   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1276                              CK_IntegralComplexCast);
1277 }
1278 }
1279 
1280 /// Handle integer arithmetic conversions.  Helper function of
1281 /// UsualArithmeticConversions()
1282 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1283 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1284                                         ExprResult &RHS, QualType LHSType,
1285                                         QualType RHSType, bool IsCompAssign) {
1286   // The rules for this case are in C99 6.3.1.8
1287   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1288   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1289   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1290   if (LHSSigned == RHSSigned) {
1291     // Same signedness; use the higher-ranked type
1292     if (order >= 0) {
1293       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1294       return LHSType;
1295     } else if (!IsCompAssign)
1296       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1297     return RHSType;
1298   } else if (order != (LHSSigned ? 1 : -1)) {
1299     // The unsigned type has greater than or equal rank to the
1300     // signed type, so use the unsigned type
1301     if (RHSSigned) {
1302       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303       return LHSType;
1304     } else if (!IsCompAssign)
1305       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306     return RHSType;
1307   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1308     // The two types are different widths; if we are here, that
1309     // means the signed type is larger than the unsigned type, so
1310     // use the signed type.
1311     if (LHSSigned) {
1312       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1313       return LHSType;
1314     } else if (!IsCompAssign)
1315       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1316     return RHSType;
1317   } else {
1318     // The signed type is higher-ranked than the unsigned type,
1319     // but isn't actually any bigger (like unsigned int and long
1320     // on most 32-bit systems).  Use the unsigned type corresponding
1321     // to the signed type.
1322     QualType result =
1323       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1324     RHS = (*doRHSCast)(S, RHS.get(), result);
1325     if (!IsCompAssign)
1326       LHS = (*doLHSCast)(S, LHS.get(), result);
1327     return result;
1328   }
1329 }
1330 
1331 /// Handle conversions with GCC complex int extension.  Helper function
1332 /// of UsualArithmeticConversions()
1333 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1334                                            ExprResult &RHS, QualType LHSType,
1335                                            QualType RHSType,
1336                                            bool IsCompAssign) {
1337   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1338   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1339 
1340   if (LHSComplexInt && RHSComplexInt) {
1341     QualType LHSEltType = LHSComplexInt->getElementType();
1342     QualType RHSEltType = RHSComplexInt->getElementType();
1343     QualType ScalarType =
1344       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1345         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1346 
1347     return S.Context.getComplexType(ScalarType);
1348   }
1349 
1350   if (LHSComplexInt) {
1351     QualType LHSEltType = LHSComplexInt->getElementType();
1352     QualType ScalarType =
1353       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1354         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1355     QualType ComplexType = S.Context.getComplexType(ScalarType);
1356     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1357                               CK_IntegralRealToComplex);
1358 
1359     return ComplexType;
1360   }
1361 
1362   assert(RHSComplexInt);
1363 
1364   QualType RHSEltType = RHSComplexInt->getElementType();
1365   QualType ScalarType =
1366     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1367       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1368   QualType ComplexType = S.Context.getComplexType(ScalarType);
1369 
1370   if (!IsCompAssign)
1371     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1372                               CK_IntegralRealToComplex);
1373   return ComplexType;
1374 }
1375 
1376 /// Return the rank of a given fixed point or integer type. The value itself
1377 /// doesn't matter, but the values must be increasing with proper increasing
1378 /// rank as described in N1169 4.1.1.
1379 static unsigned GetFixedPointRank(QualType Ty) {
1380   const auto *BTy = Ty->getAs<BuiltinType>();
1381   assert(BTy && "Expected a builtin type.");
1382 
1383   switch (BTy->getKind()) {
1384   case BuiltinType::ShortFract:
1385   case BuiltinType::UShortFract:
1386   case BuiltinType::SatShortFract:
1387   case BuiltinType::SatUShortFract:
1388     return 1;
1389   case BuiltinType::Fract:
1390   case BuiltinType::UFract:
1391   case BuiltinType::SatFract:
1392   case BuiltinType::SatUFract:
1393     return 2;
1394   case BuiltinType::LongFract:
1395   case BuiltinType::ULongFract:
1396   case BuiltinType::SatLongFract:
1397   case BuiltinType::SatULongFract:
1398     return 3;
1399   case BuiltinType::ShortAccum:
1400   case BuiltinType::UShortAccum:
1401   case BuiltinType::SatShortAccum:
1402   case BuiltinType::SatUShortAccum:
1403     return 4;
1404   case BuiltinType::Accum:
1405   case BuiltinType::UAccum:
1406   case BuiltinType::SatAccum:
1407   case BuiltinType::SatUAccum:
1408     return 5;
1409   case BuiltinType::LongAccum:
1410   case BuiltinType::ULongAccum:
1411   case BuiltinType::SatLongAccum:
1412   case BuiltinType::SatULongAccum:
1413     return 6;
1414   default:
1415     if (BTy->isInteger())
1416       return 0;
1417     llvm_unreachable("Unexpected fixed point or integer type");
1418   }
1419 }
1420 
1421 /// handleFixedPointConversion - Fixed point operations between fixed
1422 /// point types and integers or other fixed point types do not fall under
1423 /// usual arithmetic conversion since these conversions could result in loss
1424 /// of precsision (N1169 4.1.4). These operations should be calculated with
1425 /// the full precision of their result type (N1169 4.1.6.2.1).
1426 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1427                                            QualType RHSTy) {
1428   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1429          "Expected at least one of the operands to be a fixed point type");
1430   assert((LHSTy->isFixedPointOrIntegerType() ||
1431           RHSTy->isFixedPointOrIntegerType()) &&
1432          "Special fixed point arithmetic operation conversions are only "
1433          "applied to ints or other fixed point types");
1434 
1435   // If one operand has signed fixed-point type and the other operand has
1436   // unsigned fixed-point type, then the unsigned fixed-point operand is
1437   // converted to its corresponding signed fixed-point type and the resulting
1438   // type is the type of the converted operand.
1439   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1440     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1441   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1442     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1443 
1444   // The result type is the type with the highest rank, whereby a fixed-point
1445   // conversion rank is always greater than an integer conversion rank; if the
1446   // type of either of the operands is a saturating fixedpoint type, the result
1447   // type shall be the saturating fixed-point type corresponding to the type
1448   // with the highest rank; the resulting value is converted (taking into
1449   // account rounding and overflow) to the precision of the resulting type.
1450   // Same ranks between signed and unsigned types are resolved earlier, so both
1451   // types are either signed or both unsigned at this point.
1452   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1453   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1454 
1455   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1456 
1457   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1458     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1459 
1460   return ResultTy;
1461 }
1462 
1463 /// Check that the usual arithmetic conversions can be performed on this pair of
1464 /// expressions that might be of enumeration type.
1465 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1466                                            SourceLocation Loc,
1467                                            Sema::ArithConvKind ACK) {
1468   // C++2a [expr.arith.conv]p1:
1469   //   If one operand is of enumeration type and the other operand is of a
1470   //   different enumeration type or a floating-point type, this behavior is
1471   //   deprecated ([depr.arith.conv.enum]).
1472   //
1473   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1474   // Eventually we will presumably reject these cases (in C++23 onwards?).
1475   QualType L = LHS->getType(), R = RHS->getType();
1476   bool LEnum = L->isUnscopedEnumerationType(),
1477        REnum = R->isUnscopedEnumerationType();
1478   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1479   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1480       (REnum && L->isFloatingType())) {
1481     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1482                     ? diag::warn_arith_conv_enum_float_cxx20
1483                     : diag::warn_arith_conv_enum_float)
1484         << LHS->getSourceRange() << RHS->getSourceRange()
1485         << (int)ACK << LEnum << L << R;
1486   } else if (!IsCompAssign && LEnum && REnum &&
1487              !S.Context.hasSameUnqualifiedType(L, R)) {
1488     unsigned DiagID;
1489     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1490         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1491       // If either enumeration type is unnamed, it's less likely that the
1492       // user cares about this, but this situation is still deprecated in
1493       // C++2a. Use a different warning group.
1494       DiagID = S.getLangOpts().CPlusPlus20
1495                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1496                     : diag::warn_arith_conv_mixed_anon_enum_types;
1497     } else if (ACK == Sema::ACK_Conditional) {
1498       // Conditional expressions are separated out because they have
1499       // historically had a different warning flag.
1500       DiagID = S.getLangOpts().CPlusPlus20
1501                    ? diag::warn_conditional_mixed_enum_types_cxx20
1502                    : diag::warn_conditional_mixed_enum_types;
1503     } else if (ACK == Sema::ACK_Comparison) {
1504       // Comparison expressions are separated out because they have
1505       // historically had a different warning flag.
1506       DiagID = S.getLangOpts().CPlusPlus20
1507                    ? diag::warn_comparison_mixed_enum_types_cxx20
1508                    : diag::warn_comparison_mixed_enum_types;
1509     } else {
1510       DiagID = S.getLangOpts().CPlusPlus20
1511                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1512                    : diag::warn_arith_conv_mixed_enum_types;
1513     }
1514     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1515                         << (int)ACK << L << R;
1516   }
1517 }
1518 
1519 /// UsualArithmeticConversions - Performs various conversions that are common to
1520 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1521 /// routine returns the first non-arithmetic type found. The client is
1522 /// responsible for emitting appropriate error diagnostics.
1523 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1524                                           SourceLocation Loc,
1525                                           ArithConvKind ACK) {
1526   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1527 
1528   if (ACK != ACK_CompAssign) {
1529     LHS = UsualUnaryConversions(LHS.get());
1530     if (LHS.isInvalid())
1531       return QualType();
1532   }
1533 
1534   RHS = UsualUnaryConversions(RHS.get());
1535   if (RHS.isInvalid())
1536     return QualType();
1537 
1538   // For conversion purposes, we ignore any qualifiers.
1539   // For example, "const float" and "float" are equivalent.
1540   QualType LHSType =
1541     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1542   QualType RHSType =
1543     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1544 
1545   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1546   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1547     LHSType = AtomicLHS->getValueType();
1548 
1549   // If both types are identical, no conversion is needed.
1550   if (LHSType == RHSType)
1551     return LHSType;
1552 
1553   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1554   // The caller can deal with this (e.g. pointer + int).
1555   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1556     return QualType();
1557 
1558   // Apply unary and bitfield promotions to the LHS's type.
1559   QualType LHSUnpromotedType = LHSType;
1560   if (LHSType->isPromotableIntegerType())
1561     LHSType = Context.getPromotedIntegerType(LHSType);
1562   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1563   if (!LHSBitfieldPromoteTy.isNull())
1564     LHSType = LHSBitfieldPromoteTy;
1565   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1566     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1567 
1568   // If both types are identical, no conversion is needed.
1569   if (LHSType == RHSType)
1570     return LHSType;
1571 
1572   // At this point, we have two different arithmetic types.
1573 
1574   // Diagnose attempts to convert between __ibm128, __float128 and long double
1575   // where such conversions currently can't be handled.
1576   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1577     return QualType();
1578 
1579   // Handle complex types first (C99 6.3.1.8p1).
1580   if (LHSType->isComplexType() || RHSType->isComplexType())
1581     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1582                                         ACK == ACK_CompAssign);
1583 
1584   // Now handle "real" floating types (i.e. float, double, long double).
1585   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1586     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1587                                  ACK == ACK_CompAssign);
1588 
1589   // Handle GCC complex int extension.
1590   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1591     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1592                                       ACK == ACK_CompAssign);
1593 
1594   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1595     return handleFixedPointConversion(*this, LHSType, RHSType);
1596 
1597   // Finally, we have two differing integer types.
1598   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1599            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1600 }
1601 
1602 //===----------------------------------------------------------------------===//
1603 //  Semantic Analysis for various Expression Types
1604 //===----------------------------------------------------------------------===//
1605 
1606 
1607 ExprResult
1608 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1609                                 SourceLocation DefaultLoc,
1610                                 SourceLocation RParenLoc,
1611                                 Expr *ControllingExpr,
1612                                 ArrayRef<ParsedType> ArgTypes,
1613                                 ArrayRef<Expr *> ArgExprs) {
1614   unsigned NumAssocs = ArgTypes.size();
1615   assert(NumAssocs == ArgExprs.size());
1616 
1617   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1618   for (unsigned i = 0; i < NumAssocs; ++i) {
1619     if (ArgTypes[i])
1620       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1621     else
1622       Types[i] = nullptr;
1623   }
1624 
1625   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1626                                              ControllingExpr,
1627                                              llvm::makeArrayRef(Types, NumAssocs),
1628                                              ArgExprs);
1629   delete [] Types;
1630   return ER;
1631 }
1632 
1633 ExprResult
1634 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1635                                  SourceLocation DefaultLoc,
1636                                  SourceLocation RParenLoc,
1637                                  Expr *ControllingExpr,
1638                                  ArrayRef<TypeSourceInfo *> Types,
1639                                  ArrayRef<Expr *> Exprs) {
1640   unsigned NumAssocs = Types.size();
1641   assert(NumAssocs == Exprs.size());
1642 
1643   // Decay and strip qualifiers for the controlling expression type, and handle
1644   // placeholder type replacement. See committee discussion from WG14 DR423.
1645   {
1646     EnterExpressionEvaluationContext Unevaluated(
1647         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1648     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1649     if (R.isInvalid())
1650       return ExprError();
1651     ControllingExpr = R.get();
1652   }
1653 
1654   // The controlling expression is an unevaluated operand, so side effects are
1655   // likely unintended.
1656   if (!inTemplateInstantiation() &&
1657       ControllingExpr->HasSideEffects(Context, false))
1658     Diag(ControllingExpr->getExprLoc(),
1659          diag::warn_side_effects_unevaluated_context);
1660 
1661   bool TypeErrorFound = false,
1662        IsResultDependent = ControllingExpr->isTypeDependent(),
1663        ContainsUnexpandedParameterPack
1664          = ControllingExpr->containsUnexpandedParameterPack();
1665 
1666   for (unsigned i = 0; i < NumAssocs; ++i) {
1667     if (Exprs[i]->containsUnexpandedParameterPack())
1668       ContainsUnexpandedParameterPack = true;
1669 
1670     if (Types[i]) {
1671       if (Types[i]->getType()->containsUnexpandedParameterPack())
1672         ContainsUnexpandedParameterPack = true;
1673 
1674       if (Types[i]->getType()->isDependentType()) {
1675         IsResultDependent = true;
1676       } else {
1677         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1678         // complete object type other than a variably modified type."
1679         unsigned D = 0;
1680         if (Types[i]->getType()->isIncompleteType())
1681           D = diag::err_assoc_type_incomplete;
1682         else if (!Types[i]->getType()->isObjectType())
1683           D = diag::err_assoc_type_nonobject;
1684         else if (Types[i]->getType()->isVariablyModifiedType())
1685           D = diag::err_assoc_type_variably_modified;
1686 
1687         if (D != 0) {
1688           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1689             << Types[i]->getTypeLoc().getSourceRange()
1690             << Types[i]->getType();
1691           TypeErrorFound = true;
1692         }
1693 
1694         // C11 6.5.1.1p2 "No two generic associations in the same generic
1695         // selection shall specify compatible types."
1696         for (unsigned j = i+1; j < NumAssocs; ++j)
1697           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1698               Context.typesAreCompatible(Types[i]->getType(),
1699                                          Types[j]->getType())) {
1700             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1701                  diag::err_assoc_compatible_types)
1702               << Types[j]->getTypeLoc().getSourceRange()
1703               << Types[j]->getType()
1704               << Types[i]->getType();
1705             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1706                  diag::note_compat_assoc)
1707               << Types[i]->getTypeLoc().getSourceRange()
1708               << Types[i]->getType();
1709             TypeErrorFound = true;
1710           }
1711       }
1712     }
1713   }
1714   if (TypeErrorFound)
1715     return ExprError();
1716 
1717   // If we determined that the generic selection is result-dependent, don't
1718   // try to compute the result expression.
1719   if (IsResultDependent)
1720     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1721                                         Exprs, DefaultLoc, RParenLoc,
1722                                         ContainsUnexpandedParameterPack);
1723 
1724   SmallVector<unsigned, 1> CompatIndices;
1725   unsigned DefaultIndex = -1U;
1726   for (unsigned i = 0; i < NumAssocs; ++i) {
1727     if (!Types[i])
1728       DefaultIndex = i;
1729     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1730                                         Types[i]->getType()))
1731       CompatIndices.push_back(i);
1732   }
1733 
1734   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1735   // type compatible with at most one of the types named in its generic
1736   // association list."
1737   if (CompatIndices.size() > 1) {
1738     // We strip parens here because the controlling expression is typically
1739     // parenthesized in macro definitions.
1740     ControllingExpr = ControllingExpr->IgnoreParens();
1741     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1742         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1743         << (unsigned)CompatIndices.size();
1744     for (unsigned I : CompatIndices) {
1745       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1746            diag::note_compat_assoc)
1747         << Types[I]->getTypeLoc().getSourceRange()
1748         << Types[I]->getType();
1749     }
1750     return ExprError();
1751   }
1752 
1753   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1754   // its controlling expression shall have type compatible with exactly one of
1755   // the types named in its generic association list."
1756   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1757     // We strip parens here because the controlling expression is typically
1758     // parenthesized in macro definitions.
1759     ControllingExpr = ControllingExpr->IgnoreParens();
1760     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1761         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1762     return ExprError();
1763   }
1764 
1765   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1766   // type name that is compatible with the type of the controlling expression,
1767   // then the result expression of the generic selection is the expression
1768   // in that generic association. Otherwise, the result expression of the
1769   // generic selection is the expression in the default generic association."
1770   unsigned ResultIndex =
1771     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1772 
1773   return GenericSelectionExpr::Create(
1774       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1775       ContainsUnexpandedParameterPack, ResultIndex);
1776 }
1777 
1778 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1779 /// location of the token and the offset of the ud-suffix within it.
1780 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1781                                      unsigned Offset) {
1782   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1783                                         S.getLangOpts());
1784 }
1785 
1786 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1787 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1788 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1789                                                  IdentifierInfo *UDSuffix,
1790                                                  SourceLocation UDSuffixLoc,
1791                                                  ArrayRef<Expr*> Args,
1792                                                  SourceLocation LitEndLoc) {
1793   assert(Args.size() <= 2 && "too many arguments for literal operator");
1794 
1795   QualType ArgTy[2];
1796   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1797     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1798     if (ArgTy[ArgIdx]->isArrayType())
1799       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1800   }
1801 
1802   DeclarationName OpName =
1803     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1804   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1805   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1806 
1807   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1808   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1809                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1810                               /*AllowStringTemplatePack*/ false,
1811                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1812     return ExprError();
1813 
1814   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1815 }
1816 
1817 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1818 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1819 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1820 /// multiple tokens.  However, the common case is that StringToks points to one
1821 /// string.
1822 ///
1823 ExprResult
1824 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1825   assert(!StringToks.empty() && "Must have at least one string!");
1826 
1827   StringLiteralParser Literal(StringToks, PP);
1828   if (Literal.hadError)
1829     return ExprError();
1830 
1831   SmallVector<SourceLocation, 4> StringTokLocs;
1832   for (const Token &Tok : StringToks)
1833     StringTokLocs.push_back(Tok.getLocation());
1834 
1835   QualType CharTy = Context.CharTy;
1836   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1837   if (Literal.isWide()) {
1838     CharTy = Context.getWideCharType();
1839     Kind = StringLiteral::Wide;
1840   } else if (Literal.isUTF8()) {
1841     if (getLangOpts().Char8)
1842       CharTy = Context.Char8Ty;
1843     Kind = StringLiteral::UTF8;
1844   } else if (Literal.isUTF16()) {
1845     CharTy = Context.Char16Ty;
1846     Kind = StringLiteral::UTF16;
1847   } else if (Literal.isUTF32()) {
1848     CharTy = Context.Char32Ty;
1849     Kind = StringLiteral::UTF32;
1850   } else if (Literal.isPascal()) {
1851     CharTy = Context.UnsignedCharTy;
1852   }
1853 
1854   // Warn on initializing an array of char from a u8 string literal; this
1855   // becomes ill-formed in C++2a.
1856   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1857       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1858     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1859 
1860     // Create removals for all 'u8' prefixes in the string literal(s). This
1861     // ensures C++2a compatibility (but may change the program behavior when
1862     // built by non-Clang compilers for which the execution character set is
1863     // not always UTF-8).
1864     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1865     SourceLocation RemovalDiagLoc;
1866     for (const Token &Tok : StringToks) {
1867       if (Tok.getKind() == tok::utf8_string_literal) {
1868         if (RemovalDiagLoc.isInvalid())
1869           RemovalDiagLoc = Tok.getLocation();
1870         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1871             Tok.getLocation(),
1872             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1873                                            getSourceManager(), getLangOpts())));
1874       }
1875     }
1876     Diag(RemovalDiagLoc, RemovalDiag);
1877   }
1878 
1879   QualType StrTy =
1880       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1881 
1882   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1883   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1884                                              Kind, Literal.Pascal, StrTy,
1885                                              &StringTokLocs[0],
1886                                              StringTokLocs.size());
1887   if (Literal.getUDSuffix().empty())
1888     return Lit;
1889 
1890   // We're building a user-defined literal.
1891   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1892   SourceLocation UDSuffixLoc =
1893     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1894                    Literal.getUDSuffixOffset());
1895 
1896   // Make sure we're allowed user-defined literals here.
1897   if (!UDLScope)
1898     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1899 
1900   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1901   //   operator "" X (str, len)
1902   QualType SizeType = Context.getSizeType();
1903 
1904   DeclarationName OpName =
1905     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1906   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1907   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1908 
1909   QualType ArgTy[] = {
1910     Context.getArrayDecayedType(StrTy), SizeType
1911   };
1912 
1913   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1914   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1915                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1916                                 /*AllowStringTemplatePack*/ true,
1917                                 /*DiagnoseMissing*/ true, Lit)) {
1918 
1919   case LOLR_Cooked: {
1920     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1921     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1922                                                     StringTokLocs[0]);
1923     Expr *Args[] = { Lit, LenArg };
1924 
1925     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1926   }
1927 
1928   case LOLR_Template: {
1929     TemplateArgumentListInfo ExplicitArgs;
1930     TemplateArgument Arg(Lit);
1931     TemplateArgumentLocInfo ArgInfo(Lit);
1932     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1933     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1934                                     &ExplicitArgs);
1935   }
1936 
1937   case LOLR_StringTemplatePack: {
1938     TemplateArgumentListInfo ExplicitArgs;
1939 
1940     unsigned CharBits = Context.getIntWidth(CharTy);
1941     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1942     llvm::APSInt Value(CharBits, CharIsUnsigned);
1943 
1944     TemplateArgument TypeArg(CharTy);
1945     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1946     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1947 
1948     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1949       Value = Lit->getCodeUnit(I);
1950       TemplateArgument Arg(Context, Value, CharTy);
1951       TemplateArgumentLocInfo ArgInfo;
1952       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1953     }
1954     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1955                                     &ExplicitArgs);
1956   }
1957   case LOLR_Raw:
1958   case LOLR_ErrorNoDiagnostic:
1959     llvm_unreachable("unexpected literal operator lookup result");
1960   case LOLR_Error:
1961     return ExprError();
1962   }
1963   llvm_unreachable("unexpected literal operator lookup result");
1964 }
1965 
1966 DeclRefExpr *
1967 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1968                        SourceLocation Loc,
1969                        const CXXScopeSpec *SS) {
1970   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1971   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1972 }
1973 
1974 DeclRefExpr *
1975 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1976                        const DeclarationNameInfo &NameInfo,
1977                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1978                        SourceLocation TemplateKWLoc,
1979                        const TemplateArgumentListInfo *TemplateArgs) {
1980   NestedNameSpecifierLoc NNS =
1981       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1982   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1983                           TemplateArgs);
1984 }
1985 
1986 // CUDA/HIP: Check whether a captured reference variable is referencing a
1987 // host variable in a device or host device lambda.
1988 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1989                                                             VarDecl *VD) {
1990   if (!S.getLangOpts().CUDA || !VD->hasInit())
1991     return false;
1992   assert(VD->getType()->isReferenceType());
1993 
1994   // Check whether the reference variable is referencing a host variable.
1995   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1996   if (!DRE)
1997     return false;
1998   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1999   if (!Referee || !Referee->hasGlobalStorage() ||
2000       Referee->hasAttr<CUDADeviceAttr>())
2001     return false;
2002 
2003   // Check whether the current function is a device or host device lambda.
2004   // Check whether the reference variable is a capture by getDeclContext()
2005   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2006   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2007   if (MD && MD->getParent()->isLambda() &&
2008       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2009       VD->getDeclContext() != MD)
2010     return true;
2011 
2012   return false;
2013 }
2014 
2015 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2016   // A declaration named in an unevaluated operand never constitutes an odr-use.
2017   if (isUnevaluatedContext())
2018     return NOUR_Unevaluated;
2019 
2020   // C++2a [basic.def.odr]p4:
2021   //   A variable x whose name appears as a potentially-evaluated expression e
2022   //   is odr-used by e unless [...] x is a reference that is usable in
2023   //   constant expressions.
2024   // CUDA/HIP:
2025   //   If a reference variable referencing a host variable is captured in a
2026   //   device or host device lambda, the value of the referee must be copied
2027   //   to the capture and the reference variable must be treated as odr-use
2028   //   since the value of the referee is not known at compile time and must
2029   //   be loaded from the captured.
2030   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2031     if (VD->getType()->isReferenceType() &&
2032         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2033         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2034         VD->isUsableInConstantExpressions(Context))
2035       return NOUR_Constant;
2036   }
2037 
2038   // All remaining non-variable cases constitute an odr-use. For variables, we
2039   // need to wait and see how the expression is used.
2040   return NOUR_None;
2041 }
2042 
2043 /// BuildDeclRefExpr - Build an expression that references a
2044 /// declaration that does not require a closure capture.
2045 DeclRefExpr *
2046 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2047                        const DeclarationNameInfo &NameInfo,
2048                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2049                        SourceLocation TemplateKWLoc,
2050                        const TemplateArgumentListInfo *TemplateArgs) {
2051   bool RefersToCapturedVariable =
2052       isa<VarDecl>(D) &&
2053       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2054 
2055   DeclRefExpr *E = DeclRefExpr::Create(
2056       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2057       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2058   MarkDeclRefReferenced(E);
2059 
2060   // C++ [except.spec]p17:
2061   //   An exception-specification is considered to be needed when:
2062   //   - in an expression, the function is the unique lookup result or
2063   //     the selected member of a set of overloaded functions.
2064   //
2065   // We delay doing this until after we've built the function reference and
2066   // marked it as used so that:
2067   //  a) if the function is defaulted, we get errors from defining it before /
2068   //     instead of errors from computing its exception specification, and
2069   //  b) if the function is a defaulted comparison, we can use the body we
2070   //     build when defining it as input to the exception specification
2071   //     computation rather than computing a new body.
2072   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2073     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2074       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2075         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2076     }
2077   }
2078 
2079   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2080       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2081       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2082     getCurFunction()->recordUseOfWeak(E);
2083 
2084   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2085   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2086     FD = IFD->getAnonField();
2087   if (FD) {
2088     UnusedPrivateFields.remove(FD);
2089     // Just in case we're building an illegal pointer-to-member.
2090     if (FD->isBitField())
2091       E->setObjectKind(OK_BitField);
2092   }
2093 
2094   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2095   // designates a bit-field.
2096   if (auto *BD = dyn_cast<BindingDecl>(D))
2097     if (auto *BE = BD->getBinding())
2098       E->setObjectKind(BE->getObjectKind());
2099 
2100   return E;
2101 }
2102 
2103 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2104 /// possibly a list of template arguments.
2105 ///
2106 /// If this produces template arguments, it is permitted to call
2107 /// DecomposeTemplateName.
2108 ///
2109 /// This actually loses a lot of source location information for
2110 /// non-standard name kinds; we should consider preserving that in
2111 /// some way.
2112 void
2113 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2114                              TemplateArgumentListInfo &Buffer,
2115                              DeclarationNameInfo &NameInfo,
2116                              const TemplateArgumentListInfo *&TemplateArgs) {
2117   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2118     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2119     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2120 
2121     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2122                                        Id.TemplateId->NumArgs);
2123     translateTemplateArguments(TemplateArgsPtr, Buffer);
2124 
2125     TemplateName TName = Id.TemplateId->Template.get();
2126     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2127     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2128     TemplateArgs = &Buffer;
2129   } else {
2130     NameInfo = GetNameFromUnqualifiedId(Id);
2131     TemplateArgs = nullptr;
2132   }
2133 }
2134 
2135 static void emitEmptyLookupTypoDiagnostic(
2136     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2137     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2138     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2139   DeclContext *Ctx =
2140       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2141   if (!TC) {
2142     // Emit a special diagnostic for failed member lookups.
2143     // FIXME: computing the declaration context might fail here (?)
2144     if (Ctx)
2145       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2146                                                  << SS.getRange();
2147     else
2148       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2149     return;
2150   }
2151 
2152   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2153   bool DroppedSpecifier =
2154       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2155   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2156                         ? diag::note_implicit_param_decl
2157                         : diag::note_previous_decl;
2158   if (!Ctx)
2159     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2160                          SemaRef.PDiag(NoteID));
2161   else
2162     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2163                                  << Typo << Ctx << DroppedSpecifier
2164                                  << SS.getRange(),
2165                          SemaRef.PDiag(NoteID));
2166 }
2167 
2168 /// Diagnose a lookup that found results in an enclosing class during error
2169 /// recovery. This usually indicates that the results were found in a dependent
2170 /// base class that could not be searched as part of a template definition.
2171 /// Always issues a diagnostic (though this may be only a warning in MS
2172 /// compatibility mode).
2173 ///
2174 /// Return \c true if the error is unrecoverable, or \c false if the caller
2175 /// should attempt to recover using these lookup results.
2176 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2177   // During a default argument instantiation the CurContext points
2178   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2179   // function parameter list, hence add an explicit check.
2180   bool isDefaultArgument =
2181       !CodeSynthesisContexts.empty() &&
2182       CodeSynthesisContexts.back().Kind ==
2183           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2184   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2185   bool isInstance = CurMethod && CurMethod->isInstance() &&
2186                     R.getNamingClass() == CurMethod->getParent() &&
2187                     !isDefaultArgument;
2188 
2189   // There are two ways we can find a class-scope declaration during template
2190   // instantiation that we did not find in the template definition: if it is a
2191   // member of a dependent base class, or if it is declared after the point of
2192   // use in the same class. Distinguish these by comparing the class in which
2193   // the member was found to the naming class of the lookup.
2194   unsigned DiagID = diag::err_found_in_dependent_base;
2195   unsigned NoteID = diag::note_member_declared_at;
2196   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2197     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2198                                       : diag::err_found_later_in_class;
2199   } else if (getLangOpts().MSVCCompat) {
2200     DiagID = diag::ext_found_in_dependent_base;
2201     NoteID = diag::note_dependent_member_use;
2202   }
2203 
2204   if (isInstance) {
2205     // Give a code modification hint to insert 'this->'.
2206     Diag(R.getNameLoc(), DiagID)
2207         << R.getLookupName()
2208         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2209     CheckCXXThisCapture(R.getNameLoc());
2210   } else {
2211     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2212     // they're not shadowed).
2213     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2214   }
2215 
2216   for (NamedDecl *D : R)
2217     Diag(D->getLocation(), NoteID);
2218 
2219   // Return true if we are inside a default argument instantiation
2220   // and the found name refers to an instance member function, otherwise
2221   // the caller will try to create an implicit member call and this is wrong
2222   // for default arguments.
2223   //
2224   // FIXME: Is this special case necessary? We could allow the caller to
2225   // diagnose this.
2226   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2227     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2228     return true;
2229   }
2230 
2231   // Tell the callee to try to recover.
2232   return false;
2233 }
2234 
2235 /// Diagnose an empty lookup.
2236 ///
2237 /// \return false if new lookup candidates were found
2238 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2239                                CorrectionCandidateCallback &CCC,
2240                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2241                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2242   DeclarationName Name = R.getLookupName();
2243 
2244   unsigned diagnostic = diag::err_undeclared_var_use;
2245   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2246   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2247       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2248       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2249     diagnostic = diag::err_undeclared_use;
2250     diagnostic_suggest = diag::err_undeclared_use_suggest;
2251   }
2252 
2253   // If the original lookup was an unqualified lookup, fake an
2254   // unqualified lookup.  This is useful when (for example) the
2255   // original lookup would not have found something because it was a
2256   // dependent name.
2257   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2258   while (DC) {
2259     if (isa<CXXRecordDecl>(DC)) {
2260       LookupQualifiedName(R, DC);
2261 
2262       if (!R.empty()) {
2263         // Don't give errors about ambiguities in this lookup.
2264         R.suppressDiagnostics();
2265 
2266         // If there's a best viable function among the results, only mention
2267         // that one in the notes.
2268         OverloadCandidateSet Candidates(R.getNameLoc(),
2269                                         OverloadCandidateSet::CSK_Normal);
2270         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2271         OverloadCandidateSet::iterator Best;
2272         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2273             OR_Success) {
2274           R.clear();
2275           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2276           R.resolveKind();
2277         }
2278 
2279         return DiagnoseDependentMemberLookup(R);
2280       }
2281 
2282       R.clear();
2283     }
2284 
2285     DC = DC->getLookupParent();
2286   }
2287 
2288   // We didn't find anything, so try to correct for a typo.
2289   TypoCorrection Corrected;
2290   if (S && Out) {
2291     SourceLocation TypoLoc = R.getNameLoc();
2292     assert(!ExplicitTemplateArgs &&
2293            "Diagnosing an empty lookup with explicit template args!");
2294     *Out = CorrectTypoDelayed(
2295         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2296         [=](const TypoCorrection &TC) {
2297           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2298                                         diagnostic, diagnostic_suggest);
2299         },
2300         nullptr, CTK_ErrorRecovery);
2301     if (*Out)
2302       return true;
2303   } else if (S &&
2304              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2305                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2306     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2307     bool DroppedSpecifier =
2308         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2309     R.setLookupName(Corrected.getCorrection());
2310 
2311     bool AcceptableWithRecovery = false;
2312     bool AcceptableWithoutRecovery = false;
2313     NamedDecl *ND = Corrected.getFoundDecl();
2314     if (ND) {
2315       if (Corrected.isOverloaded()) {
2316         OverloadCandidateSet OCS(R.getNameLoc(),
2317                                  OverloadCandidateSet::CSK_Normal);
2318         OverloadCandidateSet::iterator Best;
2319         for (NamedDecl *CD : Corrected) {
2320           if (FunctionTemplateDecl *FTD =
2321                    dyn_cast<FunctionTemplateDecl>(CD))
2322             AddTemplateOverloadCandidate(
2323                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2324                 Args, OCS);
2325           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2326             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2327               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2328                                    Args, OCS);
2329         }
2330         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2331         case OR_Success:
2332           ND = Best->FoundDecl;
2333           Corrected.setCorrectionDecl(ND);
2334           break;
2335         default:
2336           // FIXME: Arbitrarily pick the first declaration for the note.
2337           Corrected.setCorrectionDecl(ND);
2338           break;
2339         }
2340       }
2341       R.addDecl(ND);
2342       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2343         CXXRecordDecl *Record = nullptr;
2344         if (Corrected.getCorrectionSpecifier()) {
2345           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2346           Record = Ty->getAsCXXRecordDecl();
2347         }
2348         if (!Record)
2349           Record = cast<CXXRecordDecl>(
2350               ND->getDeclContext()->getRedeclContext());
2351         R.setNamingClass(Record);
2352       }
2353 
2354       auto *UnderlyingND = ND->getUnderlyingDecl();
2355       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2356                                isa<FunctionTemplateDecl>(UnderlyingND);
2357       // FIXME: If we ended up with a typo for a type name or
2358       // Objective-C class name, we're in trouble because the parser
2359       // is in the wrong place to recover. Suggest the typo
2360       // correction, but don't make it a fix-it since we're not going
2361       // to recover well anyway.
2362       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2363                                   getAsTypeTemplateDecl(UnderlyingND) ||
2364                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2365     } else {
2366       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2367       // because we aren't able to recover.
2368       AcceptableWithoutRecovery = true;
2369     }
2370 
2371     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2372       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2373                             ? diag::note_implicit_param_decl
2374                             : diag::note_previous_decl;
2375       if (SS.isEmpty())
2376         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2377                      PDiag(NoteID), AcceptableWithRecovery);
2378       else
2379         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2380                                   << Name << computeDeclContext(SS, false)
2381                                   << DroppedSpecifier << SS.getRange(),
2382                      PDiag(NoteID), AcceptableWithRecovery);
2383 
2384       // Tell the callee whether to try to recover.
2385       return !AcceptableWithRecovery;
2386     }
2387   }
2388   R.clear();
2389 
2390   // Emit a special diagnostic for failed member lookups.
2391   // FIXME: computing the declaration context might fail here (?)
2392   if (!SS.isEmpty()) {
2393     Diag(R.getNameLoc(), diag::err_no_member)
2394       << Name << computeDeclContext(SS, false)
2395       << SS.getRange();
2396     return true;
2397   }
2398 
2399   // Give up, we can't recover.
2400   Diag(R.getNameLoc(), diagnostic) << Name;
2401   return true;
2402 }
2403 
2404 /// In Microsoft mode, if we are inside a template class whose parent class has
2405 /// dependent base classes, and we can't resolve an unqualified identifier, then
2406 /// assume the identifier is a member of a dependent base class.  We can only
2407 /// recover successfully in static methods, instance methods, and other contexts
2408 /// where 'this' is available.  This doesn't precisely match MSVC's
2409 /// instantiation model, but it's close enough.
2410 static Expr *
2411 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2412                                DeclarationNameInfo &NameInfo,
2413                                SourceLocation TemplateKWLoc,
2414                                const TemplateArgumentListInfo *TemplateArgs) {
2415   // Only try to recover from lookup into dependent bases in static methods or
2416   // contexts where 'this' is available.
2417   QualType ThisType = S.getCurrentThisType();
2418   const CXXRecordDecl *RD = nullptr;
2419   if (!ThisType.isNull())
2420     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2421   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2422     RD = MD->getParent();
2423   if (!RD || !RD->hasAnyDependentBases())
2424     return nullptr;
2425 
2426   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2427   // is available, suggest inserting 'this->' as a fixit.
2428   SourceLocation Loc = NameInfo.getLoc();
2429   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2430   DB << NameInfo.getName() << RD;
2431 
2432   if (!ThisType.isNull()) {
2433     DB << FixItHint::CreateInsertion(Loc, "this->");
2434     return CXXDependentScopeMemberExpr::Create(
2435         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2436         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2437         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2438   }
2439 
2440   // Synthesize a fake NNS that points to the derived class.  This will
2441   // perform name lookup during template instantiation.
2442   CXXScopeSpec SS;
2443   auto *NNS =
2444       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2445   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2446   return DependentScopeDeclRefExpr::Create(
2447       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2448       TemplateArgs);
2449 }
2450 
2451 ExprResult
2452 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2453                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2454                         bool HasTrailingLParen, bool IsAddressOfOperand,
2455                         CorrectionCandidateCallback *CCC,
2456                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2457   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2458          "cannot be direct & operand and have a trailing lparen");
2459   if (SS.isInvalid())
2460     return ExprError();
2461 
2462   TemplateArgumentListInfo TemplateArgsBuffer;
2463 
2464   // Decompose the UnqualifiedId into the following data.
2465   DeclarationNameInfo NameInfo;
2466   const TemplateArgumentListInfo *TemplateArgs;
2467   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2468 
2469   DeclarationName Name = NameInfo.getName();
2470   IdentifierInfo *II = Name.getAsIdentifierInfo();
2471   SourceLocation NameLoc = NameInfo.getLoc();
2472 
2473   if (II && II->isEditorPlaceholder()) {
2474     // FIXME: When typed placeholders are supported we can create a typed
2475     // placeholder expression node.
2476     return ExprError();
2477   }
2478 
2479   // C++ [temp.dep.expr]p3:
2480   //   An id-expression is type-dependent if it contains:
2481   //     -- an identifier that was declared with a dependent type,
2482   //        (note: handled after lookup)
2483   //     -- a template-id that is dependent,
2484   //        (note: handled in BuildTemplateIdExpr)
2485   //     -- a conversion-function-id that specifies a dependent type,
2486   //     -- a nested-name-specifier that contains a class-name that
2487   //        names a dependent type.
2488   // Determine whether this is a member of an unknown specialization;
2489   // we need to handle these differently.
2490   bool DependentID = false;
2491   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2492       Name.getCXXNameType()->isDependentType()) {
2493     DependentID = true;
2494   } else if (SS.isSet()) {
2495     if (DeclContext *DC = computeDeclContext(SS, false)) {
2496       if (RequireCompleteDeclContext(SS, DC))
2497         return ExprError();
2498     } else {
2499       DependentID = true;
2500     }
2501   }
2502 
2503   if (DependentID)
2504     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2505                                       IsAddressOfOperand, TemplateArgs);
2506 
2507   // Perform the required lookup.
2508   LookupResult R(*this, NameInfo,
2509                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2510                      ? LookupObjCImplicitSelfParam
2511                      : LookupOrdinaryName);
2512   if (TemplateKWLoc.isValid() || TemplateArgs) {
2513     // Lookup the template name again to correctly establish the context in
2514     // which it was found. This is really unfortunate as we already did the
2515     // lookup to determine that it was a template name in the first place. If
2516     // this becomes a performance hit, we can work harder to preserve those
2517     // results until we get here but it's likely not worth it.
2518     bool MemberOfUnknownSpecialization;
2519     AssumedTemplateKind AssumedTemplate;
2520     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2521                            MemberOfUnknownSpecialization, TemplateKWLoc,
2522                            &AssumedTemplate))
2523       return ExprError();
2524 
2525     if (MemberOfUnknownSpecialization ||
2526         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2527       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2528                                         IsAddressOfOperand, TemplateArgs);
2529   } else {
2530     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2531     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2532 
2533     // If the result might be in a dependent base class, this is a dependent
2534     // id-expression.
2535     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2536       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2537                                         IsAddressOfOperand, TemplateArgs);
2538 
2539     // If this reference is in an Objective-C method, then we need to do
2540     // some special Objective-C lookup, too.
2541     if (IvarLookupFollowUp) {
2542       ExprResult E(LookupInObjCMethod(R, S, II, true));
2543       if (E.isInvalid())
2544         return ExprError();
2545 
2546       if (Expr *Ex = E.getAs<Expr>())
2547         return Ex;
2548     }
2549   }
2550 
2551   if (R.isAmbiguous())
2552     return ExprError();
2553 
2554   // This could be an implicitly declared function reference (legal in C90,
2555   // extension in C99, forbidden in C++).
2556   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2557     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2558     if (D) R.addDecl(D);
2559   }
2560 
2561   // Determine whether this name might be a candidate for
2562   // argument-dependent lookup.
2563   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2564 
2565   if (R.empty() && !ADL) {
2566     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2567       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2568                                                    TemplateKWLoc, TemplateArgs))
2569         return E;
2570     }
2571 
2572     // Don't diagnose an empty lookup for inline assembly.
2573     if (IsInlineAsmIdentifier)
2574       return ExprError();
2575 
2576     // If this name wasn't predeclared and if this is not a function
2577     // call, diagnose the problem.
2578     TypoExpr *TE = nullptr;
2579     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2580                                                        : nullptr);
2581     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2582     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2583            "Typo correction callback misconfigured");
2584     if (CCC) {
2585       // Make sure the callback knows what the typo being diagnosed is.
2586       CCC->setTypoName(II);
2587       if (SS.isValid())
2588         CCC->setTypoNNS(SS.getScopeRep());
2589     }
2590     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2591     // a template name, but we happen to have always already looked up the name
2592     // before we get here if it must be a template name.
2593     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2594                             None, &TE)) {
2595       if (TE && KeywordReplacement) {
2596         auto &State = getTypoExprState(TE);
2597         auto BestTC = State.Consumer->getNextCorrection();
2598         if (BestTC.isKeyword()) {
2599           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2600           if (State.DiagHandler)
2601             State.DiagHandler(BestTC);
2602           KeywordReplacement->startToken();
2603           KeywordReplacement->setKind(II->getTokenID());
2604           KeywordReplacement->setIdentifierInfo(II);
2605           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2606           // Clean up the state associated with the TypoExpr, since it has
2607           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2608           clearDelayedTypo(TE);
2609           // Signal that a correction to a keyword was performed by returning a
2610           // valid-but-null ExprResult.
2611           return (Expr*)nullptr;
2612         }
2613         State.Consumer->resetCorrectionStream();
2614       }
2615       return TE ? TE : ExprError();
2616     }
2617 
2618     assert(!R.empty() &&
2619            "DiagnoseEmptyLookup returned false but added no results");
2620 
2621     // If we found an Objective-C instance variable, let
2622     // LookupInObjCMethod build the appropriate expression to
2623     // reference the ivar.
2624     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2625       R.clear();
2626       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2627       // In a hopelessly buggy code, Objective-C instance variable
2628       // lookup fails and no expression will be built to reference it.
2629       if (!E.isInvalid() && !E.get())
2630         return ExprError();
2631       return E;
2632     }
2633   }
2634 
2635   // This is guaranteed from this point on.
2636   assert(!R.empty() || ADL);
2637 
2638   // Check whether this might be a C++ implicit instance member access.
2639   // C++ [class.mfct.non-static]p3:
2640   //   When an id-expression that is not part of a class member access
2641   //   syntax and not used to form a pointer to member is used in the
2642   //   body of a non-static member function of class X, if name lookup
2643   //   resolves the name in the id-expression to a non-static non-type
2644   //   member of some class C, the id-expression is transformed into a
2645   //   class member access expression using (*this) as the
2646   //   postfix-expression to the left of the . operator.
2647   //
2648   // But we don't actually need to do this for '&' operands if R
2649   // resolved to a function or overloaded function set, because the
2650   // expression is ill-formed if it actually works out to be a
2651   // non-static member function:
2652   //
2653   // C++ [expr.ref]p4:
2654   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2655   //   [t]he expression can be used only as the left-hand operand of a
2656   //   member function call.
2657   //
2658   // There are other safeguards against such uses, but it's important
2659   // to get this right here so that we don't end up making a
2660   // spuriously dependent expression if we're inside a dependent
2661   // instance method.
2662   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2663     bool MightBeImplicitMember;
2664     if (!IsAddressOfOperand)
2665       MightBeImplicitMember = true;
2666     else if (!SS.isEmpty())
2667       MightBeImplicitMember = false;
2668     else if (R.isOverloadedResult())
2669       MightBeImplicitMember = false;
2670     else if (R.isUnresolvableResult())
2671       MightBeImplicitMember = true;
2672     else
2673       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2674                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2675                               isa<MSPropertyDecl>(R.getFoundDecl());
2676 
2677     if (MightBeImplicitMember)
2678       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2679                                              R, TemplateArgs, S);
2680   }
2681 
2682   if (TemplateArgs || TemplateKWLoc.isValid()) {
2683 
2684     // In C++1y, if this is a variable template id, then check it
2685     // in BuildTemplateIdExpr().
2686     // The single lookup result must be a variable template declaration.
2687     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2688         Id.TemplateId->Kind == TNK_Var_template) {
2689       assert(R.getAsSingle<VarTemplateDecl>() &&
2690              "There should only be one declaration found.");
2691     }
2692 
2693     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2694   }
2695 
2696   return BuildDeclarationNameExpr(SS, R, ADL);
2697 }
2698 
2699 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2700 /// declaration name, generally during template instantiation.
2701 /// There's a large number of things which don't need to be done along
2702 /// this path.
2703 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2704     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2705     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2706   DeclContext *DC = computeDeclContext(SS, false);
2707   if (!DC)
2708     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2709                                      NameInfo, /*TemplateArgs=*/nullptr);
2710 
2711   if (RequireCompleteDeclContext(SS, DC))
2712     return ExprError();
2713 
2714   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2715   LookupQualifiedName(R, DC);
2716 
2717   if (R.isAmbiguous())
2718     return ExprError();
2719 
2720   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2721     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2722                                      NameInfo, /*TemplateArgs=*/nullptr);
2723 
2724   if (R.empty()) {
2725     // Don't diagnose problems with invalid record decl, the secondary no_member
2726     // diagnostic during template instantiation is likely bogus, e.g. if a class
2727     // is invalid because it's derived from an invalid base class, then missing
2728     // members were likely supposed to be inherited.
2729     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2730       if (CD->isInvalidDecl())
2731         return ExprError();
2732     Diag(NameInfo.getLoc(), diag::err_no_member)
2733       << NameInfo.getName() << DC << SS.getRange();
2734     return ExprError();
2735   }
2736 
2737   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2738     // Diagnose a missing typename if this resolved unambiguously to a type in
2739     // a dependent context.  If we can recover with a type, downgrade this to
2740     // a warning in Microsoft compatibility mode.
2741     unsigned DiagID = diag::err_typename_missing;
2742     if (RecoveryTSI && getLangOpts().MSVCCompat)
2743       DiagID = diag::ext_typename_missing;
2744     SourceLocation Loc = SS.getBeginLoc();
2745     auto D = Diag(Loc, DiagID);
2746     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2747       << SourceRange(Loc, NameInfo.getEndLoc());
2748 
2749     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2750     // context.
2751     if (!RecoveryTSI)
2752       return ExprError();
2753 
2754     // Only issue the fixit if we're prepared to recover.
2755     D << FixItHint::CreateInsertion(Loc, "typename ");
2756 
2757     // Recover by pretending this was an elaborated type.
2758     QualType Ty = Context.getTypeDeclType(TD);
2759     TypeLocBuilder TLB;
2760     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2761 
2762     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2763     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2764     QTL.setElaboratedKeywordLoc(SourceLocation());
2765     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2766 
2767     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2768 
2769     return ExprEmpty();
2770   }
2771 
2772   // Defend against this resolving to an implicit member access. We usually
2773   // won't get here if this might be a legitimate a class member (we end up in
2774   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2775   // a pointer-to-member or in an unevaluated context in C++11.
2776   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2777     return BuildPossibleImplicitMemberExpr(SS,
2778                                            /*TemplateKWLoc=*/SourceLocation(),
2779                                            R, /*TemplateArgs=*/nullptr, S);
2780 
2781   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2782 }
2783 
2784 /// The parser has read a name in, and Sema has detected that we're currently
2785 /// inside an ObjC method. Perform some additional checks and determine if we
2786 /// should form a reference to an ivar.
2787 ///
2788 /// Ideally, most of this would be done by lookup, but there's
2789 /// actually quite a lot of extra work involved.
2790 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2791                                         IdentifierInfo *II) {
2792   SourceLocation Loc = Lookup.getNameLoc();
2793   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2794 
2795   // Check for error condition which is already reported.
2796   if (!CurMethod)
2797     return DeclResult(true);
2798 
2799   // There are two cases to handle here.  1) scoped lookup could have failed,
2800   // in which case we should look for an ivar.  2) scoped lookup could have
2801   // found a decl, but that decl is outside the current instance method (i.e.
2802   // a global variable).  In these two cases, we do a lookup for an ivar with
2803   // this name, if the lookup sucedes, we replace it our current decl.
2804 
2805   // If we're in a class method, we don't normally want to look for
2806   // ivars.  But if we don't find anything else, and there's an
2807   // ivar, that's an error.
2808   bool IsClassMethod = CurMethod->isClassMethod();
2809 
2810   bool LookForIvars;
2811   if (Lookup.empty())
2812     LookForIvars = true;
2813   else if (IsClassMethod)
2814     LookForIvars = false;
2815   else
2816     LookForIvars = (Lookup.isSingleResult() &&
2817                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2818   ObjCInterfaceDecl *IFace = nullptr;
2819   if (LookForIvars) {
2820     IFace = CurMethod->getClassInterface();
2821     ObjCInterfaceDecl *ClassDeclared;
2822     ObjCIvarDecl *IV = nullptr;
2823     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2824       // Diagnose using an ivar in a class method.
2825       if (IsClassMethod) {
2826         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2827         return DeclResult(true);
2828       }
2829 
2830       // Diagnose the use of an ivar outside of the declaring class.
2831       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2832           !declaresSameEntity(ClassDeclared, IFace) &&
2833           !getLangOpts().DebuggerSupport)
2834         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2835 
2836       // Success.
2837       return IV;
2838     }
2839   } else if (CurMethod->isInstanceMethod()) {
2840     // We should warn if a local variable hides an ivar.
2841     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2842       ObjCInterfaceDecl *ClassDeclared;
2843       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2844         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2845             declaresSameEntity(IFace, ClassDeclared))
2846           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2847       }
2848     }
2849   } else if (Lookup.isSingleResult() &&
2850              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2851     // If accessing a stand-alone ivar in a class method, this is an error.
2852     if (const ObjCIvarDecl *IV =
2853             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2854       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2855       return DeclResult(true);
2856     }
2857   }
2858 
2859   // Didn't encounter an error, didn't find an ivar.
2860   return DeclResult(false);
2861 }
2862 
2863 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2864                                   ObjCIvarDecl *IV) {
2865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2866   assert(CurMethod && CurMethod->isInstanceMethod() &&
2867          "should not reference ivar from this context");
2868 
2869   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2870   assert(IFace && "should not reference ivar from this context");
2871 
2872   // If we're referencing an invalid decl, just return this as a silent
2873   // error node.  The error diagnostic was already emitted on the decl.
2874   if (IV->isInvalidDecl())
2875     return ExprError();
2876 
2877   // Check if referencing a field with __attribute__((deprecated)).
2878   if (DiagnoseUseOfDecl(IV, Loc))
2879     return ExprError();
2880 
2881   // FIXME: This should use a new expr for a direct reference, don't
2882   // turn this into Self->ivar, just return a BareIVarExpr or something.
2883   IdentifierInfo &II = Context.Idents.get("self");
2884   UnqualifiedId SelfName;
2885   SelfName.setImplicitSelfParam(&II);
2886   CXXScopeSpec SelfScopeSpec;
2887   SourceLocation TemplateKWLoc;
2888   ExprResult SelfExpr =
2889       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2890                         /*HasTrailingLParen=*/false,
2891                         /*IsAddressOfOperand=*/false);
2892   if (SelfExpr.isInvalid())
2893     return ExprError();
2894 
2895   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2896   if (SelfExpr.isInvalid())
2897     return ExprError();
2898 
2899   MarkAnyDeclReferenced(Loc, IV, true);
2900 
2901   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2902   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2903       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2904     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2905 
2906   ObjCIvarRefExpr *Result = new (Context)
2907       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2908                       IV->getLocation(), SelfExpr.get(), true, true);
2909 
2910   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2911     if (!isUnevaluatedContext() &&
2912         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2913       getCurFunction()->recordUseOfWeak(Result);
2914   }
2915   if (getLangOpts().ObjCAutoRefCount)
2916     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2917       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2918 
2919   return Result;
2920 }
2921 
2922 /// The parser has read a name in, and Sema has detected that we're currently
2923 /// inside an ObjC method. Perform some additional checks and determine if we
2924 /// should form a reference to an ivar. If so, build an expression referencing
2925 /// that ivar.
2926 ExprResult
2927 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2928                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2929   // FIXME: Integrate this lookup step into LookupParsedName.
2930   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2931   if (Ivar.isInvalid())
2932     return ExprError();
2933   if (Ivar.isUsable())
2934     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2935                             cast<ObjCIvarDecl>(Ivar.get()));
2936 
2937   if (Lookup.empty() && II && AllowBuiltinCreation)
2938     LookupBuiltin(Lookup);
2939 
2940   // Sentinel value saying that we didn't do anything special.
2941   return ExprResult(false);
2942 }
2943 
2944 /// Cast a base object to a member's actual type.
2945 ///
2946 /// There are two relevant checks:
2947 ///
2948 /// C++ [class.access.base]p7:
2949 ///
2950 ///   If a class member access operator [...] is used to access a non-static
2951 ///   data member or non-static member function, the reference is ill-formed if
2952 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2953 ///   naming class of the right operand.
2954 ///
2955 /// C++ [expr.ref]p7:
2956 ///
2957 ///   If E2 is a non-static data member or a non-static member function, the
2958 ///   program is ill-formed if the class of which E2 is directly a member is an
2959 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2960 ///
2961 /// Note that the latter check does not consider access; the access of the
2962 /// "real" base class is checked as appropriate when checking the access of the
2963 /// member name.
2964 ExprResult
2965 Sema::PerformObjectMemberConversion(Expr *From,
2966                                     NestedNameSpecifier *Qualifier,
2967                                     NamedDecl *FoundDecl,
2968                                     NamedDecl *Member) {
2969   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2970   if (!RD)
2971     return From;
2972 
2973   QualType DestRecordType;
2974   QualType DestType;
2975   QualType FromRecordType;
2976   QualType FromType = From->getType();
2977   bool PointerConversions = false;
2978   if (isa<FieldDecl>(Member)) {
2979     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2980     auto FromPtrType = FromType->getAs<PointerType>();
2981     DestRecordType = Context.getAddrSpaceQualType(
2982         DestRecordType, FromPtrType
2983                             ? FromType->getPointeeType().getAddressSpace()
2984                             : FromType.getAddressSpace());
2985 
2986     if (FromPtrType) {
2987       DestType = Context.getPointerType(DestRecordType);
2988       FromRecordType = FromPtrType->getPointeeType();
2989       PointerConversions = true;
2990     } else {
2991       DestType = DestRecordType;
2992       FromRecordType = FromType;
2993     }
2994   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2995     if (Method->isStatic())
2996       return From;
2997 
2998     DestType = Method->getThisType();
2999     DestRecordType = DestType->getPointeeType();
3000 
3001     if (FromType->getAs<PointerType>()) {
3002       FromRecordType = FromType->getPointeeType();
3003       PointerConversions = true;
3004     } else {
3005       FromRecordType = FromType;
3006       DestType = DestRecordType;
3007     }
3008 
3009     LangAS FromAS = FromRecordType.getAddressSpace();
3010     LangAS DestAS = DestRecordType.getAddressSpace();
3011     if (FromAS != DestAS) {
3012       QualType FromRecordTypeWithoutAS =
3013           Context.removeAddrSpaceQualType(FromRecordType);
3014       QualType FromTypeWithDestAS =
3015           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3016       if (PointerConversions)
3017         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3018       From = ImpCastExprToType(From, FromTypeWithDestAS,
3019                                CK_AddressSpaceConversion, From->getValueKind())
3020                  .get();
3021     }
3022   } else {
3023     // No conversion necessary.
3024     return From;
3025   }
3026 
3027   if (DestType->isDependentType() || FromType->isDependentType())
3028     return From;
3029 
3030   // If the unqualified types are the same, no conversion is necessary.
3031   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3032     return From;
3033 
3034   SourceRange FromRange = From->getSourceRange();
3035   SourceLocation FromLoc = FromRange.getBegin();
3036 
3037   ExprValueKind VK = From->getValueKind();
3038 
3039   // C++ [class.member.lookup]p8:
3040   //   [...] Ambiguities can often be resolved by qualifying a name with its
3041   //   class name.
3042   //
3043   // If the member was a qualified name and the qualified referred to a
3044   // specific base subobject type, we'll cast to that intermediate type
3045   // first and then to the object in which the member is declared. That allows
3046   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3047   //
3048   //   class Base { public: int x; };
3049   //   class Derived1 : public Base { };
3050   //   class Derived2 : public Base { };
3051   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3052   //
3053   //   void VeryDerived::f() {
3054   //     x = 17; // error: ambiguous base subobjects
3055   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3056   //   }
3057   if (Qualifier && Qualifier->getAsType()) {
3058     QualType QType = QualType(Qualifier->getAsType(), 0);
3059     assert(QType->isRecordType() && "lookup done with non-record type");
3060 
3061     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3062 
3063     // In C++98, the qualifier type doesn't actually have to be a base
3064     // type of the object type, in which case we just ignore it.
3065     // Otherwise build the appropriate casts.
3066     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3067       CXXCastPath BasePath;
3068       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3069                                        FromLoc, FromRange, &BasePath))
3070         return ExprError();
3071 
3072       if (PointerConversions)
3073         QType = Context.getPointerType(QType);
3074       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3075                                VK, &BasePath).get();
3076 
3077       FromType = QType;
3078       FromRecordType = QRecordType;
3079 
3080       // If the qualifier type was the same as the destination type,
3081       // we're done.
3082       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3083         return From;
3084     }
3085   }
3086 
3087   CXXCastPath BasePath;
3088   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3089                                    FromLoc, FromRange, &BasePath,
3090                                    /*IgnoreAccess=*/true))
3091     return ExprError();
3092 
3093   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3094                            VK, &BasePath);
3095 }
3096 
3097 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3098                                       const LookupResult &R,
3099                                       bool HasTrailingLParen) {
3100   // Only when used directly as the postfix-expression of a call.
3101   if (!HasTrailingLParen)
3102     return false;
3103 
3104   // Never if a scope specifier was provided.
3105   if (SS.isSet())
3106     return false;
3107 
3108   // Only in C++ or ObjC++.
3109   if (!getLangOpts().CPlusPlus)
3110     return false;
3111 
3112   // Turn off ADL when we find certain kinds of declarations during
3113   // normal lookup:
3114   for (NamedDecl *D : R) {
3115     // C++0x [basic.lookup.argdep]p3:
3116     //     -- a declaration of a class member
3117     // Since using decls preserve this property, we check this on the
3118     // original decl.
3119     if (D->isCXXClassMember())
3120       return false;
3121 
3122     // C++0x [basic.lookup.argdep]p3:
3123     //     -- a block-scope function declaration that is not a
3124     //        using-declaration
3125     // NOTE: we also trigger this for function templates (in fact, we
3126     // don't check the decl type at all, since all other decl types
3127     // turn off ADL anyway).
3128     if (isa<UsingShadowDecl>(D))
3129       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3130     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3131       return false;
3132 
3133     // C++0x [basic.lookup.argdep]p3:
3134     //     -- a declaration that is neither a function or a function
3135     //        template
3136     // And also for builtin functions.
3137     if (isa<FunctionDecl>(D)) {
3138       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3139 
3140       // But also builtin functions.
3141       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3142         return false;
3143     } else if (!isa<FunctionTemplateDecl>(D))
3144       return false;
3145   }
3146 
3147   return true;
3148 }
3149 
3150 
3151 /// Diagnoses obvious problems with the use of the given declaration
3152 /// as an expression.  This is only actually called for lookups that
3153 /// were not overloaded, and it doesn't promise that the declaration
3154 /// will in fact be used.
3155 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3156   if (D->isInvalidDecl())
3157     return true;
3158 
3159   if (isa<TypedefNameDecl>(D)) {
3160     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3161     return true;
3162   }
3163 
3164   if (isa<ObjCInterfaceDecl>(D)) {
3165     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3166     return true;
3167   }
3168 
3169   if (isa<NamespaceDecl>(D)) {
3170     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3171     return true;
3172   }
3173 
3174   return false;
3175 }
3176 
3177 // Certain multiversion types should be treated as overloaded even when there is
3178 // only one result.
3179 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3180   assert(R.isSingleResult() && "Expected only a single result");
3181   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3182   return FD &&
3183          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3184 }
3185 
3186 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3187                                           LookupResult &R, bool NeedsADL,
3188                                           bool AcceptInvalidDecl) {
3189   // If this is a single, fully-resolved result and we don't need ADL,
3190   // just build an ordinary singleton decl ref.
3191   if (!NeedsADL && R.isSingleResult() &&
3192       !R.getAsSingle<FunctionTemplateDecl>() &&
3193       !ShouldLookupResultBeMultiVersionOverload(R))
3194     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3195                                     R.getRepresentativeDecl(), nullptr,
3196                                     AcceptInvalidDecl);
3197 
3198   // We only need to check the declaration if there's exactly one
3199   // result, because in the overloaded case the results can only be
3200   // functions and function templates.
3201   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3202       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3203     return ExprError();
3204 
3205   // Otherwise, just build an unresolved lookup expression.  Suppress
3206   // any lookup-related diagnostics; we'll hash these out later, when
3207   // we've picked a target.
3208   R.suppressDiagnostics();
3209 
3210   UnresolvedLookupExpr *ULE
3211     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3212                                    SS.getWithLocInContext(Context),
3213                                    R.getLookupNameInfo(),
3214                                    NeedsADL, R.isOverloadedResult(),
3215                                    R.begin(), R.end());
3216 
3217   return ULE;
3218 }
3219 
3220 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3221                                                ValueDecl *var);
3222 
3223 /// Complete semantic analysis for a reference to the given declaration.
3224 ExprResult Sema::BuildDeclarationNameExpr(
3225     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3226     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3227     bool AcceptInvalidDecl) {
3228   assert(D && "Cannot refer to a NULL declaration");
3229   assert(!isa<FunctionTemplateDecl>(D) &&
3230          "Cannot refer unambiguously to a function template");
3231 
3232   SourceLocation Loc = NameInfo.getLoc();
3233   if (CheckDeclInExpr(*this, Loc, D)) {
3234     // Recovery from invalid cases (e.g. D is an invalid Decl).
3235     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3236     // diagnostics, as invalid decls use int as a fallback type.
3237     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3238   }
3239 
3240   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3241     // Specifically diagnose references to class templates that are missing
3242     // a template argument list.
3243     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3244     return ExprError();
3245   }
3246 
3247   // Make sure that we're referring to a value.
3248   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3249     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3250     Diag(D->getLocation(), diag::note_declared_at);
3251     return ExprError();
3252   }
3253 
3254   // Check whether this declaration can be used. Note that we suppress
3255   // this check when we're going to perform argument-dependent lookup
3256   // on this function name, because this might not be the function
3257   // that overload resolution actually selects.
3258   if (DiagnoseUseOfDecl(D, Loc))
3259     return ExprError();
3260 
3261   auto *VD = cast<ValueDecl>(D);
3262 
3263   // Only create DeclRefExpr's for valid Decl's.
3264   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3265     return ExprError();
3266 
3267   // Handle members of anonymous structs and unions.  If we got here,
3268   // and the reference is to a class member indirect field, then this
3269   // must be the subject of a pointer-to-member expression.
3270   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3271     if (!indirectField->isCXXClassMember())
3272       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3273                                                       indirectField);
3274 
3275   QualType type = VD->getType();
3276   if (type.isNull())
3277     return ExprError();
3278   ExprValueKind valueKind = VK_PRValue;
3279 
3280   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3281   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3282   // is expanded by some outer '...' in the context of the use.
3283   type = type.getNonPackExpansionType();
3284 
3285   switch (D->getKind()) {
3286     // Ignore all the non-ValueDecl kinds.
3287 #define ABSTRACT_DECL(kind)
3288 #define VALUE(type, base)
3289 #define DECL(type, base) case Decl::type:
3290 #include "clang/AST/DeclNodes.inc"
3291     llvm_unreachable("invalid value decl kind");
3292 
3293   // These shouldn't make it here.
3294   case Decl::ObjCAtDefsField:
3295     llvm_unreachable("forming non-member reference to ivar?");
3296 
3297   // Enum constants are always r-values and never references.
3298   // Unresolved using declarations are dependent.
3299   case Decl::EnumConstant:
3300   case Decl::UnresolvedUsingValue:
3301   case Decl::OMPDeclareReduction:
3302   case Decl::OMPDeclareMapper:
3303     valueKind = VK_PRValue;
3304     break;
3305 
3306   // Fields and indirect fields that got here must be for
3307   // pointer-to-member expressions; we just call them l-values for
3308   // internal consistency, because this subexpression doesn't really
3309   // exist in the high-level semantics.
3310   case Decl::Field:
3311   case Decl::IndirectField:
3312   case Decl::ObjCIvar:
3313     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3314 
3315     // These can't have reference type in well-formed programs, but
3316     // for internal consistency we do this anyway.
3317     type = type.getNonReferenceType();
3318     valueKind = VK_LValue;
3319     break;
3320 
3321   // Non-type template parameters are either l-values or r-values
3322   // depending on the type.
3323   case Decl::NonTypeTemplateParm: {
3324     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3325       type = reftype->getPointeeType();
3326       valueKind = VK_LValue; // even if the parameter is an r-value reference
3327       break;
3328     }
3329 
3330     // [expr.prim.id.unqual]p2:
3331     //   If the entity is a template parameter object for a template
3332     //   parameter of type T, the type of the expression is const T.
3333     //   [...] The expression is an lvalue if the entity is a [...] template
3334     //   parameter object.
3335     if (type->isRecordType()) {
3336       type = type.getUnqualifiedType().withConst();
3337       valueKind = VK_LValue;
3338       break;
3339     }
3340 
3341     // For non-references, we need to strip qualifiers just in case
3342     // the template parameter was declared as 'const int' or whatever.
3343     valueKind = VK_PRValue;
3344     type = type.getUnqualifiedType();
3345     break;
3346   }
3347 
3348   case Decl::Var:
3349   case Decl::VarTemplateSpecialization:
3350   case Decl::VarTemplatePartialSpecialization:
3351   case Decl::Decomposition:
3352   case Decl::OMPCapturedExpr:
3353     // In C, "extern void blah;" is valid and is an r-value.
3354     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3355         type->isVoidType()) {
3356       valueKind = VK_PRValue;
3357       break;
3358     }
3359     LLVM_FALLTHROUGH;
3360 
3361   case Decl::ImplicitParam:
3362   case Decl::ParmVar: {
3363     // These are always l-values.
3364     valueKind = VK_LValue;
3365     type = type.getNonReferenceType();
3366 
3367     // FIXME: Does the addition of const really only apply in
3368     // potentially-evaluated contexts? Since the variable isn't actually
3369     // captured in an unevaluated context, it seems that the answer is no.
3370     if (!isUnevaluatedContext()) {
3371       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3372       if (!CapturedType.isNull())
3373         type = CapturedType;
3374     }
3375 
3376     break;
3377   }
3378 
3379   case Decl::Binding: {
3380     // These are always lvalues.
3381     valueKind = VK_LValue;
3382     type = type.getNonReferenceType();
3383     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3384     // decides how that's supposed to work.
3385     auto *BD = cast<BindingDecl>(VD);
3386     if (BD->getDeclContext() != CurContext) {
3387       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3388       if (DD && DD->hasLocalStorage())
3389         diagnoseUncapturableValueReference(*this, Loc, BD);
3390     }
3391     break;
3392   }
3393 
3394   case Decl::Function: {
3395     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3396       if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3397         type = Context.BuiltinFnTy;
3398         valueKind = VK_PRValue;
3399         break;
3400       }
3401     }
3402 
3403     const FunctionType *fty = type->castAs<FunctionType>();
3404 
3405     // If we're referring to a function with an __unknown_anytype
3406     // result type, make the entire expression __unknown_anytype.
3407     if (fty->getReturnType() == Context.UnknownAnyTy) {
3408       type = Context.UnknownAnyTy;
3409       valueKind = VK_PRValue;
3410       break;
3411     }
3412 
3413     // Functions are l-values in C++.
3414     if (getLangOpts().CPlusPlus) {
3415       valueKind = VK_LValue;
3416       break;
3417     }
3418 
3419     // C99 DR 316 says that, if a function type comes from a
3420     // function definition (without a prototype), that type is only
3421     // used for checking compatibility. Therefore, when referencing
3422     // the function, we pretend that we don't have the full function
3423     // type.
3424     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3425       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3426                                             fty->getExtInfo());
3427 
3428     // Functions are r-values in C.
3429     valueKind = VK_PRValue;
3430     break;
3431   }
3432 
3433   case Decl::CXXDeductionGuide:
3434     llvm_unreachable("building reference to deduction guide");
3435 
3436   case Decl::MSProperty:
3437   case Decl::MSGuid:
3438   case Decl::TemplateParamObject:
3439     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3440     // capture in OpenMP, or duplicated between host and device?
3441     valueKind = VK_LValue;
3442     break;
3443 
3444   case Decl::UnnamedGlobalConstant:
3445     valueKind = VK_LValue;
3446     break;
3447 
3448   case Decl::CXXMethod:
3449     // If we're referring to a method with an __unknown_anytype
3450     // result type, make the entire expression __unknown_anytype.
3451     // This should only be possible with a type written directly.
3452     if (const FunctionProtoType *proto =
3453             dyn_cast<FunctionProtoType>(VD->getType()))
3454       if (proto->getReturnType() == Context.UnknownAnyTy) {
3455         type = Context.UnknownAnyTy;
3456         valueKind = VK_PRValue;
3457         break;
3458       }
3459 
3460     // C++ methods are l-values if static, r-values if non-static.
3461     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3462       valueKind = VK_LValue;
3463       break;
3464     }
3465     LLVM_FALLTHROUGH;
3466 
3467   case Decl::CXXConversion:
3468   case Decl::CXXDestructor:
3469   case Decl::CXXConstructor:
3470     valueKind = VK_PRValue;
3471     break;
3472   }
3473 
3474   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3475                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3476                           TemplateArgs);
3477 }
3478 
3479 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3480                                     SmallString<32> &Target) {
3481   Target.resize(CharByteWidth * (Source.size() + 1));
3482   char *ResultPtr = &Target[0];
3483   const llvm::UTF8 *ErrorPtr;
3484   bool success =
3485       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3486   (void)success;
3487   assert(success);
3488   Target.resize(ResultPtr - &Target[0]);
3489 }
3490 
3491 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3492                                      PredefinedExpr::IdentKind IK) {
3493   // Pick the current block, lambda, captured statement or function.
3494   Decl *currentDecl = nullptr;
3495   if (const BlockScopeInfo *BSI = getCurBlock())
3496     currentDecl = BSI->TheDecl;
3497   else if (const LambdaScopeInfo *LSI = getCurLambda())
3498     currentDecl = LSI->CallOperator;
3499   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3500     currentDecl = CSI->TheCapturedDecl;
3501   else
3502     currentDecl = getCurFunctionOrMethodDecl();
3503 
3504   if (!currentDecl) {
3505     Diag(Loc, diag::ext_predef_outside_function);
3506     currentDecl = Context.getTranslationUnitDecl();
3507   }
3508 
3509   QualType ResTy;
3510   StringLiteral *SL = nullptr;
3511   if (cast<DeclContext>(currentDecl)->isDependentContext())
3512     ResTy = Context.DependentTy;
3513   else {
3514     // Pre-defined identifiers are of type char[x], where x is the length of
3515     // the string.
3516     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3517     unsigned Length = Str.length();
3518 
3519     llvm::APInt LengthI(32, Length + 1);
3520     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3521       ResTy =
3522           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3523       SmallString<32> RawChars;
3524       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3525                               Str, RawChars);
3526       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3527                                            ArrayType::Normal,
3528                                            /*IndexTypeQuals*/ 0);
3529       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3530                                  /*Pascal*/ false, ResTy, Loc);
3531     } else {
3532       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3533       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3534                                            ArrayType::Normal,
3535                                            /*IndexTypeQuals*/ 0);
3536       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3537                                  /*Pascal*/ false, ResTy, Loc);
3538     }
3539   }
3540 
3541   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3542 }
3543 
3544 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3545                                                SourceLocation LParen,
3546                                                SourceLocation RParen,
3547                                                TypeSourceInfo *TSI) {
3548   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3549 }
3550 
3551 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3552                                                SourceLocation LParen,
3553                                                SourceLocation RParen,
3554                                                ParsedType ParsedTy) {
3555   TypeSourceInfo *TSI = nullptr;
3556   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3557 
3558   if (Ty.isNull())
3559     return ExprError();
3560   if (!TSI)
3561     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3562 
3563   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3564 }
3565 
3566 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3567   PredefinedExpr::IdentKind IK;
3568 
3569   switch (Kind) {
3570   default: llvm_unreachable("Unknown simple primary expr!");
3571   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3572   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3573   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3574   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3575   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3576   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3577   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3578   }
3579 
3580   return BuildPredefinedExpr(Loc, IK);
3581 }
3582 
3583 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3584   SmallString<16> CharBuffer;
3585   bool Invalid = false;
3586   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3587   if (Invalid)
3588     return ExprError();
3589 
3590   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3591                             PP, Tok.getKind());
3592   if (Literal.hadError())
3593     return ExprError();
3594 
3595   QualType Ty;
3596   if (Literal.isWide())
3597     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3598   else if (Literal.isUTF8() && getLangOpts().Char8)
3599     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3600   else if (Literal.isUTF16())
3601     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3602   else if (Literal.isUTF32())
3603     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3604   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3605     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3606   else
3607     Ty = Context.CharTy;  // 'x' -> char in C++
3608 
3609   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3610   if (Literal.isWide())
3611     Kind = CharacterLiteral::Wide;
3612   else if (Literal.isUTF16())
3613     Kind = CharacterLiteral::UTF16;
3614   else if (Literal.isUTF32())
3615     Kind = CharacterLiteral::UTF32;
3616   else if (Literal.isUTF8())
3617     Kind = CharacterLiteral::UTF8;
3618 
3619   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3620                                              Tok.getLocation());
3621 
3622   if (Literal.getUDSuffix().empty())
3623     return Lit;
3624 
3625   // We're building a user-defined literal.
3626   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3627   SourceLocation UDSuffixLoc =
3628     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3629 
3630   // Make sure we're allowed user-defined literals here.
3631   if (!UDLScope)
3632     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3633 
3634   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3635   //   operator "" X (ch)
3636   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3637                                         Lit, Tok.getLocation());
3638 }
3639 
3640 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3641   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3642   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3643                                 Context.IntTy, Loc);
3644 }
3645 
3646 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3647                                   QualType Ty, SourceLocation Loc) {
3648   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3649 
3650   using llvm::APFloat;
3651   APFloat Val(Format);
3652 
3653   APFloat::opStatus result = Literal.GetFloatValue(Val);
3654 
3655   // Overflow is always an error, but underflow is only an error if
3656   // we underflowed to zero (APFloat reports denormals as underflow).
3657   if ((result & APFloat::opOverflow) ||
3658       ((result & APFloat::opUnderflow) && Val.isZero())) {
3659     unsigned diagnostic;
3660     SmallString<20> buffer;
3661     if (result & APFloat::opOverflow) {
3662       diagnostic = diag::warn_float_overflow;
3663       APFloat::getLargest(Format).toString(buffer);
3664     } else {
3665       diagnostic = diag::warn_float_underflow;
3666       APFloat::getSmallest(Format).toString(buffer);
3667     }
3668 
3669     S.Diag(Loc, diagnostic)
3670       << Ty
3671       << StringRef(buffer.data(), buffer.size());
3672   }
3673 
3674   bool isExact = (result == APFloat::opOK);
3675   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3676 }
3677 
3678 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3679   assert(E && "Invalid expression");
3680 
3681   if (E->isValueDependent())
3682     return false;
3683 
3684   QualType QT = E->getType();
3685   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3686     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3687     return true;
3688   }
3689 
3690   llvm::APSInt ValueAPS;
3691   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3692 
3693   if (R.isInvalid())
3694     return true;
3695 
3696   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3697   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3698     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3699         << toString(ValueAPS, 10) << ValueIsPositive;
3700     return true;
3701   }
3702 
3703   return false;
3704 }
3705 
3706 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3707   // Fast path for a single digit (which is quite common).  A single digit
3708   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3709   if (Tok.getLength() == 1) {
3710     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3711     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3712   }
3713 
3714   SmallString<128> SpellingBuffer;
3715   // NumericLiteralParser wants to overread by one character.  Add padding to
3716   // the buffer in case the token is copied to the buffer.  If getSpelling()
3717   // returns a StringRef to the memory buffer, it should have a null char at
3718   // the EOF, so it is also safe.
3719   SpellingBuffer.resize(Tok.getLength() + 1);
3720 
3721   // Get the spelling of the token, which eliminates trigraphs, etc.
3722   bool Invalid = false;
3723   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3724   if (Invalid)
3725     return ExprError();
3726 
3727   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3728                                PP.getSourceManager(), PP.getLangOpts(),
3729                                PP.getTargetInfo(), PP.getDiagnostics());
3730   if (Literal.hadError)
3731     return ExprError();
3732 
3733   if (Literal.hasUDSuffix()) {
3734     // We're building a user-defined literal.
3735     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3736     SourceLocation UDSuffixLoc =
3737       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3738 
3739     // Make sure we're allowed user-defined literals here.
3740     if (!UDLScope)
3741       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3742 
3743     QualType CookedTy;
3744     if (Literal.isFloatingLiteral()) {
3745       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3746       // long double, the literal is treated as a call of the form
3747       //   operator "" X (f L)
3748       CookedTy = Context.LongDoubleTy;
3749     } else {
3750       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3751       // unsigned long long, the literal is treated as a call of the form
3752       //   operator "" X (n ULL)
3753       CookedTy = Context.UnsignedLongLongTy;
3754     }
3755 
3756     DeclarationName OpName =
3757       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3758     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3759     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3760 
3761     SourceLocation TokLoc = Tok.getLocation();
3762 
3763     // Perform literal operator lookup to determine if we're building a raw
3764     // literal or a cooked one.
3765     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3766     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3767                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3768                                   /*AllowStringTemplatePack*/ false,
3769                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3770     case LOLR_ErrorNoDiagnostic:
3771       // Lookup failure for imaginary constants isn't fatal, there's still the
3772       // GNU extension producing _Complex types.
3773       break;
3774     case LOLR_Error:
3775       return ExprError();
3776     case LOLR_Cooked: {
3777       Expr *Lit;
3778       if (Literal.isFloatingLiteral()) {
3779         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3780       } else {
3781         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3782         if (Literal.GetIntegerValue(ResultVal))
3783           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3784               << /* Unsigned */ 1;
3785         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3786                                      Tok.getLocation());
3787       }
3788       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3789     }
3790 
3791     case LOLR_Raw: {
3792       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3793       // literal is treated as a call of the form
3794       //   operator "" X ("n")
3795       unsigned Length = Literal.getUDSuffixOffset();
3796       QualType StrTy = Context.getConstantArrayType(
3797           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3798           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3799       Expr *Lit = StringLiteral::Create(
3800           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3801           /*Pascal*/false, StrTy, &TokLoc, 1);
3802       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3803     }
3804 
3805     case LOLR_Template: {
3806       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3807       // template), L is treated as a call fo the form
3808       //   operator "" X <'c1', 'c2', ... 'ck'>()
3809       // where n is the source character sequence c1 c2 ... ck.
3810       TemplateArgumentListInfo ExplicitArgs;
3811       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3812       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3813       llvm::APSInt Value(CharBits, CharIsUnsigned);
3814       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3815         Value = TokSpelling[I];
3816         TemplateArgument Arg(Context, Value, Context.CharTy);
3817         TemplateArgumentLocInfo ArgInfo;
3818         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3819       }
3820       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3821                                       &ExplicitArgs);
3822     }
3823     case LOLR_StringTemplatePack:
3824       llvm_unreachable("unexpected literal operator lookup result");
3825     }
3826   }
3827 
3828   Expr *Res;
3829 
3830   if (Literal.isFixedPointLiteral()) {
3831     QualType Ty;
3832 
3833     if (Literal.isAccum) {
3834       if (Literal.isHalf) {
3835         Ty = Context.ShortAccumTy;
3836       } else if (Literal.isLong) {
3837         Ty = Context.LongAccumTy;
3838       } else {
3839         Ty = Context.AccumTy;
3840       }
3841     } else if (Literal.isFract) {
3842       if (Literal.isHalf) {
3843         Ty = Context.ShortFractTy;
3844       } else if (Literal.isLong) {
3845         Ty = Context.LongFractTy;
3846       } else {
3847         Ty = Context.FractTy;
3848       }
3849     }
3850 
3851     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3852 
3853     bool isSigned = !Literal.isUnsigned;
3854     unsigned scale = Context.getFixedPointScale(Ty);
3855     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3856 
3857     llvm::APInt Val(bit_width, 0, isSigned);
3858     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3859     bool ValIsZero = Val.isZero() && !Overflowed;
3860 
3861     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3862     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3863       // Clause 6.4.4 - The value of a constant shall be in the range of
3864       // representable values for its type, with exception for constants of a
3865       // fract type with a value of exactly 1; such a constant shall denote
3866       // the maximal value for the type.
3867       --Val;
3868     else if (Val.ugt(MaxVal) || Overflowed)
3869       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3870 
3871     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3872                                               Tok.getLocation(), scale);
3873   } else if (Literal.isFloatingLiteral()) {
3874     QualType Ty;
3875     if (Literal.isHalf){
3876       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3877         Ty = Context.HalfTy;
3878       else {
3879         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3880         return ExprError();
3881       }
3882     } else if (Literal.isFloat)
3883       Ty = Context.FloatTy;
3884     else if (Literal.isLong)
3885       Ty = Context.LongDoubleTy;
3886     else if (Literal.isFloat16)
3887       Ty = Context.Float16Ty;
3888     else if (Literal.isFloat128)
3889       Ty = Context.Float128Ty;
3890     else
3891       Ty = Context.DoubleTy;
3892 
3893     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3894 
3895     if (Ty == Context.DoubleTy) {
3896       if (getLangOpts().SinglePrecisionConstants) {
3897         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3898           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3899         }
3900       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3901                                              "cl_khr_fp64", getLangOpts())) {
3902         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3903         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3904             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3905         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3906       }
3907     }
3908   } else if (!Literal.isIntegerLiteral()) {
3909     return ExprError();
3910   } else {
3911     QualType Ty;
3912 
3913     // 'long long' is a C99 or C++11 feature.
3914     if (!getLangOpts().C99 && Literal.isLongLong) {
3915       if (getLangOpts().CPlusPlus)
3916         Diag(Tok.getLocation(),
3917              getLangOpts().CPlusPlus11 ?
3918              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3919       else
3920         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3921     }
3922 
3923     // 'z/uz' literals are a C++2b feature.
3924     if (Literal.isSizeT)
3925       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3926                                   ? getLangOpts().CPlusPlus2b
3927                                         ? diag::warn_cxx20_compat_size_t_suffix
3928                                         : diag::ext_cxx2b_size_t_suffix
3929                                   : diag::err_cxx2b_size_t_suffix);
3930 
3931     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3932     // but we do not currently support the suffix in C++ mode because it's not
3933     // entirely clear whether WG21 will prefer this suffix to return a library
3934     // type such as std::bit_int instead of returning a _BitInt.
3935     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3936       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3937                                      ? diag::warn_c2x_compat_bitint_suffix
3938                                      : diag::ext_c2x_bitint_suffix);
3939 
3940     // Get the value in the widest-possible width. What is "widest" depends on
3941     // whether the literal is a bit-precise integer or not. For a bit-precise
3942     // integer type, try to scan the source to determine how many bits are
3943     // needed to represent the value. This may seem a bit expensive, but trying
3944     // to get the integer value from an overly-wide APInt is *extremely*
3945     // expensive, so the naive approach of assuming
3946     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3947     unsigned BitsNeeded =
3948         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3949                                Literal.getLiteralDigits(), Literal.getRadix())
3950                          : Context.getTargetInfo().getIntMaxTWidth();
3951     llvm::APInt ResultVal(BitsNeeded, 0);
3952 
3953     if (Literal.GetIntegerValue(ResultVal)) {
3954       // If this value didn't fit into uintmax_t, error and force to ull.
3955       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3956           << /* Unsigned */ 1;
3957       Ty = Context.UnsignedLongLongTy;
3958       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3959              "long long is not intmax_t?");
3960     } else {
3961       // If this value fits into a ULL, try to figure out what else it fits into
3962       // according to the rules of C99 6.4.4.1p5.
3963 
3964       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3965       // be an unsigned int.
3966       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3967 
3968       // Check from smallest to largest, picking the smallest type we can.
3969       unsigned Width = 0;
3970 
3971       // Microsoft specific integer suffixes are explicitly sized.
3972       if (Literal.MicrosoftInteger) {
3973         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3974           Width = 8;
3975           Ty = Context.CharTy;
3976         } else {
3977           Width = Literal.MicrosoftInteger;
3978           Ty = Context.getIntTypeForBitwidth(Width,
3979                                              /*Signed=*/!Literal.isUnsigned);
3980         }
3981       }
3982 
3983       // Bit-precise integer literals are automagically-sized based on the
3984       // width required by the literal.
3985       if (Literal.isBitInt) {
3986         // The signed version has one more bit for the sign value. There are no
3987         // zero-width bit-precise integers, even if the literal value is 0.
3988         Width = std::max(ResultVal.getActiveBits(), 1u) +
3989                 (Literal.isUnsigned ? 0u : 1u);
3990 
3991         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3992         // and reset the type to the largest supported width.
3993         unsigned int MaxBitIntWidth =
3994             Context.getTargetInfo().getMaxBitIntWidth();
3995         if (Width > MaxBitIntWidth) {
3996           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3997               << Literal.isUnsigned;
3998           Width = MaxBitIntWidth;
3999         }
4000 
4001         // Reset the result value to the smaller APInt and select the correct
4002         // type to be used. Note, we zext even for signed values because the
4003         // literal itself is always an unsigned value (a preceeding - is a
4004         // unary operator, not part of the literal).
4005         ResultVal = ResultVal.zextOrTrunc(Width);
4006         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4007       }
4008 
4009       // Check C++2b size_t literals.
4010       if (Literal.isSizeT) {
4011         assert(!Literal.MicrosoftInteger &&
4012                "size_t literals can't be Microsoft literals");
4013         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4014             Context.getTargetInfo().getSizeType());
4015 
4016         // Does it fit in size_t?
4017         if (ResultVal.isIntN(SizeTSize)) {
4018           // Does it fit in ssize_t?
4019           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4020             Ty = Context.getSignedSizeType();
4021           else if (AllowUnsigned)
4022             Ty = Context.getSizeType();
4023           Width = SizeTSize;
4024         }
4025       }
4026 
4027       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4028           !Literal.isSizeT) {
4029         // Are int/unsigned possibilities?
4030         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4031 
4032         // Does it fit in a unsigned int?
4033         if (ResultVal.isIntN(IntSize)) {
4034           // Does it fit in a signed int?
4035           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4036             Ty = Context.IntTy;
4037           else if (AllowUnsigned)
4038             Ty = Context.UnsignedIntTy;
4039           Width = IntSize;
4040         }
4041       }
4042 
4043       // Are long/unsigned long possibilities?
4044       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4045         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4046 
4047         // Does it fit in a unsigned long?
4048         if (ResultVal.isIntN(LongSize)) {
4049           // Does it fit in a signed long?
4050           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4051             Ty = Context.LongTy;
4052           else if (AllowUnsigned)
4053             Ty = Context.UnsignedLongTy;
4054           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4055           // is compatible.
4056           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4057             const unsigned LongLongSize =
4058                 Context.getTargetInfo().getLongLongWidth();
4059             Diag(Tok.getLocation(),
4060                  getLangOpts().CPlusPlus
4061                      ? Literal.isLong
4062                            ? diag::warn_old_implicitly_unsigned_long_cxx
4063                            : /*C++98 UB*/ diag::
4064                                  ext_old_implicitly_unsigned_long_cxx
4065                      : diag::warn_old_implicitly_unsigned_long)
4066                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4067                                             : /*will be ill-formed*/ 1);
4068             Ty = Context.UnsignedLongTy;
4069           }
4070           Width = LongSize;
4071         }
4072       }
4073 
4074       // Check long long if needed.
4075       if (Ty.isNull() && !Literal.isSizeT) {
4076         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4077 
4078         // Does it fit in a unsigned long long?
4079         if (ResultVal.isIntN(LongLongSize)) {
4080           // Does it fit in a signed long long?
4081           // To be compatible with MSVC, hex integer literals ending with the
4082           // LL or i64 suffix are always signed in Microsoft mode.
4083           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4084               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4085             Ty = Context.LongLongTy;
4086           else if (AllowUnsigned)
4087             Ty = Context.UnsignedLongLongTy;
4088           Width = LongLongSize;
4089         }
4090       }
4091 
4092       // If we still couldn't decide a type, we either have 'size_t' literal
4093       // that is out of range, or a decimal literal that does not fit in a
4094       // signed long long and has no U suffix.
4095       if (Ty.isNull()) {
4096         if (Literal.isSizeT)
4097           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4098               << Literal.isUnsigned;
4099         else
4100           Diag(Tok.getLocation(),
4101                diag::ext_integer_literal_too_large_for_signed);
4102         Ty = Context.UnsignedLongLongTy;
4103         Width = Context.getTargetInfo().getLongLongWidth();
4104       }
4105 
4106       if (ResultVal.getBitWidth() != Width)
4107         ResultVal = ResultVal.trunc(Width);
4108     }
4109     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4110   }
4111 
4112   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4113   if (Literal.isImaginary) {
4114     Res = new (Context) ImaginaryLiteral(Res,
4115                                         Context.getComplexType(Res->getType()));
4116 
4117     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4118   }
4119   return Res;
4120 }
4121 
4122 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4123   assert(E && "ActOnParenExpr() missing expr");
4124   QualType ExprTy = E->getType();
4125   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4126       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4127     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4128   return new (Context) ParenExpr(L, R, E);
4129 }
4130 
4131 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4132                                          SourceLocation Loc,
4133                                          SourceRange ArgRange) {
4134   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4135   // scalar or vector data type argument..."
4136   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4137   // type (C99 6.2.5p18) or void.
4138   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4139     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4140       << T << ArgRange;
4141     return true;
4142   }
4143 
4144   assert((T->isVoidType() || !T->isIncompleteType()) &&
4145          "Scalar types should always be complete");
4146   return false;
4147 }
4148 
4149 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4150                                            SourceLocation Loc,
4151                                            SourceRange ArgRange,
4152                                            UnaryExprOrTypeTrait TraitKind) {
4153   // Invalid types must be hard errors for SFINAE in C++.
4154   if (S.LangOpts.CPlusPlus)
4155     return true;
4156 
4157   // C99 6.5.3.4p1:
4158   if (T->isFunctionType() &&
4159       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4160        TraitKind == UETT_PreferredAlignOf)) {
4161     // sizeof(function)/alignof(function) is allowed as an extension.
4162     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4163         << getTraitSpelling(TraitKind) << ArgRange;
4164     return false;
4165   }
4166 
4167   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4168   // this is an error (OpenCL v1.1 s6.3.k)
4169   if (T->isVoidType()) {
4170     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4171                                         : diag::ext_sizeof_alignof_void_type;
4172     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4173     return false;
4174   }
4175 
4176   return true;
4177 }
4178 
4179 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4180                                              SourceLocation Loc,
4181                                              SourceRange ArgRange,
4182                                              UnaryExprOrTypeTrait TraitKind) {
4183   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4184   // runtime doesn't allow it.
4185   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4186     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4187       << T << (TraitKind == UETT_SizeOf)
4188       << ArgRange;
4189     return true;
4190   }
4191 
4192   return false;
4193 }
4194 
4195 /// Check whether E is a pointer from a decayed array type (the decayed
4196 /// pointer type is equal to T) and emit a warning if it is.
4197 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4198                                      Expr *E) {
4199   // Don't warn if the operation changed the type.
4200   if (T != E->getType())
4201     return;
4202 
4203   // Now look for array decays.
4204   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4205   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4206     return;
4207 
4208   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4209                                              << ICE->getType()
4210                                              << ICE->getSubExpr()->getType();
4211 }
4212 
4213 /// Check the constraints on expression operands to unary type expression
4214 /// and type traits.
4215 ///
4216 /// Completes any types necessary and validates the constraints on the operand
4217 /// expression. The logic mostly mirrors the type-based overload, but may modify
4218 /// the expression as it completes the type for that expression through template
4219 /// instantiation, etc.
4220 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4221                                             UnaryExprOrTypeTrait ExprKind) {
4222   QualType ExprTy = E->getType();
4223   assert(!ExprTy->isReferenceType());
4224 
4225   bool IsUnevaluatedOperand =
4226       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4227        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4228   if (IsUnevaluatedOperand) {
4229     ExprResult Result = CheckUnevaluatedOperand(E);
4230     if (Result.isInvalid())
4231       return true;
4232     E = Result.get();
4233   }
4234 
4235   // The operand for sizeof and alignof is in an unevaluated expression context,
4236   // so side effects could result in unintended consequences.
4237   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4238   // used to build SFINAE gadgets.
4239   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4240   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4241       !E->isInstantiationDependent() &&
4242       E->HasSideEffects(Context, false))
4243     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4244 
4245   if (ExprKind == UETT_VecStep)
4246     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4247                                         E->getSourceRange());
4248 
4249   // Explicitly list some types as extensions.
4250   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4251                                       E->getSourceRange(), ExprKind))
4252     return false;
4253 
4254   // 'alignof' applied to an expression only requires the base element type of
4255   // the expression to be complete. 'sizeof' requires the expression's type to
4256   // be complete (and will attempt to complete it if it's an array of unknown
4257   // bound).
4258   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4259     if (RequireCompleteSizedType(
4260             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4261             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4262             getTraitSpelling(ExprKind), E->getSourceRange()))
4263       return true;
4264   } else {
4265     if (RequireCompleteSizedExprType(
4266             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4267             getTraitSpelling(ExprKind), E->getSourceRange()))
4268       return true;
4269   }
4270 
4271   // Completing the expression's type may have changed it.
4272   ExprTy = E->getType();
4273   assert(!ExprTy->isReferenceType());
4274 
4275   if (ExprTy->isFunctionType()) {
4276     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4277         << getTraitSpelling(ExprKind) << E->getSourceRange();
4278     return true;
4279   }
4280 
4281   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4282                                        E->getSourceRange(), ExprKind))
4283     return true;
4284 
4285   if (ExprKind == UETT_SizeOf) {
4286     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4287       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4288         QualType OType = PVD->getOriginalType();
4289         QualType Type = PVD->getType();
4290         if (Type->isPointerType() && OType->isArrayType()) {
4291           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4292             << Type << OType;
4293           Diag(PVD->getLocation(), diag::note_declared_at);
4294         }
4295       }
4296     }
4297 
4298     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4299     // decays into a pointer and returns an unintended result. This is most
4300     // likely a typo for "sizeof(array) op x".
4301     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4302       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4303                                BO->getLHS());
4304       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4305                                BO->getRHS());
4306     }
4307   }
4308 
4309   return false;
4310 }
4311 
4312 /// Check the constraints on operands to unary expression and type
4313 /// traits.
4314 ///
4315 /// This will complete any types necessary, and validate the various constraints
4316 /// on those operands.
4317 ///
4318 /// The UsualUnaryConversions() function is *not* called by this routine.
4319 /// C99 6.3.2.1p[2-4] all state:
4320 ///   Except when it is the operand of the sizeof operator ...
4321 ///
4322 /// C++ [expr.sizeof]p4
4323 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4324 ///   standard conversions are not applied to the operand of sizeof.
4325 ///
4326 /// This policy is followed for all of the unary trait expressions.
4327 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4328                                             SourceLocation OpLoc,
4329                                             SourceRange ExprRange,
4330                                             UnaryExprOrTypeTrait ExprKind) {
4331   if (ExprType->isDependentType())
4332     return false;
4333 
4334   // C++ [expr.sizeof]p2:
4335   //     When applied to a reference or a reference type, the result
4336   //     is the size of the referenced type.
4337   // C++11 [expr.alignof]p3:
4338   //     When alignof is applied to a reference type, the result
4339   //     shall be the alignment of the referenced type.
4340   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4341     ExprType = Ref->getPointeeType();
4342 
4343   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4344   //   When alignof or _Alignof is applied to an array type, the result
4345   //   is the alignment of the element type.
4346   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4347       ExprKind == UETT_OpenMPRequiredSimdAlign)
4348     ExprType = Context.getBaseElementType(ExprType);
4349 
4350   if (ExprKind == UETT_VecStep)
4351     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4352 
4353   // Explicitly list some types as extensions.
4354   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4355                                       ExprKind))
4356     return false;
4357 
4358   if (RequireCompleteSizedType(
4359           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4360           getTraitSpelling(ExprKind), ExprRange))
4361     return true;
4362 
4363   if (ExprType->isFunctionType()) {
4364     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4365         << getTraitSpelling(ExprKind) << ExprRange;
4366     return true;
4367   }
4368 
4369   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4370                                        ExprKind))
4371     return true;
4372 
4373   return false;
4374 }
4375 
4376 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4377   // Cannot know anything else if the expression is dependent.
4378   if (E->isTypeDependent())
4379     return false;
4380 
4381   if (E->getObjectKind() == OK_BitField) {
4382     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4383        << 1 << E->getSourceRange();
4384     return true;
4385   }
4386 
4387   ValueDecl *D = nullptr;
4388   Expr *Inner = E->IgnoreParens();
4389   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4390     D = DRE->getDecl();
4391   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4392     D = ME->getMemberDecl();
4393   }
4394 
4395   // If it's a field, require the containing struct to have a
4396   // complete definition so that we can compute the layout.
4397   //
4398   // This can happen in C++11 onwards, either by naming the member
4399   // in a way that is not transformed into a member access expression
4400   // (in an unevaluated operand, for instance), or by naming the member
4401   // in a trailing-return-type.
4402   //
4403   // For the record, since __alignof__ on expressions is a GCC
4404   // extension, GCC seems to permit this but always gives the
4405   // nonsensical answer 0.
4406   //
4407   // We don't really need the layout here --- we could instead just
4408   // directly check for all the appropriate alignment-lowing
4409   // attributes --- but that would require duplicating a lot of
4410   // logic that just isn't worth duplicating for such a marginal
4411   // use-case.
4412   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4413     // Fast path this check, since we at least know the record has a
4414     // definition if we can find a member of it.
4415     if (!FD->getParent()->isCompleteDefinition()) {
4416       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4417         << E->getSourceRange();
4418       return true;
4419     }
4420 
4421     // Otherwise, if it's a field, and the field doesn't have
4422     // reference type, then it must have a complete type (or be a
4423     // flexible array member, which we explicitly want to
4424     // white-list anyway), which makes the following checks trivial.
4425     if (!FD->getType()->isReferenceType())
4426       return false;
4427   }
4428 
4429   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4430 }
4431 
4432 bool Sema::CheckVecStepExpr(Expr *E) {
4433   E = E->IgnoreParens();
4434 
4435   // Cannot know anything else if the expression is dependent.
4436   if (E->isTypeDependent())
4437     return false;
4438 
4439   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4440 }
4441 
4442 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4443                                         CapturingScopeInfo *CSI) {
4444   assert(T->isVariablyModifiedType());
4445   assert(CSI != nullptr);
4446 
4447   // We're going to walk down into the type and look for VLA expressions.
4448   do {
4449     const Type *Ty = T.getTypePtr();
4450     switch (Ty->getTypeClass()) {
4451 #define TYPE(Class, Base)
4452 #define ABSTRACT_TYPE(Class, Base)
4453 #define NON_CANONICAL_TYPE(Class, Base)
4454 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4455 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4456 #include "clang/AST/TypeNodes.inc"
4457       T = QualType();
4458       break;
4459     // These types are never variably-modified.
4460     case Type::Builtin:
4461     case Type::Complex:
4462     case Type::Vector:
4463     case Type::ExtVector:
4464     case Type::ConstantMatrix:
4465     case Type::Record:
4466     case Type::Enum:
4467     case Type::Elaborated:
4468     case Type::TemplateSpecialization:
4469     case Type::ObjCObject:
4470     case Type::ObjCInterface:
4471     case Type::ObjCObjectPointer:
4472     case Type::ObjCTypeParam:
4473     case Type::Pipe:
4474     case Type::BitInt:
4475       llvm_unreachable("type class is never variably-modified!");
4476     case Type::Adjusted:
4477       T = cast<AdjustedType>(Ty)->getOriginalType();
4478       break;
4479     case Type::Decayed:
4480       T = cast<DecayedType>(Ty)->getPointeeType();
4481       break;
4482     case Type::Pointer:
4483       T = cast<PointerType>(Ty)->getPointeeType();
4484       break;
4485     case Type::BlockPointer:
4486       T = cast<BlockPointerType>(Ty)->getPointeeType();
4487       break;
4488     case Type::LValueReference:
4489     case Type::RValueReference:
4490       T = cast<ReferenceType>(Ty)->getPointeeType();
4491       break;
4492     case Type::MemberPointer:
4493       T = cast<MemberPointerType>(Ty)->getPointeeType();
4494       break;
4495     case Type::ConstantArray:
4496     case Type::IncompleteArray:
4497       // Losing element qualification here is fine.
4498       T = cast<ArrayType>(Ty)->getElementType();
4499       break;
4500     case Type::VariableArray: {
4501       // Losing element qualification here is fine.
4502       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4503 
4504       // Unknown size indication requires no size computation.
4505       // Otherwise, evaluate and record it.
4506       auto Size = VAT->getSizeExpr();
4507       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4508           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4509         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4510 
4511       T = VAT->getElementType();
4512       break;
4513     }
4514     case Type::FunctionProto:
4515     case Type::FunctionNoProto:
4516       T = cast<FunctionType>(Ty)->getReturnType();
4517       break;
4518     case Type::Paren:
4519     case Type::TypeOf:
4520     case Type::UnaryTransform:
4521     case Type::Attributed:
4522     case Type::BTFTagAttributed:
4523     case Type::SubstTemplateTypeParm:
4524     case Type::MacroQualified:
4525       // Keep walking after single level desugaring.
4526       T = T.getSingleStepDesugaredType(Context);
4527       break;
4528     case Type::Typedef:
4529       T = cast<TypedefType>(Ty)->desugar();
4530       break;
4531     case Type::Decltype:
4532       T = cast<DecltypeType>(Ty)->desugar();
4533       break;
4534     case Type::Using:
4535       T = cast<UsingType>(Ty)->desugar();
4536       break;
4537     case Type::Auto:
4538     case Type::DeducedTemplateSpecialization:
4539       T = cast<DeducedType>(Ty)->getDeducedType();
4540       break;
4541     case Type::TypeOfExpr:
4542       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4543       break;
4544     case Type::Atomic:
4545       T = cast<AtomicType>(Ty)->getValueType();
4546       break;
4547     }
4548   } while (!T.isNull() && T->isVariablyModifiedType());
4549 }
4550 
4551 /// Build a sizeof or alignof expression given a type operand.
4552 ExprResult
4553 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4554                                      SourceLocation OpLoc,
4555                                      UnaryExprOrTypeTrait ExprKind,
4556                                      SourceRange R) {
4557   if (!TInfo)
4558     return ExprError();
4559 
4560   QualType T = TInfo->getType();
4561 
4562   if (!T->isDependentType() &&
4563       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4564     return ExprError();
4565 
4566   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4567     if (auto *TT = T->getAs<TypedefType>()) {
4568       for (auto I = FunctionScopes.rbegin(),
4569                 E = std::prev(FunctionScopes.rend());
4570            I != E; ++I) {
4571         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4572         if (CSI == nullptr)
4573           break;
4574         DeclContext *DC = nullptr;
4575         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4576           DC = LSI->CallOperator;
4577         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4578           DC = CRSI->TheCapturedDecl;
4579         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4580           DC = BSI->TheDecl;
4581         if (DC) {
4582           if (DC->containsDecl(TT->getDecl()))
4583             break;
4584           captureVariablyModifiedType(Context, T, CSI);
4585         }
4586       }
4587     }
4588   }
4589 
4590   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4591   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4592       TInfo->getType()->isVariablyModifiedType())
4593     TInfo = TransformToPotentiallyEvaluated(TInfo);
4594 
4595   return new (Context) UnaryExprOrTypeTraitExpr(
4596       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4597 }
4598 
4599 /// Build a sizeof or alignof expression given an expression
4600 /// operand.
4601 ExprResult
4602 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4603                                      UnaryExprOrTypeTrait ExprKind) {
4604   ExprResult PE = CheckPlaceholderExpr(E);
4605   if (PE.isInvalid())
4606     return ExprError();
4607 
4608   E = PE.get();
4609 
4610   // Verify that the operand is valid.
4611   bool isInvalid = false;
4612   if (E->isTypeDependent()) {
4613     // Delay type-checking for type-dependent expressions.
4614   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4615     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4616   } else if (ExprKind == UETT_VecStep) {
4617     isInvalid = CheckVecStepExpr(E);
4618   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4619       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4620       isInvalid = true;
4621   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4622     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4623     isInvalid = true;
4624   } else {
4625     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4626   }
4627 
4628   if (isInvalid)
4629     return ExprError();
4630 
4631   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4632     PE = TransformToPotentiallyEvaluated(E);
4633     if (PE.isInvalid()) return ExprError();
4634     E = PE.get();
4635   }
4636 
4637   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4638   return new (Context) UnaryExprOrTypeTraitExpr(
4639       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4640 }
4641 
4642 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4643 /// expr and the same for @c alignof and @c __alignof
4644 /// Note that the ArgRange is invalid if isType is false.
4645 ExprResult
4646 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4647                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4648                                     void *TyOrEx, SourceRange ArgRange) {
4649   // If error parsing type, ignore.
4650   if (!TyOrEx) return ExprError();
4651 
4652   if (IsType) {
4653     TypeSourceInfo *TInfo;
4654     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4655     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4656   }
4657 
4658   Expr *ArgEx = (Expr *)TyOrEx;
4659   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4660   return Result;
4661 }
4662 
4663 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4664                                      bool IsReal) {
4665   if (V.get()->isTypeDependent())
4666     return S.Context.DependentTy;
4667 
4668   // _Real and _Imag are only l-values for normal l-values.
4669   if (V.get()->getObjectKind() != OK_Ordinary) {
4670     V = S.DefaultLvalueConversion(V.get());
4671     if (V.isInvalid())
4672       return QualType();
4673   }
4674 
4675   // These operators return the element type of a complex type.
4676   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4677     return CT->getElementType();
4678 
4679   // Otherwise they pass through real integer and floating point types here.
4680   if (V.get()->getType()->isArithmeticType())
4681     return V.get()->getType();
4682 
4683   // Test for placeholders.
4684   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4685   if (PR.isInvalid()) return QualType();
4686   if (PR.get() != V.get()) {
4687     V = PR;
4688     return CheckRealImagOperand(S, V, Loc, IsReal);
4689   }
4690 
4691   // Reject anything else.
4692   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4693     << (IsReal ? "__real" : "__imag");
4694   return QualType();
4695 }
4696 
4697 
4698 
4699 ExprResult
4700 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4701                           tok::TokenKind Kind, Expr *Input) {
4702   UnaryOperatorKind Opc;
4703   switch (Kind) {
4704   default: llvm_unreachable("Unknown unary op!");
4705   case tok::plusplus:   Opc = UO_PostInc; break;
4706   case tok::minusminus: Opc = UO_PostDec; break;
4707   }
4708 
4709   // Since this might is a postfix expression, get rid of ParenListExprs.
4710   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4711   if (Result.isInvalid()) return ExprError();
4712   Input = Result.get();
4713 
4714   return BuildUnaryOp(S, OpLoc, Opc, Input);
4715 }
4716 
4717 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4718 ///
4719 /// \return true on error
4720 static bool checkArithmeticOnObjCPointer(Sema &S,
4721                                          SourceLocation opLoc,
4722                                          Expr *op) {
4723   assert(op->getType()->isObjCObjectPointerType());
4724   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4725       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4726     return false;
4727 
4728   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4729     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4730     << op->getSourceRange();
4731   return true;
4732 }
4733 
4734 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4735   auto *BaseNoParens = Base->IgnoreParens();
4736   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4737     return MSProp->getPropertyDecl()->getType()->isArrayType();
4738   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4739 }
4740 
4741 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4742 // Typically this is DependentTy, but can sometimes be more precise.
4743 //
4744 // There are cases when we could determine a non-dependent type:
4745 //  - LHS and RHS may have non-dependent types despite being type-dependent
4746 //    (e.g. unbounded array static members of the current instantiation)
4747 //  - one may be a dependent-sized array with known element type
4748 //  - one may be a dependent-typed valid index (enum in current instantiation)
4749 //
4750 // We *always* return a dependent type, in such cases it is DependentTy.
4751 // This avoids creating type-dependent expressions with non-dependent types.
4752 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4753 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4754                                                const ASTContext &Ctx) {
4755   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4756   QualType LTy = LHS->getType(), RTy = RHS->getType();
4757   QualType Result = Ctx.DependentTy;
4758   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4759     if (const PointerType *PT = LTy->getAs<PointerType>())
4760       Result = PT->getPointeeType();
4761     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4762       Result = AT->getElementType();
4763   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4764     if (const PointerType *PT = RTy->getAs<PointerType>())
4765       Result = PT->getPointeeType();
4766     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4767       Result = AT->getElementType();
4768   }
4769   // Ensure we return a dependent type.
4770   return Result->isDependentType() ? Result : Ctx.DependentTy;
4771 }
4772 
4773 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4774 
4775 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4776                                          SourceLocation lbLoc,
4777                                          MultiExprArg ArgExprs,
4778                                          SourceLocation rbLoc) {
4779 
4780   if (base && !base->getType().isNull() &&
4781       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4782     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4783                                     SourceLocation(), /*Length*/ nullptr,
4784                                     /*Stride=*/nullptr, rbLoc);
4785 
4786   // Since this might be a postfix expression, get rid of ParenListExprs.
4787   if (isa<ParenListExpr>(base)) {
4788     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4789     if (result.isInvalid())
4790       return ExprError();
4791     base = result.get();
4792   }
4793 
4794   // Check if base and idx form a MatrixSubscriptExpr.
4795   //
4796   // Helper to check for comma expressions, which are not allowed as indices for
4797   // matrix subscript expressions.
4798   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4799     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4800       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4801           << SourceRange(base->getBeginLoc(), rbLoc);
4802       return true;
4803     }
4804     return false;
4805   };
4806   // The matrix subscript operator ([][])is considered a single operator.
4807   // Separating the index expressions by parenthesis is not allowed.
4808   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4809       !isa<MatrixSubscriptExpr>(base)) {
4810     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4811         << SourceRange(base->getBeginLoc(), rbLoc);
4812     return ExprError();
4813   }
4814   // If the base is a MatrixSubscriptExpr, try to create a new
4815   // MatrixSubscriptExpr.
4816   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4817   if (matSubscriptE) {
4818     assert(ArgExprs.size() == 1);
4819     if (CheckAndReportCommaError(ArgExprs.front()))
4820       return ExprError();
4821 
4822     assert(matSubscriptE->isIncomplete() &&
4823            "base has to be an incomplete matrix subscript");
4824     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4825                                             matSubscriptE->getRowIdx(),
4826                                             ArgExprs.front(), rbLoc);
4827   }
4828 
4829   // Handle any non-overload placeholder types in the base and index
4830   // expressions.  We can't handle overloads here because the other
4831   // operand might be an overloadable type, in which case the overload
4832   // resolution for the operator overload should get the first crack
4833   // at the overload.
4834   bool IsMSPropertySubscript = false;
4835   if (base->getType()->isNonOverloadPlaceholderType()) {
4836     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4837     if (!IsMSPropertySubscript) {
4838       ExprResult result = CheckPlaceholderExpr(base);
4839       if (result.isInvalid())
4840         return ExprError();
4841       base = result.get();
4842     }
4843   }
4844 
4845   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4846   if (base->getType()->isMatrixType()) {
4847     assert(ArgExprs.size() == 1);
4848     if (CheckAndReportCommaError(ArgExprs.front()))
4849       return ExprError();
4850 
4851     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4852                                             rbLoc);
4853   }
4854 
4855   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4856     Expr *idx = ArgExprs[0];
4857     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4858         (isa<CXXOperatorCallExpr>(idx) &&
4859          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4860       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4861           << SourceRange(base->getBeginLoc(), rbLoc);
4862     }
4863   }
4864 
4865   if (ArgExprs.size() == 1 &&
4866       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4867     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4868     if (result.isInvalid())
4869       return ExprError();
4870     ArgExprs[0] = result.get();
4871   } else {
4872     if (checkArgsForPlaceholders(*this, ArgExprs))
4873       return ExprError();
4874   }
4875 
4876   // Build an unanalyzed expression if either operand is type-dependent.
4877   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4878       (base->isTypeDependent() ||
4879        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4880     return new (Context) ArraySubscriptExpr(
4881         base, ArgExprs.front(),
4882         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4883         VK_LValue, OK_Ordinary, rbLoc);
4884   }
4885 
4886   // MSDN, property (C++)
4887   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4888   // This attribute can also be used in the declaration of an empty array in a
4889   // class or structure definition. For example:
4890   // __declspec(property(get=GetX, put=PutX)) int x[];
4891   // The above statement indicates that x[] can be used with one or more array
4892   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4893   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4894   if (IsMSPropertySubscript) {
4895     assert(ArgExprs.size() == 1);
4896     // Build MS property subscript expression if base is MS property reference
4897     // or MS property subscript.
4898     return new (Context)
4899         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4900                                 VK_LValue, OK_Ordinary, rbLoc);
4901   }
4902 
4903   // Use C++ overloaded-operator rules if either operand has record
4904   // type.  The spec says to do this if either type is *overloadable*,
4905   // but enum types can't declare subscript operators or conversion
4906   // operators, so there's nothing interesting for overload resolution
4907   // to do if there aren't any record types involved.
4908   //
4909   // ObjC pointers have their own subscripting logic that is not tied
4910   // to overload resolution and so should not take this path.
4911   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4912       ((base->getType()->isRecordType() ||
4913         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4914     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4915   }
4916 
4917   ExprResult Res =
4918       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4919 
4920   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4921     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4922 
4923   return Res;
4924 }
4925 
4926 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4927   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4928   InitializationKind Kind =
4929       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4930   InitializationSequence InitSeq(*this, Entity, Kind, E);
4931   return InitSeq.Perform(*this, Entity, Kind, E);
4932 }
4933 
4934 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4935                                                   Expr *ColumnIdx,
4936                                                   SourceLocation RBLoc) {
4937   ExprResult BaseR = CheckPlaceholderExpr(Base);
4938   if (BaseR.isInvalid())
4939     return BaseR;
4940   Base = BaseR.get();
4941 
4942   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4943   if (RowR.isInvalid())
4944     return RowR;
4945   RowIdx = RowR.get();
4946 
4947   if (!ColumnIdx)
4948     return new (Context) MatrixSubscriptExpr(
4949         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4950 
4951   // Build an unanalyzed expression if any of the operands is type-dependent.
4952   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4953       ColumnIdx->isTypeDependent())
4954     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4955                                              Context.DependentTy, RBLoc);
4956 
4957   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4958   if (ColumnR.isInvalid())
4959     return ColumnR;
4960   ColumnIdx = ColumnR.get();
4961 
4962   // Check that IndexExpr is an integer expression. If it is a constant
4963   // expression, check that it is less than Dim (= the number of elements in the
4964   // corresponding dimension).
4965   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4966                           bool IsColumnIdx) -> Expr * {
4967     if (!IndexExpr->getType()->isIntegerType() &&
4968         !IndexExpr->isTypeDependent()) {
4969       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4970           << IsColumnIdx;
4971       return nullptr;
4972     }
4973 
4974     if (Optional<llvm::APSInt> Idx =
4975             IndexExpr->getIntegerConstantExpr(Context)) {
4976       if ((*Idx < 0 || *Idx >= Dim)) {
4977         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4978             << IsColumnIdx << Dim;
4979         return nullptr;
4980       }
4981     }
4982 
4983     ExprResult ConvExpr =
4984         tryConvertExprToType(IndexExpr, Context.getSizeType());
4985     assert(!ConvExpr.isInvalid() &&
4986            "should be able to convert any integer type to size type");
4987     return ConvExpr.get();
4988   };
4989 
4990   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4991   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4992   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4993   if (!RowIdx || !ColumnIdx)
4994     return ExprError();
4995 
4996   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4997                                            MTy->getElementType(), RBLoc);
4998 }
4999 
5000 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5001   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5002   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5003 
5004   // For expressions like `&(*s).b`, the base is recorded and what should be
5005   // checked.
5006   const MemberExpr *Member = nullptr;
5007   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5008     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5009 
5010   LastRecord.PossibleDerefs.erase(StrippedExpr);
5011 }
5012 
5013 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5014   if (isUnevaluatedContext())
5015     return;
5016 
5017   QualType ResultTy = E->getType();
5018   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5019 
5020   // Bail if the element is an array since it is not memory access.
5021   if (isa<ArrayType>(ResultTy))
5022     return;
5023 
5024   if (ResultTy->hasAttr(attr::NoDeref)) {
5025     LastRecord.PossibleDerefs.insert(E);
5026     return;
5027   }
5028 
5029   // Check if the base type is a pointer to a member access of a struct
5030   // marked with noderef.
5031   const Expr *Base = E->getBase();
5032   QualType BaseTy = Base->getType();
5033   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5034     // Not a pointer access
5035     return;
5036 
5037   const MemberExpr *Member = nullptr;
5038   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5039          Member->isArrow())
5040     Base = Member->getBase();
5041 
5042   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5043     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5044       LastRecord.PossibleDerefs.insert(E);
5045   }
5046 }
5047 
5048 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5049                                           Expr *LowerBound,
5050                                           SourceLocation ColonLocFirst,
5051                                           SourceLocation ColonLocSecond,
5052                                           Expr *Length, Expr *Stride,
5053                                           SourceLocation RBLoc) {
5054   if (Base->hasPlaceholderType() &&
5055       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5056     ExprResult Result = CheckPlaceholderExpr(Base);
5057     if (Result.isInvalid())
5058       return ExprError();
5059     Base = Result.get();
5060   }
5061   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5062     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5063     if (Result.isInvalid())
5064       return ExprError();
5065     Result = DefaultLvalueConversion(Result.get());
5066     if (Result.isInvalid())
5067       return ExprError();
5068     LowerBound = Result.get();
5069   }
5070   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5071     ExprResult Result = CheckPlaceholderExpr(Length);
5072     if (Result.isInvalid())
5073       return ExprError();
5074     Result = DefaultLvalueConversion(Result.get());
5075     if (Result.isInvalid())
5076       return ExprError();
5077     Length = Result.get();
5078   }
5079   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5080     ExprResult Result = CheckPlaceholderExpr(Stride);
5081     if (Result.isInvalid())
5082       return ExprError();
5083     Result = DefaultLvalueConversion(Result.get());
5084     if (Result.isInvalid())
5085       return ExprError();
5086     Stride = Result.get();
5087   }
5088 
5089   // Build an unanalyzed expression if either operand is type-dependent.
5090   if (Base->isTypeDependent() ||
5091       (LowerBound &&
5092        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5093       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5094       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5095     return new (Context) OMPArraySectionExpr(
5096         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5097         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5098   }
5099 
5100   // Perform default conversions.
5101   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5102   QualType ResultTy;
5103   if (OriginalTy->isAnyPointerType()) {
5104     ResultTy = OriginalTy->getPointeeType();
5105   } else if (OriginalTy->isArrayType()) {
5106     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5107   } else {
5108     return ExprError(
5109         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5110         << Base->getSourceRange());
5111   }
5112   // C99 6.5.2.1p1
5113   if (LowerBound) {
5114     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5115                                                       LowerBound);
5116     if (Res.isInvalid())
5117       return ExprError(Diag(LowerBound->getExprLoc(),
5118                             diag::err_omp_typecheck_section_not_integer)
5119                        << 0 << LowerBound->getSourceRange());
5120     LowerBound = Res.get();
5121 
5122     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5123         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5124       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5125           << 0 << LowerBound->getSourceRange();
5126   }
5127   if (Length) {
5128     auto Res =
5129         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5130     if (Res.isInvalid())
5131       return ExprError(Diag(Length->getExprLoc(),
5132                             diag::err_omp_typecheck_section_not_integer)
5133                        << 1 << Length->getSourceRange());
5134     Length = Res.get();
5135 
5136     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5137         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5138       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5139           << 1 << Length->getSourceRange();
5140   }
5141   if (Stride) {
5142     ExprResult Res =
5143         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5144     if (Res.isInvalid())
5145       return ExprError(Diag(Stride->getExprLoc(),
5146                             diag::err_omp_typecheck_section_not_integer)
5147                        << 1 << Stride->getSourceRange());
5148     Stride = Res.get();
5149 
5150     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5151         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5152       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5153           << 1 << Stride->getSourceRange();
5154   }
5155 
5156   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5157   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5158   // type. Note that functions are not objects, and that (in C99 parlance)
5159   // incomplete types are not object types.
5160   if (ResultTy->isFunctionType()) {
5161     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5162         << ResultTy << Base->getSourceRange();
5163     return ExprError();
5164   }
5165 
5166   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5167                           diag::err_omp_section_incomplete_type, Base))
5168     return ExprError();
5169 
5170   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5171     Expr::EvalResult Result;
5172     if (LowerBound->EvaluateAsInt(Result, Context)) {
5173       // OpenMP 5.0, [2.1.5 Array Sections]
5174       // The array section must be a subset of the original array.
5175       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5176       if (LowerBoundValue.isNegative()) {
5177         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5178             << LowerBound->getSourceRange();
5179         return ExprError();
5180       }
5181     }
5182   }
5183 
5184   if (Length) {
5185     Expr::EvalResult Result;
5186     if (Length->EvaluateAsInt(Result, Context)) {
5187       // OpenMP 5.0, [2.1.5 Array Sections]
5188       // The length must evaluate to non-negative integers.
5189       llvm::APSInt LengthValue = Result.Val.getInt();
5190       if (LengthValue.isNegative()) {
5191         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5192             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5193             << Length->getSourceRange();
5194         return ExprError();
5195       }
5196     }
5197   } else if (ColonLocFirst.isValid() &&
5198              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5199                                       !OriginalTy->isVariableArrayType()))) {
5200     // OpenMP 5.0, [2.1.5 Array Sections]
5201     // When the size of the array dimension is not known, the length must be
5202     // specified explicitly.
5203     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5204         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5205     return ExprError();
5206   }
5207 
5208   if (Stride) {
5209     Expr::EvalResult Result;
5210     if (Stride->EvaluateAsInt(Result, Context)) {
5211       // OpenMP 5.0, [2.1.5 Array Sections]
5212       // The stride must evaluate to a positive integer.
5213       llvm::APSInt StrideValue = Result.Val.getInt();
5214       if (!StrideValue.isStrictlyPositive()) {
5215         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5216             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5217             << Stride->getSourceRange();
5218         return ExprError();
5219       }
5220     }
5221   }
5222 
5223   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5224     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5225     if (Result.isInvalid())
5226       return ExprError();
5227     Base = Result.get();
5228   }
5229   return new (Context) OMPArraySectionExpr(
5230       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5231       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5232 }
5233 
5234 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5235                                           SourceLocation RParenLoc,
5236                                           ArrayRef<Expr *> Dims,
5237                                           ArrayRef<SourceRange> Brackets) {
5238   if (Base->hasPlaceholderType()) {
5239     ExprResult Result = CheckPlaceholderExpr(Base);
5240     if (Result.isInvalid())
5241       return ExprError();
5242     Result = DefaultLvalueConversion(Result.get());
5243     if (Result.isInvalid())
5244       return ExprError();
5245     Base = Result.get();
5246   }
5247   QualType BaseTy = Base->getType();
5248   // Delay analysis of the types/expressions if instantiation/specialization is
5249   // required.
5250   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5251     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5252                                        LParenLoc, RParenLoc, Dims, Brackets);
5253   if (!BaseTy->isPointerType() ||
5254       (!Base->isTypeDependent() &&
5255        BaseTy->getPointeeType()->isIncompleteType()))
5256     return ExprError(Diag(Base->getExprLoc(),
5257                           diag::err_omp_non_pointer_type_array_shaping_base)
5258                      << Base->getSourceRange());
5259 
5260   SmallVector<Expr *, 4> NewDims;
5261   bool ErrorFound = false;
5262   for (Expr *Dim : Dims) {
5263     if (Dim->hasPlaceholderType()) {
5264       ExprResult Result = CheckPlaceholderExpr(Dim);
5265       if (Result.isInvalid()) {
5266         ErrorFound = true;
5267         continue;
5268       }
5269       Result = DefaultLvalueConversion(Result.get());
5270       if (Result.isInvalid()) {
5271         ErrorFound = true;
5272         continue;
5273       }
5274       Dim = Result.get();
5275     }
5276     if (!Dim->isTypeDependent()) {
5277       ExprResult Result =
5278           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5279       if (Result.isInvalid()) {
5280         ErrorFound = true;
5281         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5282             << Dim->getSourceRange();
5283         continue;
5284       }
5285       Dim = Result.get();
5286       Expr::EvalResult EvResult;
5287       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5288         // OpenMP 5.0, [2.1.4 Array Shaping]
5289         // Each si is an integral type expression that must evaluate to a
5290         // positive integer.
5291         llvm::APSInt Value = EvResult.Val.getInt();
5292         if (!Value.isStrictlyPositive()) {
5293           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5294               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5295               << Dim->getSourceRange();
5296           ErrorFound = true;
5297           continue;
5298         }
5299       }
5300     }
5301     NewDims.push_back(Dim);
5302   }
5303   if (ErrorFound)
5304     return ExprError();
5305   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5306                                      LParenLoc, RParenLoc, NewDims, Brackets);
5307 }
5308 
5309 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5310                                       SourceLocation LLoc, SourceLocation RLoc,
5311                                       ArrayRef<OMPIteratorData> Data) {
5312   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5313   bool IsCorrect = true;
5314   for (const OMPIteratorData &D : Data) {
5315     TypeSourceInfo *TInfo = nullptr;
5316     SourceLocation StartLoc;
5317     QualType DeclTy;
5318     if (!D.Type.getAsOpaquePtr()) {
5319       // OpenMP 5.0, 2.1.6 Iterators
5320       // In an iterator-specifier, if the iterator-type is not specified then
5321       // the type of that iterator is of int type.
5322       DeclTy = Context.IntTy;
5323       StartLoc = D.DeclIdentLoc;
5324     } else {
5325       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5326       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5327     }
5328 
5329     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5330                              DeclTy->containsUnexpandedParameterPack() ||
5331                              DeclTy->isInstantiationDependentType();
5332     if (!IsDeclTyDependent) {
5333       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5334         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5335         // The iterator-type must be an integral or pointer type.
5336         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5337             << DeclTy;
5338         IsCorrect = false;
5339         continue;
5340       }
5341       if (DeclTy.isConstant(Context)) {
5342         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5343         // The iterator-type must not be const qualified.
5344         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5345             << DeclTy;
5346         IsCorrect = false;
5347         continue;
5348       }
5349     }
5350 
5351     // Iterator declaration.
5352     assert(D.DeclIdent && "Identifier expected.");
5353     // Always try to create iterator declarator to avoid extra error messages
5354     // about unknown declarations use.
5355     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5356                                D.DeclIdent, DeclTy, TInfo, SC_None);
5357     VD->setImplicit();
5358     if (S) {
5359       // Check for conflicting previous declaration.
5360       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5361       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5362                             ForVisibleRedeclaration);
5363       Previous.suppressDiagnostics();
5364       LookupName(Previous, S);
5365 
5366       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5367                            /*AllowInlineNamespace=*/false);
5368       if (!Previous.empty()) {
5369         NamedDecl *Old = Previous.getRepresentativeDecl();
5370         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5371         Diag(Old->getLocation(), diag::note_previous_definition);
5372       } else {
5373         PushOnScopeChains(VD, S);
5374       }
5375     } else {
5376       CurContext->addDecl(VD);
5377     }
5378     Expr *Begin = D.Range.Begin;
5379     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5380       ExprResult BeginRes =
5381           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5382       Begin = BeginRes.get();
5383     }
5384     Expr *End = D.Range.End;
5385     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5386       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5387       End = EndRes.get();
5388     }
5389     Expr *Step = D.Range.Step;
5390     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5391       if (!Step->getType()->isIntegralType(Context)) {
5392         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5393             << Step << Step->getSourceRange();
5394         IsCorrect = false;
5395         continue;
5396       }
5397       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5398       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5399       // If the step expression of a range-specification equals zero, the
5400       // behavior is unspecified.
5401       if (Result && Result->isZero()) {
5402         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5403             << Step << Step->getSourceRange();
5404         IsCorrect = false;
5405         continue;
5406       }
5407     }
5408     if (!Begin || !End || !IsCorrect) {
5409       IsCorrect = false;
5410       continue;
5411     }
5412     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5413     IDElem.IteratorDecl = VD;
5414     IDElem.AssignmentLoc = D.AssignLoc;
5415     IDElem.Range.Begin = Begin;
5416     IDElem.Range.End = End;
5417     IDElem.Range.Step = Step;
5418     IDElem.ColonLoc = D.ColonLoc;
5419     IDElem.SecondColonLoc = D.SecColonLoc;
5420   }
5421   if (!IsCorrect) {
5422     // Invalidate all created iterator declarations if error is found.
5423     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5424       if (Decl *ID = D.IteratorDecl)
5425         ID->setInvalidDecl();
5426     }
5427     return ExprError();
5428   }
5429   SmallVector<OMPIteratorHelperData, 4> Helpers;
5430   if (!CurContext->isDependentContext()) {
5431     // Build number of ityeration for each iteration range.
5432     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5433     // ((Begini-Stepi-1-Endi) / -Stepi);
5434     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5435       // (Endi - Begini)
5436       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5437                                           D.Range.Begin);
5438       if(!Res.isUsable()) {
5439         IsCorrect = false;
5440         continue;
5441       }
5442       ExprResult St, St1;
5443       if (D.Range.Step) {
5444         St = D.Range.Step;
5445         // (Endi - Begini) + Stepi
5446         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5447         if (!Res.isUsable()) {
5448           IsCorrect = false;
5449           continue;
5450         }
5451         // (Endi - Begini) + Stepi - 1
5452         Res =
5453             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5454                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5455         if (!Res.isUsable()) {
5456           IsCorrect = false;
5457           continue;
5458         }
5459         // ((Endi - Begini) + Stepi - 1) / Stepi
5460         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5461         if (!Res.isUsable()) {
5462           IsCorrect = false;
5463           continue;
5464         }
5465         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5466         // (Begini - Endi)
5467         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5468                                              D.Range.Begin, D.Range.End);
5469         if (!Res1.isUsable()) {
5470           IsCorrect = false;
5471           continue;
5472         }
5473         // (Begini - Endi) - Stepi
5474         Res1 =
5475             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5476         if (!Res1.isUsable()) {
5477           IsCorrect = false;
5478           continue;
5479         }
5480         // (Begini - Endi) - Stepi - 1
5481         Res1 =
5482             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5483                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5484         if (!Res1.isUsable()) {
5485           IsCorrect = false;
5486           continue;
5487         }
5488         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5489         Res1 =
5490             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5491         if (!Res1.isUsable()) {
5492           IsCorrect = false;
5493           continue;
5494         }
5495         // Stepi > 0.
5496         ExprResult CmpRes =
5497             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5498                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5499         if (!CmpRes.isUsable()) {
5500           IsCorrect = false;
5501           continue;
5502         }
5503         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5504                                  Res.get(), Res1.get());
5505         if (!Res.isUsable()) {
5506           IsCorrect = false;
5507           continue;
5508         }
5509       }
5510       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5511       if (!Res.isUsable()) {
5512         IsCorrect = false;
5513         continue;
5514       }
5515 
5516       // Build counter update.
5517       // Build counter.
5518       auto *CounterVD =
5519           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5520                           D.IteratorDecl->getBeginLoc(), nullptr,
5521                           Res.get()->getType(), nullptr, SC_None);
5522       CounterVD->setImplicit();
5523       ExprResult RefRes =
5524           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5525                            D.IteratorDecl->getBeginLoc());
5526       // Build counter update.
5527       // I = Begini + counter * Stepi;
5528       ExprResult UpdateRes;
5529       if (D.Range.Step) {
5530         UpdateRes = CreateBuiltinBinOp(
5531             D.AssignmentLoc, BO_Mul,
5532             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5533       } else {
5534         UpdateRes = DefaultLvalueConversion(RefRes.get());
5535       }
5536       if (!UpdateRes.isUsable()) {
5537         IsCorrect = false;
5538         continue;
5539       }
5540       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5541                                      UpdateRes.get());
5542       if (!UpdateRes.isUsable()) {
5543         IsCorrect = false;
5544         continue;
5545       }
5546       ExprResult VDRes =
5547           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5548                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5549                            D.IteratorDecl->getBeginLoc());
5550       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5551                                      UpdateRes.get());
5552       if (!UpdateRes.isUsable()) {
5553         IsCorrect = false;
5554         continue;
5555       }
5556       UpdateRes =
5557           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5558       if (!UpdateRes.isUsable()) {
5559         IsCorrect = false;
5560         continue;
5561       }
5562       ExprResult CounterUpdateRes =
5563           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5564       if (!CounterUpdateRes.isUsable()) {
5565         IsCorrect = false;
5566         continue;
5567       }
5568       CounterUpdateRes =
5569           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5570       if (!CounterUpdateRes.isUsable()) {
5571         IsCorrect = false;
5572         continue;
5573       }
5574       OMPIteratorHelperData &HD = Helpers.emplace_back();
5575       HD.CounterVD = CounterVD;
5576       HD.Upper = Res.get();
5577       HD.Update = UpdateRes.get();
5578       HD.CounterUpdate = CounterUpdateRes.get();
5579     }
5580   } else {
5581     Helpers.assign(ID.size(), {});
5582   }
5583   if (!IsCorrect) {
5584     // Invalidate all created iterator declarations if error is found.
5585     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5586       if (Decl *ID = D.IteratorDecl)
5587         ID->setInvalidDecl();
5588     }
5589     return ExprError();
5590   }
5591   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5592                                  LLoc, RLoc, ID, Helpers);
5593 }
5594 
5595 ExprResult
5596 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5597                                       Expr *Idx, SourceLocation RLoc) {
5598   Expr *LHSExp = Base;
5599   Expr *RHSExp = Idx;
5600 
5601   ExprValueKind VK = VK_LValue;
5602   ExprObjectKind OK = OK_Ordinary;
5603 
5604   // Per C++ core issue 1213, the result is an xvalue if either operand is
5605   // a non-lvalue array, and an lvalue otherwise.
5606   if (getLangOpts().CPlusPlus11) {
5607     for (auto *Op : {LHSExp, RHSExp}) {
5608       Op = Op->IgnoreImplicit();
5609       if (Op->getType()->isArrayType() && !Op->isLValue())
5610         VK = VK_XValue;
5611     }
5612   }
5613 
5614   // Perform default conversions.
5615   if (!LHSExp->getType()->getAs<VectorType>()) {
5616     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5617     if (Result.isInvalid())
5618       return ExprError();
5619     LHSExp = Result.get();
5620   }
5621   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5622   if (Result.isInvalid())
5623     return ExprError();
5624   RHSExp = Result.get();
5625 
5626   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5627 
5628   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5629   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5630   // in the subscript position. As a result, we need to derive the array base
5631   // and index from the expression types.
5632   Expr *BaseExpr, *IndexExpr;
5633   QualType ResultType;
5634   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5635     BaseExpr = LHSExp;
5636     IndexExpr = RHSExp;
5637     ResultType =
5638         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5639   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5640     BaseExpr = LHSExp;
5641     IndexExpr = RHSExp;
5642     ResultType = PTy->getPointeeType();
5643   } else if (const ObjCObjectPointerType *PTy =
5644                LHSTy->getAs<ObjCObjectPointerType>()) {
5645     BaseExpr = LHSExp;
5646     IndexExpr = RHSExp;
5647 
5648     // Use custom logic if this should be the pseudo-object subscript
5649     // expression.
5650     if (!LangOpts.isSubscriptPointerArithmetic())
5651       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5652                                           nullptr);
5653 
5654     ResultType = PTy->getPointeeType();
5655   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5656      // Handle the uncommon case of "123[Ptr]".
5657     BaseExpr = RHSExp;
5658     IndexExpr = LHSExp;
5659     ResultType = PTy->getPointeeType();
5660   } else if (const ObjCObjectPointerType *PTy =
5661                RHSTy->getAs<ObjCObjectPointerType>()) {
5662      // Handle the uncommon case of "123[Ptr]".
5663     BaseExpr = RHSExp;
5664     IndexExpr = LHSExp;
5665     ResultType = PTy->getPointeeType();
5666     if (!LangOpts.isSubscriptPointerArithmetic()) {
5667       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5668         << ResultType << BaseExpr->getSourceRange();
5669       return ExprError();
5670     }
5671   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5672     BaseExpr = LHSExp;    // vectors: V[123]
5673     IndexExpr = RHSExp;
5674     // We apply C++ DR1213 to vector subscripting too.
5675     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5676       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5677       if (Materialized.isInvalid())
5678         return ExprError();
5679       LHSExp = Materialized.get();
5680     }
5681     VK = LHSExp->getValueKind();
5682     if (VK != VK_PRValue)
5683       OK = OK_VectorComponent;
5684 
5685     ResultType = VTy->getElementType();
5686     QualType BaseType = BaseExpr->getType();
5687     Qualifiers BaseQuals = BaseType.getQualifiers();
5688     Qualifiers MemberQuals = ResultType.getQualifiers();
5689     Qualifiers Combined = BaseQuals + MemberQuals;
5690     if (Combined != MemberQuals)
5691       ResultType = Context.getQualifiedType(ResultType, Combined);
5692   } else if (LHSTy->isArrayType()) {
5693     // If we see an array that wasn't promoted by
5694     // DefaultFunctionArrayLvalueConversion, it must be an array that
5695     // wasn't promoted because of the C90 rule that doesn't
5696     // allow promoting non-lvalue arrays.  Warn, then
5697     // force the promotion here.
5698     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5699         << LHSExp->getSourceRange();
5700     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5701                                CK_ArrayToPointerDecay).get();
5702     LHSTy = LHSExp->getType();
5703 
5704     BaseExpr = LHSExp;
5705     IndexExpr = RHSExp;
5706     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5707   } else if (RHSTy->isArrayType()) {
5708     // Same as previous, except for 123[f().a] case
5709     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5710         << RHSExp->getSourceRange();
5711     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5712                                CK_ArrayToPointerDecay).get();
5713     RHSTy = RHSExp->getType();
5714 
5715     BaseExpr = RHSExp;
5716     IndexExpr = LHSExp;
5717     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5718   } else {
5719     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5720        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5721   }
5722   // C99 6.5.2.1p1
5723   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5724     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5725                      << IndexExpr->getSourceRange());
5726 
5727   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5728        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5729          && !IndexExpr->isTypeDependent())
5730     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5731 
5732   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5733   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5734   // type. Note that Functions are not objects, and that (in C99 parlance)
5735   // incomplete types are not object types.
5736   if (ResultType->isFunctionType()) {
5737     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5738         << ResultType << BaseExpr->getSourceRange();
5739     return ExprError();
5740   }
5741 
5742   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5743     // GNU extension: subscripting on pointer to void
5744     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5745       << BaseExpr->getSourceRange();
5746 
5747     // C forbids expressions of unqualified void type from being l-values.
5748     // See IsCForbiddenLValueType.
5749     if (!ResultType.hasQualifiers())
5750       VK = VK_PRValue;
5751   } else if (!ResultType->isDependentType() &&
5752              RequireCompleteSizedType(
5753                  LLoc, ResultType,
5754                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5755     return ExprError();
5756 
5757   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5758          !ResultType.isCForbiddenLValueType());
5759 
5760   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5761       FunctionScopes.size() > 1) {
5762     if (auto *TT =
5763             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5764       for (auto I = FunctionScopes.rbegin(),
5765                 E = std::prev(FunctionScopes.rend());
5766            I != E; ++I) {
5767         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5768         if (CSI == nullptr)
5769           break;
5770         DeclContext *DC = nullptr;
5771         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5772           DC = LSI->CallOperator;
5773         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5774           DC = CRSI->TheCapturedDecl;
5775         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5776           DC = BSI->TheDecl;
5777         if (DC) {
5778           if (DC->containsDecl(TT->getDecl()))
5779             break;
5780           captureVariablyModifiedType(
5781               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5782         }
5783       }
5784     }
5785   }
5786 
5787   return new (Context)
5788       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5789 }
5790 
5791 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5792                                   ParmVarDecl *Param) {
5793   if (Param->hasUnparsedDefaultArg()) {
5794     // If we've already cleared out the location for the default argument,
5795     // that means we're parsing it right now.
5796     if (!UnparsedDefaultArgLocs.count(Param)) {
5797       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5798       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5799       Param->setInvalidDecl();
5800       return true;
5801     }
5802 
5803     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5804         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5805     Diag(UnparsedDefaultArgLocs[Param],
5806          diag::note_default_argument_declared_here);
5807     return true;
5808   }
5809 
5810   if (Param->hasUninstantiatedDefaultArg() &&
5811       InstantiateDefaultArgument(CallLoc, FD, Param))
5812     return true;
5813 
5814   assert(Param->hasInit() && "default argument but no initializer?");
5815 
5816   // If the default expression creates temporaries, we need to
5817   // push them to the current stack of expression temporaries so they'll
5818   // be properly destroyed.
5819   // FIXME: We should really be rebuilding the default argument with new
5820   // bound temporaries; see the comment in PR5810.
5821   // We don't need to do that with block decls, though, because
5822   // blocks in default argument expression can never capture anything.
5823   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5824     // Set the "needs cleanups" bit regardless of whether there are
5825     // any explicit objects.
5826     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5827 
5828     // Append all the objects to the cleanup list.  Right now, this
5829     // should always be a no-op, because blocks in default argument
5830     // expressions should never be able to capture anything.
5831     assert(!Init->getNumObjects() &&
5832            "default argument expression has capturing blocks?");
5833   }
5834 
5835   // We already type-checked the argument, so we know it works.
5836   // Just mark all of the declarations in this potentially-evaluated expression
5837   // as being "referenced".
5838   EnterExpressionEvaluationContext EvalContext(
5839       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5840   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5841                                    /*SkipLocalVariables=*/true);
5842   return false;
5843 }
5844 
5845 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5846                                         FunctionDecl *FD, ParmVarDecl *Param) {
5847   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5848   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5849     return ExprError();
5850   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5851 }
5852 
5853 Sema::VariadicCallType
5854 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5855                           Expr *Fn) {
5856   if (Proto && Proto->isVariadic()) {
5857     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5858       return VariadicConstructor;
5859     else if (Fn && Fn->getType()->isBlockPointerType())
5860       return VariadicBlock;
5861     else if (FDecl) {
5862       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5863         if (Method->isInstance())
5864           return VariadicMethod;
5865     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5866       return VariadicMethod;
5867     return VariadicFunction;
5868   }
5869   return VariadicDoesNotApply;
5870 }
5871 
5872 namespace {
5873 class FunctionCallCCC final : public FunctionCallFilterCCC {
5874 public:
5875   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5876                   unsigned NumArgs, MemberExpr *ME)
5877       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5878         FunctionName(FuncName) {}
5879 
5880   bool ValidateCandidate(const TypoCorrection &candidate) override {
5881     if (!candidate.getCorrectionSpecifier() ||
5882         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5883       return false;
5884     }
5885 
5886     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5887   }
5888 
5889   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5890     return std::make_unique<FunctionCallCCC>(*this);
5891   }
5892 
5893 private:
5894   const IdentifierInfo *const FunctionName;
5895 };
5896 }
5897 
5898 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5899                                                FunctionDecl *FDecl,
5900                                                ArrayRef<Expr *> Args) {
5901   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5902   DeclarationName FuncName = FDecl->getDeclName();
5903   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5904 
5905   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5906   if (TypoCorrection Corrected = S.CorrectTypo(
5907           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5908           S.getScopeForContext(S.CurContext), nullptr, CCC,
5909           Sema::CTK_ErrorRecovery)) {
5910     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5911       if (Corrected.isOverloaded()) {
5912         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5913         OverloadCandidateSet::iterator Best;
5914         for (NamedDecl *CD : Corrected) {
5915           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5916             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5917                                    OCS);
5918         }
5919         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5920         case OR_Success:
5921           ND = Best->FoundDecl;
5922           Corrected.setCorrectionDecl(ND);
5923           break;
5924         default:
5925           break;
5926         }
5927       }
5928       ND = ND->getUnderlyingDecl();
5929       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5930         return Corrected;
5931     }
5932   }
5933   return TypoCorrection();
5934 }
5935 
5936 /// ConvertArgumentsForCall - Converts the arguments specified in
5937 /// Args/NumArgs to the parameter types of the function FDecl with
5938 /// function prototype Proto. Call is the call expression itself, and
5939 /// Fn is the function expression. For a C++ member function, this
5940 /// routine does not attempt to convert the object argument. Returns
5941 /// true if the call is ill-formed.
5942 bool
5943 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5944                               FunctionDecl *FDecl,
5945                               const FunctionProtoType *Proto,
5946                               ArrayRef<Expr *> Args,
5947                               SourceLocation RParenLoc,
5948                               bool IsExecConfig) {
5949   // Bail out early if calling a builtin with custom typechecking.
5950   if (FDecl)
5951     if (unsigned ID = FDecl->getBuiltinID())
5952       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5953         return false;
5954 
5955   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5956   // assignment, to the types of the corresponding parameter, ...
5957   unsigned NumParams = Proto->getNumParams();
5958   bool Invalid = false;
5959   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5960   unsigned FnKind = Fn->getType()->isBlockPointerType()
5961                        ? 1 /* block */
5962                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5963                                        : 0 /* function */);
5964 
5965   // If too few arguments are available (and we don't have default
5966   // arguments for the remaining parameters), don't make the call.
5967   if (Args.size() < NumParams) {
5968     if (Args.size() < MinArgs) {
5969       TypoCorrection TC;
5970       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5971         unsigned diag_id =
5972             MinArgs == NumParams && !Proto->isVariadic()
5973                 ? diag::err_typecheck_call_too_few_args_suggest
5974                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5975         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5976                                         << static_cast<unsigned>(Args.size())
5977                                         << TC.getCorrectionRange());
5978       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5979         Diag(RParenLoc,
5980              MinArgs == NumParams && !Proto->isVariadic()
5981                  ? diag::err_typecheck_call_too_few_args_one
5982                  : diag::err_typecheck_call_too_few_args_at_least_one)
5983             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5984       else
5985         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5986                             ? diag::err_typecheck_call_too_few_args
5987                             : diag::err_typecheck_call_too_few_args_at_least)
5988             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5989             << Fn->getSourceRange();
5990 
5991       // Emit the location of the prototype.
5992       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5993         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5994 
5995       return true;
5996     }
5997     // We reserve space for the default arguments when we create
5998     // the call expression, before calling ConvertArgumentsForCall.
5999     assert((Call->getNumArgs() == NumParams) &&
6000            "We should have reserved space for the default arguments before!");
6001   }
6002 
6003   // If too many are passed and not variadic, error on the extras and drop
6004   // them.
6005   if (Args.size() > NumParams) {
6006     if (!Proto->isVariadic()) {
6007       TypoCorrection TC;
6008       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6009         unsigned diag_id =
6010             MinArgs == NumParams && !Proto->isVariadic()
6011                 ? diag::err_typecheck_call_too_many_args_suggest
6012                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6013         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6014                                         << static_cast<unsigned>(Args.size())
6015                                         << TC.getCorrectionRange());
6016       } else if (NumParams == 1 && FDecl &&
6017                  FDecl->getParamDecl(0)->getDeclName())
6018         Diag(Args[NumParams]->getBeginLoc(),
6019              MinArgs == NumParams
6020                  ? diag::err_typecheck_call_too_many_args_one
6021                  : diag::err_typecheck_call_too_many_args_at_most_one)
6022             << FnKind << FDecl->getParamDecl(0)
6023             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6024             << SourceRange(Args[NumParams]->getBeginLoc(),
6025                            Args.back()->getEndLoc());
6026       else
6027         Diag(Args[NumParams]->getBeginLoc(),
6028              MinArgs == NumParams
6029                  ? diag::err_typecheck_call_too_many_args
6030                  : diag::err_typecheck_call_too_many_args_at_most)
6031             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6032             << Fn->getSourceRange()
6033             << SourceRange(Args[NumParams]->getBeginLoc(),
6034                            Args.back()->getEndLoc());
6035 
6036       // Emit the location of the prototype.
6037       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6038         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6039 
6040       // This deletes the extra arguments.
6041       Call->shrinkNumArgs(NumParams);
6042       return true;
6043     }
6044   }
6045   SmallVector<Expr *, 8> AllArgs;
6046   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6047 
6048   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6049                                    AllArgs, CallType);
6050   if (Invalid)
6051     return true;
6052   unsigned TotalNumArgs = AllArgs.size();
6053   for (unsigned i = 0; i < TotalNumArgs; ++i)
6054     Call->setArg(i, AllArgs[i]);
6055 
6056   Call->computeDependence();
6057   return false;
6058 }
6059 
6060 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6061                                   const FunctionProtoType *Proto,
6062                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6063                                   SmallVectorImpl<Expr *> &AllArgs,
6064                                   VariadicCallType CallType, bool AllowExplicit,
6065                                   bool IsListInitialization) {
6066   unsigned NumParams = Proto->getNumParams();
6067   bool Invalid = false;
6068   size_t ArgIx = 0;
6069   // Continue to check argument types (even if we have too few/many args).
6070   for (unsigned i = FirstParam; i < NumParams; i++) {
6071     QualType ProtoArgType = Proto->getParamType(i);
6072 
6073     Expr *Arg;
6074     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6075     if (ArgIx < Args.size()) {
6076       Arg = Args[ArgIx++];
6077 
6078       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6079                               diag::err_call_incomplete_argument, Arg))
6080         return true;
6081 
6082       // Strip the unbridged-cast placeholder expression off, if applicable.
6083       bool CFAudited = false;
6084       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6085           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6086           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6087         Arg = stripARCUnbridgedCast(Arg);
6088       else if (getLangOpts().ObjCAutoRefCount &&
6089                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6090                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6091         CFAudited = true;
6092 
6093       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6094           ProtoArgType->isBlockPointerType())
6095         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6096           BE->getBlockDecl()->setDoesNotEscape();
6097 
6098       InitializedEntity Entity =
6099           Param ? InitializedEntity::InitializeParameter(Context, Param,
6100                                                          ProtoArgType)
6101                 : InitializedEntity::InitializeParameter(
6102                       Context, ProtoArgType, Proto->isParamConsumed(i));
6103 
6104       // Remember that parameter belongs to a CF audited API.
6105       if (CFAudited)
6106         Entity.setParameterCFAudited();
6107 
6108       ExprResult ArgE = PerformCopyInitialization(
6109           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6110       if (ArgE.isInvalid())
6111         return true;
6112 
6113       Arg = ArgE.getAs<Expr>();
6114     } else {
6115       assert(Param && "can't use default arguments without a known callee");
6116 
6117       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6118       if (ArgExpr.isInvalid())
6119         return true;
6120 
6121       Arg = ArgExpr.getAs<Expr>();
6122     }
6123 
6124     // Check for array bounds violations for each argument to the call. This
6125     // check only triggers warnings when the argument isn't a more complex Expr
6126     // with its own checking, such as a BinaryOperator.
6127     CheckArrayAccess(Arg);
6128 
6129     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6130     CheckStaticArrayArgument(CallLoc, Param, Arg);
6131 
6132     AllArgs.push_back(Arg);
6133   }
6134 
6135   // If this is a variadic call, handle args passed through "...".
6136   if (CallType != VariadicDoesNotApply) {
6137     // Assume that extern "C" functions with variadic arguments that
6138     // return __unknown_anytype aren't *really* variadic.
6139     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6140         FDecl->isExternC()) {
6141       for (Expr *A : Args.slice(ArgIx)) {
6142         QualType paramType; // ignored
6143         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6144         Invalid |= arg.isInvalid();
6145         AllArgs.push_back(arg.get());
6146       }
6147 
6148     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6149     } else {
6150       for (Expr *A : Args.slice(ArgIx)) {
6151         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6152         Invalid |= Arg.isInvalid();
6153         AllArgs.push_back(Arg.get());
6154       }
6155     }
6156 
6157     // Check for array bounds violations.
6158     for (Expr *A : Args.slice(ArgIx))
6159       CheckArrayAccess(A);
6160   }
6161   return Invalid;
6162 }
6163 
6164 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6165   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6166   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6167     TL = DTL.getOriginalLoc();
6168   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6169     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6170       << ATL.getLocalSourceRange();
6171 }
6172 
6173 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6174 /// array parameter, check that it is non-null, and that if it is formed by
6175 /// array-to-pointer decay, the underlying array is sufficiently large.
6176 ///
6177 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6178 /// array type derivation, then for each call to the function, the value of the
6179 /// corresponding actual argument shall provide access to the first element of
6180 /// an array with at least as many elements as specified by the size expression.
6181 void
6182 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6183                                ParmVarDecl *Param,
6184                                const Expr *ArgExpr) {
6185   // Static array parameters are not supported in C++.
6186   if (!Param || getLangOpts().CPlusPlus)
6187     return;
6188 
6189   QualType OrigTy = Param->getOriginalType();
6190 
6191   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6192   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6193     return;
6194 
6195   if (ArgExpr->isNullPointerConstant(Context,
6196                                      Expr::NPC_NeverValueDependent)) {
6197     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6198     DiagnoseCalleeStaticArrayParam(*this, Param);
6199     return;
6200   }
6201 
6202   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6203   if (!CAT)
6204     return;
6205 
6206   const ConstantArrayType *ArgCAT =
6207     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6208   if (!ArgCAT)
6209     return;
6210 
6211   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6212                                              ArgCAT->getElementType())) {
6213     if (ArgCAT->getSize().ult(CAT->getSize())) {
6214       Diag(CallLoc, diag::warn_static_array_too_small)
6215           << ArgExpr->getSourceRange()
6216           << (unsigned)ArgCAT->getSize().getZExtValue()
6217           << (unsigned)CAT->getSize().getZExtValue() << 0;
6218       DiagnoseCalleeStaticArrayParam(*this, Param);
6219     }
6220     return;
6221   }
6222 
6223   Optional<CharUnits> ArgSize =
6224       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6225   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6226   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6227     Diag(CallLoc, diag::warn_static_array_too_small)
6228         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6229         << (unsigned)ParmSize->getQuantity() << 1;
6230     DiagnoseCalleeStaticArrayParam(*this, Param);
6231   }
6232 }
6233 
6234 /// Given a function expression of unknown-any type, try to rebuild it
6235 /// to have a function type.
6236 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6237 
6238 /// Is the given type a placeholder that we need to lower out
6239 /// immediately during argument processing?
6240 static bool isPlaceholderToRemoveAsArg(QualType type) {
6241   // Placeholders are never sugared.
6242   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6243   if (!placeholder) return false;
6244 
6245   switch (placeholder->getKind()) {
6246   // Ignore all the non-placeholder types.
6247 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6248   case BuiltinType::Id:
6249 #include "clang/Basic/OpenCLImageTypes.def"
6250 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6251   case BuiltinType::Id:
6252 #include "clang/Basic/OpenCLExtensionTypes.def"
6253   // In practice we'll never use this, since all SVE types are sugared
6254   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6255 #define SVE_TYPE(Name, Id, SingletonId) \
6256   case BuiltinType::Id:
6257 #include "clang/Basic/AArch64SVEACLETypes.def"
6258 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6259   case BuiltinType::Id:
6260 #include "clang/Basic/PPCTypes.def"
6261 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6262 #include "clang/Basic/RISCVVTypes.def"
6263 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6264 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6265 #include "clang/AST/BuiltinTypes.def"
6266     return false;
6267 
6268   // We cannot lower out overload sets; they might validly be resolved
6269   // by the call machinery.
6270   case BuiltinType::Overload:
6271     return false;
6272 
6273   // Unbridged casts in ARC can be handled in some call positions and
6274   // should be left in place.
6275   case BuiltinType::ARCUnbridgedCast:
6276     return false;
6277 
6278   // Pseudo-objects should be converted as soon as possible.
6279   case BuiltinType::PseudoObject:
6280     return true;
6281 
6282   // The debugger mode could theoretically but currently does not try
6283   // to resolve unknown-typed arguments based on known parameter types.
6284   case BuiltinType::UnknownAny:
6285     return true;
6286 
6287   // These are always invalid as call arguments and should be reported.
6288   case BuiltinType::BoundMember:
6289   case BuiltinType::BuiltinFn:
6290   case BuiltinType::IncompleteMatrixIdx:
6291   case BuiltinType::OMPArraySection:
6292   case BuiltinType::OMPArrayShaping:
6293   case BuiltinType::OMPIterator:
6294     return true;
6295 
6296   }
6297   llvm_unreachable("bad builtin type kind");
6298 }
6299 
6300 /// Check an argument list for placeholders that we won't try to
6301 /// handle later.
6302 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6303   // Apply this processing to all the arguments at once instead of
6304   // dying at the first failure.
6305   bool hasInvalid = false;
6306   for (size_t i = 0, e = args.size(); i != e; i++) {
6307     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6308       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6309       if (result.isInvalid()) hasInvalid = true;
6310       else args[i] = result.get();
6311     }
6312   }
6313   return hasInvalid;
6314 }
6315 
6316 /// If a builtin function has a pointer argument with no explicit address
6317 /// space, then it should be able to accept a pointer to any address
6318 /// space as input.  In order to do this, we need to replace the
6319 /// standard builtin declaration with one that uses the same address space
6320 /// as the call.
6321 ///
6322 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6323 ///                  it does not contain any pointer arguments without
6324 ///                  an address space qualifer.  Otherwise the rewritten
6325 ///                  FunctionDecl is returned.
6326 /// TODO: Handle pointer return types.
6327 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6328                                                 FunctionDecl *FDecl,
6329                                                 MultiExprArg ArgExprs) {
6330 
6331   QualType DeclType = FDecl->getType();
6332   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6333 
6334   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6335       ArgExprs.size() < FT->getNumParams())
6336     return nullptr;
6337 
6338   bool NeedsNewDecl = false;
6339   unsigned i = 0;
6340   SmallVector<QualType, 8> OverloadParams;
6341 
6342   for (QualType ParamType : FT->param_types()) {
6343 
6344     // Convert array arguments to pointer to simplify type lookup.
6345     ExprResult ArgRes =
6346         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6347     if (ArgRes.isInvalid())
6348       return nullptr;
6349     Expr *Arg = ArgRes.get();
6350     QualType ArgType = Arg->getType();
6351     if (!ParamType->isPointerType() ||
6352         ParamType.hasAddressSpace() ||
6353         !ArgType->isPointerType() ||
6354         !ArgType->getPointeeType().hasAddressSpace()) {
6355       OverloadParams.push_back(ParamType);
6356       continue;
6357     }
6358 
6359     QualType PointeeType = ParamType->getPointeeType();
6360     if (PointeeType.hasAddressSpace())
6361       continue;
6362 
6363     NeedsNewDecl = true;
6364     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6365 
6366     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6367     OverloadParams.push_back(Context.getPointerType(PointeeType));
6368   }
6369 
6370   if (!NeedsNewDecl)
6371     return nullptr;
6372 
6373   FunctionProtoType::ExtProtoInfo EPI;
6374   EPI.Variadic = FT->isVariadic();
6375   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6376                                                 OverloadParams, EPI);
6377   DeclContext *Parent = FDecl->getParent();
6378   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6379       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6380       FDecl->getIdentifier(), OverloadTy,
6381       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6382       false,
6383       /*hasPrototype=*/true);
6384   SmallVector<ParmVarDecl*, 16> Params;
6385   FT = cast<FunctionProtoType>(OverloadTy);
6386   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6387     QualType ParamType = FT->getParamType(i);
6388     ParmVarDecl *Parm =
6389         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6390                                 SourceLocation(), nullptr, ParamType,
6391                                 /*TInfo=*/nullptr, SC_None, nullptr);
6392     Parm->setScopeInfo(0, i);
6393     Params.push_back(Parm);
6394   }
6395   OverloadDecl->setParams(Params);
6396   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6397   return OverloadDecl;
6398 }
6399 
6400 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6401                                     FunctionDecl *Callee,
6402                                     MultiExprArg ArgExprs) {
6403   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6404   // similar attributes) really don't like it when functions are called with an
6405   // invalid number of args.
6406   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6407                          /*PartialOverloading=*/false) &&
6408       !Callee->isVariadic())
6409     return;
6410   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6411     return;
6412 
6413   if (const EnableIfAttr *Attr =
6414           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6415     S.Diag(Fn->getBeginLoc(),
6416            isa<CXXMethodDecl>(Callee)
6417                ? diag::err_ovl_no_viable_member_function_in_call
6418                : diag::err_ovl_no_viable_function_in_call)
6419         << Callee << Callee->getSourceRange();
6420     S.Diag(Callee->getLocation(),
6421            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6422         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6423     return;
6424   }
6425 }
6426 
6427 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6428     const UnresolvedMemberExpr *const UME, Sema &S) {
6429 
6430   const auto GetFunctionLevelDCIfCXXClass =
6431       [](Sema &S) -> const CXXRecordDecl * {
6432     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6433     if (!DC || !DC->getParent())
6434       return nullptr;
6435 
6436     // If the call to some member function was made from within a member
6437     // function body 'M' return return 'M's parent.
6438     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6439       return MD->getParent()->getCanonicalDecl();
6440     // else the call was made from within a default member initializer of a
6441     // class, so return the class.
6442     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6443       return RD->getCanonicalDecl();
6444     return nullptr;
6445   };
6446   // If our DeclContext is neither a member function nor a class (in the
6447   // case of a lambda in a default member initializer), we can't have an
6448   // enclosing 'this'.
6449 
6450   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6451   if (!CurParentClass)
6452     return false;
6453 
6454   // The naming class for implicit member functions call is the class in which
6455   // name lookup starts.
6456   const CXXRecordDecl *const NamingClass =
6457       UME->getNamingClass()->getCanonicalDecl();
6458   assert(NamingClass && "Must have naming class even for implicit access");
6459 
6460   // If the unresolved member functions were found in a 'naming class' that is
6461   // related (either the same or derived from) to the class that contains the
6462   // member function that itself contained the implicit member access.
6463 
6464   return CurParentClass == NamingClass ||
6465          CurParentClass->isDerivedFrom(NamingClass);
6466 }
6467 
6468 static void
6469 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6470     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6471 
6472   if (!UME)
6473     return;
6474 
6475   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6476   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6477   // already been captured, or if this is an implicit member function call (if
6478   // it isn't, an attempt to capture 'this' should already have been made).
6479   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6480       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6481     return;
6482 
6483   // Check if the naming class in which the unresolved members were found is
6484   // related (same as or is a base of) to the enclosing class.
6485 
6486   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6487     return;
6488 
6489 
6490   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6491   // If the enclosing function is not dependent, then this lambda is
6492   // capture ready, so if we can capture this, do so.
6493   if (!EnclosingFunctionCtx->isDependentContext()) {
6494     // If the current lambda and all enclosing lambdas can capture 'this' -
6495     // then go ahead and capture 'this' (since our unresolved overload set
6496     // contains at least one non-static member function).
6497     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6498       S.CheckCXXThisCapture(CallLoc);
6499   } else if (S.CurContext->isDependentContext()) {
6500     // ... since this is an implicit member reference, that might potentially
6501     // involve a 'this' capture, mark 'this' for potential capture in
6502     // enclosing lambdas.
6503     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6504       CurLSI->addPotentialThisCapture(CallLoc);
6505   }
6506 }
6507 
6508 // Once a call is fully resolved, warn for unqualified calls to specific
6509 // C++ standard functions, like move and forward.
6510 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6511   // We are only checking unary move and forward so exit early here.
6512   if (Call->getNumArgs() != 1)
6513     return;
6514 
6515   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6516   if (!E || isa<UnresolvedLookupExpr>(E))
6517     return;
6518   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6519   if (!DRE || !DRE->getLocation().isValid())
6520     return;
6521 
6522   if (DRE->getQualifier())
6523     return;
6524 
6525   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6526   if (!D || !D->isInStdNamespace())
6527     return;
6528 
6529   // Only warn for some functions deemed more frequent or problematic.
6530   static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6531   auto it = llvm::find(SpecialFunctions, D->getName());
6532   if (it == std::end(SpecialFunctions))
6533     return;
6534 
6535   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6536       << D->getQualifiedNameAsString()
6537       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6538 }
6539 
6540 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6541                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6542                                Expr *ExecConfig) {
6543   ExprResult Call =
6544       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6545                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6546   if (Call.isInvalid())
6547     return Call;
6548 
6549   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6550   // language modes.
6551   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6552     if (ULE->hasExplicitTemplateArgs() &&
6553         ULE->decls_begin() == ULE->decls_end()) {
6554       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6555                                  ? diag::warn_cxx17_compat_adl_only_template_id
6556                                  : diag::ext_adl_only_template_id)
6557           << ULE->getName();
6558     }
6559   }
6560 
6561   if (LangOpts.OpenMP)
6562     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6563                            ExecConfig);
6564   if (LangOpts.CPlusPlus) {
6565     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6566     if (CE)
6567       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6568   }
6569   return Call;
6570 }
6571 
6572 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6573 /// This provides the location of the left/right parens and a list of comma
6574 /// locations.
6575 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6576                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6577                                Expr *ExecConfig, bool IsExecConfig,
6578                                bool AllowRecovery) {
6579   // Since this might be a postfix expression, get rid of ParenListExprs.
6580   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6581   if (Result.isInvalid()) return ExprError();
6582   Fn = Result.get();
6583 
6584   if (checkArgsForPlaceholders(*this, ArgExprs))
6585     return ExprError();
6586 
6587   if (getLangOpts().CPlusPlus) {
6588     // If this is a pseudo-destructor expression, build the call immediately.
6589     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6590       if (!ArgExprs.empty()) {
6591         // Pseudo-destructor calls should not have any arguments.
6592         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6593             << FixItHint::CreateRemoval(
6594                    SourceRange(ArgExprs.front()->getBeginLoc(),
6595                                ArgExprs.back()->getEndLoc()));
6596       }
6597 
6598       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6599                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6600     }
6601     if (Fn->getType() == Context.PseudoObjectTy) {
6602       ExprResult result = CheckPlaceholderExpr(Fn);
6603       if (result.isInvalid()) return ExprError();
6604       Fn = result.get();
6605     }
6606 
6607     // Determine whether this is a dependent call inside a C++ template,
6608     // in which case we won't do any semantic analysis now.
6609     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6610       if (ExecConfig) {
6611         return CUDAKernelCallExpr::Create(Context, Fn,
6612                                           cast<CallExpr>(ExecConfig), ArgExprs,
6613                                           Context.DependentTy, VK_PRValue,
6614                                           RParenLoc, CurFPFeatureOverrides());
6615       } else {
6616 
6617         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6618             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6619             Fn->getBeginLoc());
6620 
6621         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6622                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6623       }
6624     }
6625 
6626     // Determine whether this is a call to an object (C++ [over.call.object]).
6627     if (Fn->getType()->isRecordType())
6628       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6629                                           RParenLoc);
6630 
6631     if (Fn->getType() == Context.UnknownAnyTy) {
6632       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6633       if (result.isInvalid()) return ExprError();
6634       Fn = result.get();
6635     }
6636 
6637     if (Fn->getType() == Context.BoundMemberTy) {
6638       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6639                                        RParenLoc, ExecConfig, IsExecConfig,
6640                                        AllowRecovery);
6641     }
6642   }
6643 
6644   // Check for overloaded calls.  This can happen even in C due to extensions.
6645   if (Fn->getType() == Context.OverloadTy) {
6646     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6647 
6648     // We aren't supposed to apply this logic if there's an '&' involved.
6649     if (!find.HasFormOfMemberPointer) {
6650       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6651         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6652                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6653       OverloadExpr *ovl = find.Expression;
6654       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6655         return BuildOverloadedCallExpr(
6656             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6657             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6658       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6659                                        RParenLoc, ExecConfig, IsExecConfig,
6660                                        AllowRecovery);
6661     }
6662   }
6663 
6664   // If we're directly calling a function, get the appropriate declaration.
6665   if (Fn->getType() == Context.UnknownAnyTy) {
6666     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6667     if (result.isInvalid()) return ExprError();
6668     Fn = result.get();
6669   }
6670 
6671   Expr *NakedFn = Fn->IgnoreParens();
6672 
6673   bool CallingNDeclIndirectly = false;
6674   NamedDecl *NDecl = nullptr;
6675   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6676     if (UnOp->getOpcode() == UO_AddrOf) {
6677       CallingNDeclIndirectly = true;
6678       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6679     }
6680   }
6681 
6682   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6683     NDecl = DRE->getDecl();
6684 
6685     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6686     if (FDecl && FDecl->getBuiltinID()) {
6687       // Rewrite the function decl for this builtin by replacing parameters
6688       // with no explicit address space with the address space of the arguments
6689       // in ArgExprs.
6690       if ((FDecl =
6691                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6692         NDecl = FDecl;
6693         Fn = DeclRefExpr::Create(
6694             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6695             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6696             nullptr, DRE->isNonOdrUse());
6697       }
6698     }
6699   } else if (isa<MemberExpr>(NakedFn))
6700     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6701 
6702   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6703     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6704                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6705       return ExprError();
6706 
6707     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6708 
6709     // If this expression is a call to a builtin function in HIP device
6710     // compilation, allow a pointer-type argument to default address space to be
6711     // passed as a pointer-type parameter to a non-default address space.
6712     // If Arg is declared in the default address space and Param is declared
6713     // in a non-default address space, perform an implicit address space cast to
6714     // the parameter type.
6715     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6716         FD->getBuiltinID()) {
6717       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6718         ParmVarDecl *Param = FD->getParamDecl(Idx);
6719         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6720             !ArgExprs[Idx]->getType()->isPointerType())
6721           continue;
6722 
6723         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6724         auto ArgTy = ArgExprs[Idx]->getType();
6725         auto ArgPtTy = ArgTy->getPointeeType();
6726         auto ArgAS = ArgPtTy.getAddressSpace();
6727 
6728         // Add address space cast if target address spaces are different
6729         bool NeedImplicitASC =
6730           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6731           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6732                                               // or from specific AS which has target AS matching that of Param.
6733           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6734         if (!NeedImplicitASC)
6735           continue;
6736 
6737         // First, ensure that the Arg is an RValue.
6738         if (ArgExprs[Idx]->isGLValue()) {
6739           ArgExprs[Idx] = ImplicitCastExpr::Create(
6740               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6741               nullptr, VK_PRValue, FPOptionsOverride());
6742         }
6743 
6744         // Construct a new arg type with address space of Param
6745         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6746         ArgPtQuals.setAddressSpace(ParamAS);
6747         auto NewArgPtTy =
6748             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6749         auto NewArgTy =
6750             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6751                                      ArgTy.getQualifiers());
6752 
6753         // Finally perform an implicit address space cast
6754         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6755                                           CK_AddressSpaceConversion)
6756                             .get();
6757       }
6758     }
6759   }
6760 
6761   if (Context.isDependenceAllowed() &&
6762       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6763     assert(!getLangOpts().CPlusPlus);
6764     assert((Fn->containsErrors() ||
6765             llvm::any_of(ArgExprs,
6766                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6767            "should only occur in error-recovery path.");
6768     QualType ReturnType =
6769         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6770             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6771             : Context.DependentTy;
6772     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6773                             Expr::getValueKindForType(ReturnType), RParenLoc,
6774                             CurFPFeatureOverrides());
6775   }
6776   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6777                                ExecConfig, IsExecConfig);
6778 }
6779 
6780 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6781 //  with the specified CallArgs
6782 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6783                                  MultiExprArg CallArgs) {
6784   StringRef Name = Context.BuiltinInfo.getName(Id);
6785   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6786                  Sema::LookupOrdinaryName);
6787   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6788 
6789   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6790   assert(BuiltInDecl && "failed to find builtin declaration");
6791 
6792   ExprResult DeclRef =
6793       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6794   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6795 
6796   ExprResult Call =
6797       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6798 
6799   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6800   return Call.get();
6801 }
6802 
6803 /// Parse a __builtin_astype expression.
6804 ///
6805 /// __builtin_astype( value, dst type )
6806 ///
6807 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6808                                  SourceLocation BuiltinLoc,
6809                                  SourceLocation RParenLoc) {
6810   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6811   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6812 }
6813 
6814 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6815 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6816                                  SourceLocation BuiltinLoc,
6817                                  SourceLocation RParenLoc) {
6818   ExprValueKind VK = VK_PRValue;
6819   ExprObjectKind OK = OK_Ordinary;
6820   QualType SrcTy = E->getType();
6821   if (!SrcTy->isDependentType() &&
6822       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6823     return ExprError(
6824         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6825         << DestTy << SrcTy << E->getSourceRange());
6826   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6827 }
6828 
6829 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6830 /// provided arguments.
6831 ///
6832 /// __builtin_convertvector( value, dst type )
6833 ///
6834 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6835                                         SourceLocation BuiltinLoc,
6836                                         SourceLocation RParenLoc) {
6837   TypeSourceInfo *TInfo;
6838   GetTypeFromParser(ParsedDestTy, &TInfo);
6839   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6840 }
6841 
6842 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6843 /// i.e. an expression not of \p OverloadTy.  The expression should
6844 /// unary-convert to an expression of function-pointer or
6845 /// block-pointer type.
6846 ///
6847 /// \param NDecl the declaration being called, if available
6848 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6849                                        SourceLocation LParenLoc,
6850                                        ArrayRef<Expr *> Args,
6851                                        SourceLocation RParenLoc, Expr *Config,
6852                                        bool IsExecConfig, ADLCallKind UsesADL) {
6853   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6854   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6855 
6856   // Functions with 'interrupt' attribute cannot be called directly.
6857   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6858     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6859     return ExprError();
6860   }
6861 
6862   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6863   // so there's some risk when calling out to non-interrupt handler functions
6864   // that the callee might not preserve them. This is easy to diagnose here,
6865   // but can be very challenging to debug.
6866   // Likewise, X86 interrupt handlers may only call routines with attribute
6867   // no_caller_saved_registers since there is no efficient way to
6868   // save and restore the non-GPR state.
6869   if (auto *Caller = getCurFunctionDecl()) {
6870     if (Caller->hasAttr<ARMInterruptAttr>()) {
6871       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6872       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6873         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6874         if (FDecl)
6875           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6876       }
6877     }
6878     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6879         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6880       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6881       if (FDecl)
6882         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6883     }
6884   }
6885 
6886   // Promote the function operand.
6887   // We special-case function promotion here because we only allow promoting
6888   // builtin functions to function pointers in the callee of a call.
6889   ExprResult Result;
6890   QualType ResultTy;
6891   if (BuiltinID &&
6892       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6893     // Extract the return type from the (builtin) function pointer type.
6894     // FIXME Several builtins still have setType in
6895     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6896     // Builtins.def to ensure they are correct before removing setType calls.
6897     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6898     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6899     ResultTy = FDecl->getCallResultType();
6900   } else {
6901     Result = CallExprUnaryConversions(Fn);
6902     ResultTy = Context.BoolTy;
6903   }
6904   if (Result.isInvalid())
6905     return ExprError();
6906   Fn = Result.get();
6907 
6908   // Check for a valid function type, but only if it is not a builtin which
6909   // requires custom type checking. These will be handled by
6910   // CheckBuiltinFunctionCall below just after creation of the call expression.
6911   const FunctionType *FuncT = nullptr;
6912   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6913   retry:
6914     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6915       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6916       // have type pointer to function".
6917       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6918       if (!FuncT)
6919         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6920                          << Fn->getType() << Fn->getSourceRange());
6921     } else if (const BlockPointerType *BPT =
6922                    Fn->getType()->getAs<BlockPointerType>()) {
6923       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6924     } else {
6925       // Handle calls to expressions of unknown-any type.
6926       if (Fn->getType() == Context.UnknownAnyTy) {
6927         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6928         if (rewrite.isInvalid())
6929           return ExprError();
6930         Fn = rewrite.get();
6931         goto retry;
6932       }
6933 
6934       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6935                        << Fn->getType() << Fn->getSourceRange());
6936     }
6937   }
6938 
6939   // Get the number of parameters in the function prototype, if any.
6940   // We will allocate space for max(Args.size(), NumParams) arguments
6941   // in the call expression.
6942   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6943   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6944 
6945   CallExpr *TheCall;
6946   if (Config) {
6947     assert(UsesADL == ADLCallKind::NotADL &&
6948            "CUDAKernelCallExpr should not use ADL");
6949     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6950                                          Args, ResultTy, VK_PRValue, RParenLoc,
6951                                          CurFPFeatureOverrides(), NumParams);
6952   } else {
6953     TheCall =
6954         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6955                          CurFPFeatureOverrides(), NumParams, UsesADL);
6956   }
6957 
6958   if (!Context.isDependenceAllowed()) {
6959     // Forget about the nulled arguments since typo correction
6960     // do not handle them well.
6961     TheCall->shrinkNumArgs(Args.size());
6962     // C cannot always handle TypoExpr nodes in builtin calls and direct
6963     // function calls as their argument checking don't necessarily handle
6964     // dependent types properly, so make sure any TypoExprs have been
6965     // dealt with.
6966     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6967     if (!Result.isUsable()) return ExprError();
6968     CallExpr *TheOldCall = TheCall;
6969     TheCall = dyn_cast<CallExpr>(Result.get());
6970     bool CorrectedTypos = TheCall != TheOldCall;
6971     if (!TheCall) return Result;
6972     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6973 
6974     // A new call expression node was created if some typos were corrected.
6975     // However it may not have been constructed with enough storage. In this
6976     // case, rebuild the node with enough storage. The waste of space is
6977     // immaterial since this only happens when some typos were corrected.
6978     if (CorrectedTypos && Args.size() < NumParams) {
6979       if (Config)
6980         TheCall = CUDAKernelCallExpr::Create(
6981             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6982             RParenLoc, CurFPFeatureOverrides(), NumParams);
6983       else
6984         TheCall =
6985             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6986                              CurFPFeatureOverrides(), NumParams, UsesADL);
6987     }
6988     // We can now handle the nulled arguments for the default arguments.
6989     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6990   }
6991 
6992   // Bail out early if calling a builtin with custom type checking.
6993   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6994     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6995 
6996   if (getLangOpts().CUDA) {
6997     if (Config) {
6998       // CUDA: Kernel calls must be to global functions
6999       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7000         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7001             << FDecl << Fn->getSourceRange());
7002 
7003       // CUDA: Kernel function must have 'void' return type
7004       if (!FuncT->getReturnType()->isVoidType() &&
7005           !FuncT->getReturnType()->getAs<AutoType>() &&
7006           !FuncT->getReturnType()->isInstantiationDependentType())
7007         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7008             << Fn->getType() << Fn->getSourceRange());
7009     } else {
7010       // CUDA: Calls to global functions must be configured
7011       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7012         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7013             << FDecl << Fn->getSourceRange());
7014     }
7015   }
7016 
7017   // Check for a valid return type
7018   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7019                           FDecl))
7020     return ExprError();
7021 
7022   // We know the result type of the call, set it.
7023   TheCall->setType(FuncT->getCallResultType(Context));
7024   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7025 
7026   if (Proto) {
7027     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7028                                 IsExecConfig))
7029       return ExprError();
7030   } else {
7031     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7032 
7033     if (FDecl) {
7034       // Check if we have too few/too many template arguments, based
7035       // on our knowledge of the function definition.
7036       const FunctionDecl *Def = nullptr;
7037       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7038         Proto = Def->getType()->getAs<FunctionProtoType>();
7039        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7040           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7041           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7042       }
7043 
7044       // If the function we're calling isn't a function prototype, but we have
7045       // a function prototype from a prior declaratiom, use that prototype.
7046       if (!FDecl->hasPrototype())
7047         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7048     }
7049 
7050     // Promote the arguments (C99 6.5.2.2p6).
7051     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7052       Expr *Arg = Args[i];
7053 
7054       if (Proto && i < Proto->getNumParams()) {
7055         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7056             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7057         ExprResult ArgE =
7058             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7059         if (ArgE.isInvalid())
7060           return true;
7061 
7062         Arg = ArgE.getAs<Expr>();
7063 
7064       } else {
7065         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7066 
7067         if (ArgE.isInvalid())
7068           return true;
7069 
7070         Arg = ArgE.getAs<Expr>();
7071       }
7072 
7073       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7074                               diag::err_call_incomplete_argument, Arg))
7075         return ExprError();
7076 
7077       TheCall->setArg(i, Arg);
7078     }
7079     TheCall->computeDependence();
7080   }
7081 
7082   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7083     if (!Method->isStatic())
7084       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7085         << Fn->getSourceRange());
7086 
7087   // Check for sentinels
7088   if (NDecl)
7089     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7090 
7091   // Warn for unions passing across security boundary (CMSE).
7092   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7093     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7094       if (const auto *RT =
7095               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7096         if (RT->getDecl()->isOrContainsUnion())
7097           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7098               << 0 << i;
7099       }
7100     }
7101   }
7102 
7103   // Do special checking on direct calls to functions.
7104   if (FDecl) {
7105     if (CheckFunctionCall(FDecl, TheCall, Proto))
7106       return ExprError();
7107 
7108     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7109 
7110     if (BuiltinID)
7111       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7112   } else if (NDecl) {
7113     if (CheckPointerCall(NDecl, TheCall, Proto))
7114       return ExprError();
7115   } else {
7116     if (CheckOtherCall(TheCall, Proto))
7117       return ExprError();
7118   }
7119 
7120   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7121 }
7122 
7123 ExprResult
7124 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7125                            SourceLocation RParenLoc, Expr *InitExpr) {
7126   assert(Ty && "ActOnCompoundLiteral(): missing type");
7127   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7128 
7129   TypeSourceInfo *TInfo;
7130   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7131   if (!TInfo)
7132     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7133 
7134   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7135 }
7136 
7137 ExprResult
7138 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7139                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7140   QualType literalType = TInfo->getType();
7141 
7142   if (literalType->isArrayType()) {
7143     if (RequireCompleteSizedType(
7144             LParenLoc, Context.getBaseElementType(literalType),
7145             diag::err_array_incomplete_or_sizeless_type,
7146             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7147       return ExprError();
7148     if (literalType->isVariableArrayType()) {
7149       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7150                                            diag::err_variable_object_no_init)) {
7151         return ExprError();
7152       }
7153     }
7154   } else if (!literalType->isDependentType() &&
7155              RequireCompleteType(LParenLoc, literalType,
7156                diag::err_typecheck_decl_incomplete_type,
7157                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7158     return ExprError();
7159 
7160   InitializedEntity Entity
7161     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7162   InitializationKind Kind
7163     = InitializationKind::CreateCStyleCast(LParenLoc,
7164                                            SourceRange(LParenLoc, RParenLoc),
7165                                            /*InitList=*/true);
7166   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7167   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7168                                       &literalType);
7169   if (Result.isInvalid())
7170     return ExprError();
7171   LiteralExpr = Result.get();
7172 
7173   bool isFileScope = !CurContext->isFunctionOrMethod();
7174 
7175   // In C, compound literals are l-values for some reason.
7176   // For GCC compatibility, in C++, file-scope array compound literals with
7177   // constant initializers are also l-values, and compound literals are
7178   // otherwise prvalues.
7179   //
7180   // (GCC also treats C++ list-initialized file-scope array prvalues with
7181   // constant initializers as l-values, but that's non-conforming, so we don't
7182   // follow it there.)
7183   //
7184   // FIXME: It would be better to handle the lvalue cases as materializing and
7185   // lifetime-extending a temporary object, but our materialized temporaries
7186   // representation only supports lifetime extension from a variable, not "out
7187   // of thin air".
7188   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7189   // is bound to the result of applying array-to-pointer decay to the compound
7190   // literal.
7191   // FIXME: GCC supports compound literals of reference type, which should
7192   // obviously have a value kind derived from the kind of reference involved.
7193   ExprValueKind VK =
7194       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7195           ? VK_PRValue
7196           : VK_LValue;
7197 
7198   if (isFileScope)
7199     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7200       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7201         Expr *Init = ILE->getInit(i);
7202         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7203       }
7204 
7205   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7206                                               VK, LiteralExpr, isFileScope);
7207   if (isFileScope) {
7208     if (!LiteralExpr->isTypeDependent() &&
7209         !LiteralExpr->isValueDependent() &&
7210         !literalType->isDependentType()) // C99 6.5.2.5p3
7211       if (CheckForConstantInitializer(LiteralExpr, literalType))
7212         return ExprError();
7213   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7214              literalType.getAddressSpace() != LangAS::Default) {
7215     // Embedded-C extensions to C99 6.5.2.5:
7216     //   "If the compound literal occurs inside the body of a function, the
7217     //   type name shall not be qualified by an address-space qualifier."
7218     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7219       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7220     return ExprError();
7221   }
7222 
7223   if (!isFileScope && !getLangOpts().CPlusPlus) {
7224     // Compound literals that have automatic storage duration are destroyed at
7225     // the end of the scope in C; in C++, they're just temporaries.
7226 
7227     // Emit diagnostics if it is or contains a C union type that is non-trivial
7228     // to destruct.
7229     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7230       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7231                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7232 
7233     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7234     if (literalType.isDestructedType()) {
7235       Cleanup.setExprNeedsCleanups(true);
7236       ExprCleanupObjects.push_back(E);
7237       getCurFunction()->setHasBranchProtectedScope();
7238     }
7239   }
7240 
7241   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7242       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7243     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7244                                        E->getInitializer()->getExprLoc());
7245 
7246   return MaybeBindToTemporary(E);
7247 }
7248 
7249 ExprResult
7250 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7251                     SourceLocation RBraceLoc) {
7252   // Only produce each kind of designated initialization diagnostic once.
7253   SourceLocation FirstDesignator;
7254   bool DiagnosedArrayDesignator = false;
7255   bool DiagnosedNestedDesignator = false;
7256   bool DiagnosedMixedDesignator = false;
7257 
7258   // Check that any designated initializers are syntactically valid in the
7259   // current language mode.
7260   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7261     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7262       if (FirstDesignator.isInvalid())
7263         FirstDesignator = DIE->getBeginLoc();
7264 
7265       if (!getLangOpts().CPlusPlus)
7266         break;
7267 
7268       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7269         DiagnosedNestedDesignator = true;
7270         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7271           << DIE->getDesignatorsSourceRange();
7272       }
7273 
7274       for (auto &Desig : DIE->designators()) {
7275         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7276           DiagnosedArrayDesignator = true;
7277           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7278             << Desig.getSourceRange();
7279         }
7280       }
7281 
7282       if (!DiagnosedMixedDesignator &&
7283           !isa<DesignatedInitExpr>(InitArgList[0])) {
7284         DiagnosedMixedDesignator = true;
7285         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7286           << DIE->getSourceRange();
7287         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7288           << InitArgList[0]->getSourceRange();
7289       }
7290     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7291                isa<DesignatedInitExpr>(InitArgList[0])) {
7292       DiagnosedMixedDesignator = true;
7293       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7294       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7295         << DIE->getSourceRange();
7296       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7297         << InitArgList[I]->getSourceRange();
7298     }
7299   }
7300 
7301   if (FirstDesignator.isValid()) {
7302     // Only diagnose designated initiaization as a C++20 extension if we didn't
7303     // already diagnose use of (non-C++20) C99 designator syntax.
7304     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7305         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7306       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7307                                 ? diag::warn_cxx17_compat_designated_init
7308                                 : diag::ext_cxx_designated_init);
7309     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7310       Diag(FirstDesignator, diag::ext_designated_init);
7311     }
7312   }
7313 
7314   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7315 }
7316 
7317 ExprResult
7318 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7319                     SourceLocation RBraceLoc) {
7320   // Semantic analysis for initializers is done by ActOnDeclarator() and
7321   // CheckInitializer() - it requires knowledge of the object being initialized.
7322 
7323   // Immediately handle non-overload placeholders.  Overloads can be
7324   // resolved contextually, but everything else here can't.
7325   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7326     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7327       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7328 
7329       // Ignore failures; dropping the entire initializer list because
7330       // of one failure would be terrible for indexing/etc.
7331       if (result.isInvalid()) continue;
7332 
7333       InitArgList[I] = result.get();
7334     }
7335   }
7336 
7337   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7338                                                RBraceLoc);
7339   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7340   return E;
7341 }
7342 
7343 /// Do an explicit extend of the given block pointer if we're in ARC.
7344 void Sema::maybeExtendBlockObject(ExprResult &E) {
7345   assert(E.get()->getType()->isBlockPointerType());
7346   assert(E.get()->isPRValue());
7347 
7348   // Only do this in an r-value context.
7349   if (!getLangOpts().ObjCAutoRefCount) return;
7350 
7351   E = ImplicitCastExpr::Create(
7352       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7353       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7354   Cleanup.setExprNeedsCleanups(true);
7355 }
7356 
7357 /// Prepare a conversion of the given expression to an ObjC object
7358 /// pointer type.
7359 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7360   QualType type = E.get()->getType();
7361   if (type->isObjCObjectPointerType()) {
7362     return CK_BitCast;
7363   } else if (type->isBlockPointerType()) {
7364     maybeExtendBlockObject(E);
7365     return CK_BlockPointerToObjCPointerCast;
7366   } else {
7367     assert(type->isPointerType());
7368     return CK_CPointerToObjCPointerCast;
7369   }
7370 }
7371 
7372 /// Prepares for a scalar cast, performing all the necessary stages
7373 /// except the final cast and returning the kind required.
7374 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7375   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7376   // Also, callers should have filtered out the invalid cases with
7377   // pointers.  Everything else should be possible.
7378 
7379   QualType SrcTy = Src.get()->getType();
7380   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7381     return CK_NoOp;
7382 
7383   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7384   case Type::STK_MemberPointer:
7385     llvm_unreachable("member pointer type in C");
7386 
7387   case Type::STK_CPointer:
7388   case Type::STK_BlockPointer:
7389   case Type::STK_ObjCObjectPointer:
7390     switch (DestTy->getScalarTypeKind()) {
7391     case Type::STK_CPointer: {
7392       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7393       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7394       if (SrcAS != DestAS)
7395         return CK_AddressSpaceConversion;
7396       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7397         return CK_NoOp;
7398       return CK_BitCast;
7399     }
7400     case Type::STK_BlockPointer:
7401       return (SrcKind == Type::STK_BlockPointer
7402                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7403     case Type::STK_ObjCObjectPointer:
7404       if (SrcKind == Type::STK_ObjCObjectPointer)
7405         return CK_BitCast;
7406       if (SrcKind == Type::STK_CPointer)
7407         return CK_CPointerToObjCPointerCast;
7408       maybeExtendBlockObject(Src);
7409       return CK_BlockPointerToObjCPointerCast;
7410     case Type::STK_Bool:
7411       return CK_PointerToBoolean;
7412     case Type::STK_Integral:
7413       return CK_PointerToIntegral;
7414     case Type::STK_Floating:
7415     case Type::STK_FloatingComplex:
7416     case Type::STK_IntegralComplex:
7417     case Type::STK_MemberPointer:
7418     case Type::STK_FixedPoint:
7419       llvm_unreachable("illegal cast from pointer");
7420     }
7421     llvm_unreachable("Should have returned before this");
7422 
7423   case Type::STK_FixedPoint:
7424     switch (DestTy->getScalarTypeKind()) {
7425     case Type::STK_FixedPoint:
7426       return CK_FixedPointCast;
7427     case Type::STK_Bool:
7428       return CK_FixedPointToBoolean;
7429     case Type::STK_Integral:
7430       return CK_FixedPointToIntegral;
7431     case Type::STK_Floating:
7432       return CK_FixedPointToFloating;
7433     case Type::STK_IntegralComplex:
7434     case Type::STK_FloatingComplex:
7435       Diag(Src.get()->getExprLoc(),
7436            diag::err_unimplemented_conversion_with_fixed_point_type)
7437           << DestTy;
7438       return CK_IntegralCast;
7439     case Type::STK_CPointer:
7440     case Type::STK_ObjCObjectPointer:
7441     case Type::STK_BlockPointer:
7442     case Type::STK_MemberPointer:
7443       llvm_unreachable("illegal cast to pointer type");
7444     }
7445     llvm_unreachable("Should have returned before this");
7446 
7447   case Type::STK_Bool: // casting from bool is like casting from an integer
7448   case Type::STK_Integral:
7449     switch (DestTy->getScalarTypeKind()) {
7450     case Type::STK_CPointer:
7451     case Type::STK_ObjCObjectPointer:
7452     case Type::STK_BlockPointer:
7453       if (Src.get()->isNullPointerConstant(Context,
7454                                            Expr::NPC_ValueDependentIsNull))
7455         return CK_NullToPointer;
7456       return CK_IntegralToPointer;
7457     case Type::STK_Bool:
7458       return CK_IntegralToBoolean;
7459     case Type::STK_Integral:
7460       return CK_IntegralCast;
7461     case Type::STK_Floating:
7462       return CK_IntegralToFloating;
7463     case Type::STK_IntegralComplex:
7464       Src = ImpCastExprToType(Src.get(),
7465                       DestTy->castAs<ComplexType>()->getElementType(),
7466                       CK_IntegralCast);
7467       return CK_IntegralRealToComplex;
7468     case Type::STK_FloatingComplex:
7469       Src = ImpCastExprToType(Src.get(),
7470                       DestTy->castAs<ComplexType>()->getElementType(),
7471                       CK_IntegralToFloating);
7472       return CK_FloatingRealToComplex;
7473     case Type::STK_MemberPointer:
7474       llvm_unreachable("member pointer type in C");
7475     case Type::STK_FixedPoint:
7476       return CK_IntegralToFixedPoint;
7477     }
7478     llvm_unreachable("Should have returned before this");
7479 
7480   case Type::STK_Floating:
7481     switch (DestTy->getScalarTypeKind()) {
7482     case Type::STK_Floating:
7483       return CK_FloatingCast;
7484     case Type::STK_Bool:
7485       return CK_FloatingToBoolean;
7486     case Type::STK_Integral:
7487       return CK_FloatingToIntegral;
7488     case Type::STK_FloatingComplex:
7489       Src = ImpCastExprToType(Src.get(),
7490                               DestTy->castAs<ComplexType>()->getElementType(),
7491                               CK_FloatingCast);
7492       return CK_FloatingRealToComplex;
7493     case Type::STK_IntegralComplex:
7494       Src = ImpCastExprToType(Src.get(),
7495                               DestTy->castAs<ComplexType>()->getElementType(),
7496                               CK_FloatingToIntegral);
7497       return CK_IntegralRealToComplex;
7498     case Type::STK_CPointer:
7499     case Type::STK_ObjCObjectPointer:
7500     case Type::STK_BlockPointer:
7501       llvm_unreachable("valid float->pointer cast?");
7502     case Type::STK_MemberPointer:
7503       llvm_unreachable("member pointer type in C");
7504     case Type::STK_FixedPoint:
7505       return CK_FloatingToFixedPoint;
7506     }
7507     llvm_unreachable("Should have returned before this");
7508 
7509   case Type::STK_FloatingComplex:
7510     switch (DestTy->getScalarTypeKind()) {
7511     case Type::STK_FloatingComplex:
7512       return CK_FloatingComplexCast;
7513     case Type::STK_IntegralComplex:
7514       return CK_FloatingComplexToIntegralComplex;
7515     case Type::STK_Floating: {
7516       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7517       if (Context.hasSameType(ET, DestTy))
7518         return CK_FloatingComplexToReal;
7519       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7520       return CK_FloatingCast;
7521     }
7522     case Type::STK_Bool:
7523       return CK_FloatingComplexToBoolean;
7524     case Type::STK_Integral:
7525       Src = ImpCastExprToType(Src.get(),
7526                               SrcTy->castAs<ComplexType>()->getElementType(),
7527                               CK_FloatingComplexToReal);
7528       return CK_FloatingToIntegral;
7529     case Type::STK_CPointer:
7530     case Type::STK_ObjCObjectPointer:
7531     case Type::STK_BlockPointer:
7532       llvm_unreachable("valid complex float->pointer cast?");
7533     case Type::STK_MemberPointer:
7534       llvm_unreachable("member pointer type in C");
7535     case Type::STK_FixedPoint:
7536       Diag(Src.get()->getExprLoc(),
7537            diag::err_unimplemented_conversion_with_fixed_point_type)
7538           << SrcTy;
7539       return CK_IntegralCast;
7540     }
7541     llvm_unreachable("Should have returned before this");
7542 
7543   case Type::STK_IntegralComplex:
7544     switch (DestTy->getScalarTypeKind()) {
7545     case Type::STK_FloatingComplex:
7546       return CK_IntegralComplexToFloatingComplex;
7547     case Type::STK_IntegralComplex:
7548       return CK_IntegralComplexCast;
7549     case Type::STK_Integral: {
7550       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7551       if (Context.hasSameType(ET, DestTy))
7552         return CK_IntegralComplexToReal;
7553       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7554       return CK_IntegralCast;
7555     }
7556     case Type::STK_Bool:
7557       return CK_IntegralComplexToBoolean;
7558     case Type::STK_Floating:
7559       Src = ImpCastExprToType(Src.get(),
7560                               SrcTy->castAs<ComplexType>()->getElementType(),
7561                               CK_IntegralComplexToReal);
7562       return CK_IntegralToFloating;
7563     case Type::STK_CPointer:
7564     case Type::STK_ObjCObjectPointer:
7565     case Type::STK_BlockPointer:
7566       llvm_unreachable("valid complex int->pointer cast?");
7567     case Type::STK_MemberPointer:
7568       llvm_unreachable("member pointer type in C");
7569     case Type::STK_FixedPoint:
7570       Diag(Src.get()->getExprLoc(),
7571            diag::err_unimplemented_conversion_with_fixed_point_type)
7572           << SrcTy;
7573       return CK_IntegralCast;
7574     }
7575     llvm_unreachable("Should have returned before this");
7576   }
7577 
7578   llvm_unreachable("Unhandled scalar cast");
7579 }
7580 
7581 static bool breakDownVectorType(QualType type, uint64_t &len,
7582                                 QualType &eltType) {
7583   // Vectors are simple.
7584   if (const VectorType *vecType = type->getAs<VectorType>()) {
7585     len = vecType->getNumElements();
7586     eltType = vecType->getElementType();
7587     assert(eltType->isScalarType());
7588     return true;
7589   }
7590 
7591   // We allow lax conversion to and from non-vector types, but only if
7592   // they're real types (i.e. non-complex, non-pointer scalar types).
7593   if (!type->isRealType()) return false;
7594 
7595   len = 1;
7596   eltType = type;
7597   return true;
7598 }
7599 
7600 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7601 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7602 /// allowed?
7603 ///
7604 /// This will also return false if the two given types do not make sense from
7605 /// the perspective of SVE bitcasts.
7606 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7607   assert(srcTy->isVectorType() || destTy->isVectorType());
7608 
7609   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7610     if (!FirstType->isSizelessBuiltinType())
7611       return false;
7612 
7613     const auto *VecTy = SecondType->getAs<VectorType>();
7614     return VecTy &&
7615            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7616   };
7617 
7618   return ValidScalableConversion(srcTy, destTy) ||
7619          ValidScalableConversion(destTy, srcTy);
7620 }
7621 
7622 /// Are the two types matrix types and do they have the same dimensions i.e.
7623 /// do they have the same number of rows and the same number of columns?
7624 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7625   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7626     return false;
7627 
7628   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7629   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7630 
7631   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7632          matSrcType->getNumColumns() == matDestType->getNumColumns();
7633 }
7634 
7635 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7636   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7637 
7638   uint64_t SrcLen, DestLen;
7639   QualType SrcEltTy, DestEltTy;
7640   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7641     return false;
7642   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7643     return false;
7644 
7645   // ASTContext::getTypeSize will return the size rounded up to a
7646   // power of 2, so instead of using that, we need to use the raw
7647   // element size multiplied by the element count.
7648   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7649   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7650 
7651   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7652 }
7653 
7654 /// Are the two types lax-compatible vector types?  That is, given
7655 /// that one of them is a vector, do they have equal storage sizes,
7656 /// where the storage size is the number of elements times the element
7657 /// size?
7658 ///
7659 /// This will also return false if either of the types is neither a
7660 /// vector nor a real type.
7661 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7662   assert(destTy->isVectorType() || srcTy->isVectorType());
7663 
7664   // Disallow lax conversions between scalars and ExtVectors (these
7665   // conversions are allowed for other vector types because common headers
7666   // depend on them).  Most scalar OP ExtVector cases are handled by the
7667   // splat path anyway, which does what we want (convert, not bitcast).
7668   // What this rules out for ExtVectors is crazy things like char4*float.
7669   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7670   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7671 
7672   return areVectorTypesSameSize(srcTy, destTy);
7673 }
7674 
7675 /// Is this a legal conversion between two types, one of which is
7676 /// known to be a vector type?
7677 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7678   assert(destTy->isVectorType() || srcTy->isVectorType());
7679 
7680   switch (Context.getLangOpts().getLaxVectorConversions()) {
7681   case LangOptions::LaxVectorConversionKind::None:
7682     return false;
7683 
7684   case LangOptions::LaxVectorConversionKind::Integer:
7685     if (!srcTy->isIntegralOrEnumerationType()) {
7686       auto *Vec = srcTy->getAs<VectorType>();
7687       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7688         return false;
7689     }
7690     if (!destTy->isIntegralOrEnumerationType()) {
7691       auto *Vec = destTy->getAs<VectorType>();
7692       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7693         return false;
7694     }
7695     // OK, integer (vector) -> integer (vector) bitcast.
7696     break;
7697 
7698     case LangOptions::LaxVectorConversionKind::All:
7699     break;
7700   }
7701 
7702   return areLaxCompatibleVectorTypes(srcTy, destTy);
7703 }
7704 
7705 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7706                            CastKind &Kind) {
7707   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7708     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7709       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7710              << DestTy << SrcTy << R;
7711     }
7712   } else if (SrcTy->isMatrixType()) {
7713     return Diag(R.getBegin(),
7714                 diag::err_invalid_conversion_between_matrix_and_type)
7715            << SrcTy << DestTy << R;
7716   } else if (DestTy->isMatrixType()) {
7717     return Diag(R.getBegin(),
7718                 diag::err_invalid_conversion_between_matrix_and_type)
7719            << DestTy << SrcTy << R;
7720   }
7721 
7722   Kind = CK_MatrixCast;
7723   return false;
7724 }
7725 
7726 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7727                            CastKind &Kind) {
7728   assert(VectorTy->isVectorType() && "Not a vector type!");
7729 
7730   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7731     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7732       return Diag(R.getBegin(),
7733                   Ty->isVectorType() ?
7734                   diag::err_invalid_conversion_between_vectors :
7735                   diag::err_invalid_conversion_between_vector_and_integer)
7736         << VectorTy << Ty << R;
7737   } else
7738     return Diag(R.getBegin(),
7739                 diag::err_invalid_conversion_between_vector_and_scalar)
7740       << VectorTy << Ty << R;
7741 
7742   Kind = CK_BitCast;
7743   return false;
7744 }
7745 
7746 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7747   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7748 
7749   if (DestElemTy == SplattedExpr->getType())
7750     return SplattedExpr;
7751 
7752   assert(DestElemTy->isFloatingType() ||
7753          DestElemTy->isIntegralOrEnumerationType());
7754 
7755   CastKind CK;
7756   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7757     // OpenCL requires that we convert `true` boolean expressions to -1, but
7758     // only when splatting vectors.
7759     if (DestElemTy->isFloatingType()) {
7760       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7761       // in two steps: boolean to signed integral, then to floating.
7762       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7763                                                  CK_BooleanToSignedIntegral);
7764       SplattedExpr = CastExprRes.get();
7765       CK = CK_IntegralToFloating;
7766     } else {
7767       CK = CK_BooleanToSignedIntegral;
7768     }
7769   } else {
7770     ExprResult CastExprRes = SplattedExpr;
7771     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7772     if (CastExprRes.isInvalid())
7773       return ExprError();
7774     SplattedExpr = CastExprRes.get();
7775   }
7776   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7777 }
7778 
7779 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7780                                     Expr *CastExpr, CastKind &Kind) {
7781   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7782 
7783   QualType SrcTy = CastExpr->getType();
7784 
7785   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7786   // an ExtVectorType.
7787   // In OpenCL, casts between vectors of different types are not allowed.
7788   // (See OpenCL 6.2).
7789   if (SrcTy->isVectorType()) {
7790     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7791         (getLangOpts().OpenCL &&
7792          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7793       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7794         << DestTy << SrcTy << R;
7795       return ExprError();
7796     }
7797     Kind = CK_BitCast;
7798     return CastExpr;
7799   }
7800 
7801   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7802   // conversion will take place first from scalar to elt type, and then
7803   // splat from elt type to vector.
7804   if (SrcTy->isPointerType())
7805     return Diag(R.getBegin(),
7806                 diag::err_invalid_conversion_between_vector_and_scalar)
7807       << DestTy << SrcTy << R;
7808 
7809   Kind = CK_VectorSplat;
7810   return prepareVectorSplat(DestTy, CastExpr);
7811 }
7812 
7813 ExprResult
7814 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7815                     Declarator &D, ParsedType &Ty,
7816                     SourceLocation RParenLoc, Expr *CastExpr) {
7817   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7818          "ActOnCastExpr(): missing type or expr");
7819 
7820   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7821   if (D.isInvalidType())
7822     return ExprError();
7823 
7824   if (getLangOpts().CPlusPlus) {
7825     // Check that there are no default arguments (C++ only).
7826     CheckExtraCXXDefaultArguments(D);
7827   } else {
7828     // Make sure any TypoExprs have been dealt with.
7829     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7830     if (!Res.isUsable())
7831       return ExprError();
7832     CastExpr = Res.get();
7833   }
7834 
7835   checkUnusedDeclAttributes(D);
7836 
7837   QualType castType = castTInfo->getType();
7838   Ty = CreateParsedType(castType, castTInfo);
7839 
7840   bool isVectorLiteral = false;
7841 
7842   // Check for an altivec or OpenCL literal,
7843   // i.e. all the elements are integer constants.
7844   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7845   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7846   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7847        && castType->isVectorType() && (PE || PLE)) {
7848     if (PLE && PLE->getNumExprs() == 0) {
7849       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7850       return ExprError();
7851     }
7852     if (PE || PLE->getNumExprs() == 1) {
7853       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7854       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7855         isVectorLiteral = true;
7856     }
7857     else
7858       isVectorLiteral = true;
7859   }
7860 
7861   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7862   // then handle it as such.
7863   if (isVectorLiteral)
7864     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7865 
7866   // If the Expr being casted is a ParenListExpr, handle it specially.
7867   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7868   // sequence of BinOp comma operators.
7869   if (isa<ParenListExpr>(CastExpr)) {
7870     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7871     if (Result.isInvalid()) return ExprError();
7872     CastExpr = Result.get();
7873   }
7874 
7875   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7876     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7877 
7878   CheckTollFreeBridgeCast(castType, CastExpr);
7879 
7880   CheckObjCBridgeRelatedCast(castType, CastExpr);
7881 
7882   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7883 
7884   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7885 }
7886 
7887 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7888                                     SourceLocation RParenLoc, Expr *E,
7889                                     TypeSourceInfo *TInfo) {
7890   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7891          "Expected paren or paren list expression");
7892 
7893   Expr **exprs;
7894   unsigned numExprs;
7895   Expr *subExpr;
7896   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7897   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7898     LiteralLParenLoc = PE->getLParenLoc();
7899     LiteralRParenLoc = PE->getRParenLoc();
7900     exprs = PE->getExprs();
7901     numExprs = PE->getNumExprs();
7902   } else { // isa<ParenExpr> by assertion at function entrance
7903     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7904     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7905     subExpr = cast<ParenExpr>(E)->getSubExpr();
7906     exprs = &subExpr;
7907     numExprs = 1;
7908   }
7909 
7910   QualType Ty = TInfo->getType();
7911   assert(Ty->isVectorType() && "Expected vector type");
7912 
7913   SmallVector<Expr *, 8> initExprs;
7914   const VectorType *VTy = Ty->castAs<VectorType>();
7915   unsigned numElems = VTy->getNumElements();
7916 
7917   // '(...)' form of vector initialization in AltiVec: the number of
7918   // initializers must be one or must match the size of the vector.
7919   // If a single value is specified in the initializer then it will be
7920   // replicated to all the components of the vector
7921   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7922                                  VTy->getElementType()))
7923     return ExprError();
7924   if (ShouldSplatAltivecScalarInCast(VTy)) {
7925     // The number of initializers must be one or must match the size of the
7926     // vector. If a single value is specified in the initializer then it will
7927     // be replicated to all the components of the vector
7928     if (numExprs == 1) {
7929       QualType ElemTy = VTy->getElementType();
7930       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7931       if (Literal.isInvalid())
7932         return ExprError();
7933       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7934                                   PrepareScalarCast(Literal, ElemTy));
7935       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7936     }
7937     else if (numExprs < numElems) {
7938       Diag(E->getExprLoc(),
7939            diag::err_incorrect_number_of_vector_initializers);
7940       return ExprError();
7941     }
7942     else
7943       initExprs.append(exprs, exprs + numExprs);
7944   }
7945   else {
7946     // For OpenCL, when the number of initializers is a single value,
7947     // it will be replicated to all components of the vector.
7948     if (getLangOpts().OpenCL &&
7949         VTy->getVectorKind() == VectorType::GenericVector &&
7950         numExprs == 1) {
7951         QualType ElemTy = VTy->getElementType();
7952         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7953         if (Literal.isInvalid())
7954           return ExprError();
7955         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7956                                     PrepareScalarCast(Literal, ElemTy));
7957         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7958     }
7959 
7960     initExprs.append(exprs, exprs + numExprs);
7961   }
7962   // FIXME: This means that pretty-printing the final AST will produce curly
7963   // braces instead of the original commas.
7964   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7965                                                    initExprs, LiteralRParenLoc);
7966   initE->setType(Ty);
7967   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7968 }
7969 
7970 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7971 /// the ParenListExpr into a sequence of comma binary operators.
7972 ExprResult
7973 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7974   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7975   if (!E)
7976     return OrigExpr;
7977 
7978   ExprResult Result(E->getExpr(0));
7979 
7980   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7981     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7982                         E->getExpr(i));
7983 
7984   if (Result.isInvalid()) return ExprError();
7985 
7986   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7987 }
7988 
7989 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7990                                     SourceLocation R,
7991                                     MultiExprArg Val) {
7992   return ParenListExpr::Create(Context, L, Val, R);
7993 }
7994 
7995 /// Emit a specialized diagnostic when one expression is a null pointer
7996 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7997 /// emitted.
7998 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7999                                       SourceLocation QuestionLoc) {
8000   Expr *NullExpr = LHSExpr;
8001   Expr *NonPointerExpr = RHSExpr;
8002   Expr::NullPointerConstantKind NullKind =
8003       NullExpr->isNullPointerConstant(Context,
8004                                       Expr::NPC_ValueDependentIsNotNull);
8005 
8006   if (NullKind == Expr::NPCK_NotNull) {
8007     NullExpr = RHSExpr;
8008     NonPointerExpr = LHSExpr;
8009     NullKind =
8010         NullExpr->isNullPointerConstant(Context,
8011                                         Expr::NPC_ValueDependentIsNotNull);
8012   }
8013 
8014   if (NullKind == Expr::NPCK_NotNull)
8015     return false;
8016 
8017   if (NullKind == Expr::NPCK_ZeroExpression)
8018     return false;
8019 
8020   if (NullKind == Expr::NPCK_ZeroLiteral) {
8021     // In this case, check to make sure that we got here from a "NULL"
8022     // string in the source code.
8023     NullExpr = NullExpr->IgnoreParenImpCasts();
8024     SourceLocation loc = NullExpr->getExprLoc();
8025     if (!findMacroSpelling(loc, "NULL"))
8026       return false;
8027   }
8028 
8029   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8030   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8031       << NonPointerExpr->getType() << DiagType
8032       << NonPointerExpr->getSourceRange();
8033   return true;
8034 }
8035 
8036 /// Return false if the condition expression is valid, true otherwise.
8037 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8038   QualType CondTy = Cond->getType();
8039 
8040   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8041   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8042     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8043       << CondTy << Cond->getSourceRange();
8044     return true;
8045   }
8046 
8047   // C99 6.5.15p2
8048   if (CondTy->isScalarType()) return false;
8049 
8050   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8051     << CondTy << Cond->getSourceRange();
8052   return true;
8053 }
8054 
8055 /// Handle when one or both operands are void type.
8056 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8057                                          ExprResult &RHS) {
8058     Expr *LHSExpr = LHS.get();
8059     Expr *RHSExpr = RHS.get();
8060 
8061     if (!LHSExpr->getType()->isVoidType())
8062       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8063           << RHSExpr->getSourceRange();
8064     if (!RHSExpr->getType()->isVoidType())
8065       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8066           << LHSExpr->getSourceRange();
8067     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8068     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8069     return S.Context.VoidTy;
8070 }
8071 
8072 /// Return false if the NullExpr can be promoted to PointerTy,
8073 /// true otherwise.
8074 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8075                                         QualType PointerTy) {
8076   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8077       !NullExpr.get()->isNullPointerConstant(S.Context,
8078                                             Expr::NPC_ValueDependentIsNull))
8079     return true;
8080 
8081   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8082   return false;
8083 }
8084 
8085 /// Checks compatibility between two pointers and return the resulting
8086 /// type.
8087 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8088                                                      ExprResult &RHS,
8089                                                      SourceLocation Loc) {
8090   QualType LHSTy = LHS.get()->getType();
8091   QualType RHSTy = RHS.get()->getType();
8092 
8093   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8094     // Two identical pointers types are always compatible.
8095     return LHSTy;
8096   }
8097 
8098   QualType lhptee, rhptee;
8099 
8100   // Get the pointee types.
8101   bool IsBlockPointer = false;
8102   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8103     lhptee = LHSBTy->getPointeeType();
8104     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8105     IsBlockPointer = true;
8106   } else {
8107     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8108     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8109   }
8110 
8111   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8112   // differently qualified versions of compatible types, the result type is
8113   // a pointer to an appropriately qualified version of the composite
8114   // type.
8115 
8116   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8117   // clause doesn't make sense for our extensions. E.g. address space 2 should
8118   // be incompatible with address space 3: they may live on different devices or
8119   // anything.
8120   Qualifiers lhQual = lhptee.getQualifiers();
8121   Qualifiers rhQual = rhptee.getQualifiers();
8122 
8123   LangAS ResultAddrSpace = LangAS::Default;
8124   LangAS LAddrSpace = lhQual.getAddressSpace();
8125   LangAS RAddrSpace = rhQual.getAddressSpace();
8126 
8127   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8128   // spaces is disallowed.
8129   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8130     ResultAddrSpace = LAddrSpace;
8131   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8132     ResultAddrSpace = RAddrSpace;
8133   else {
8134     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8135         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8136         << RHS.get()->getSourceRange();
8137     return QualType();
8138   }
8139 
8140   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8141   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8142   lhQual.removeCVRQualifiers();
8143   rhQual.removeCVRQualifiers();
8144 
8145   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8146   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8147   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8148   // qual types are compatible iff
8149   //  * corresponded types are compatible
8150   //  * CVR qualifiers are equal
8151   //  * address spaces are equal
8152   // Thus for conditional operator we merge CVR and address space unqualified
8153   // pointees and if there is a composite type we return a pointer to it with
8154   // merged qualifiers.
8155   LHSCastKind =
8156       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8157   RHSCastKind =
8158       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8159   lhQual.removeAddressSpace();
8160   rhQual.removeAddressSpace();
8161 
8162   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8163   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8164 
8165   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8166 
8167   if (CompositeTy.isNull()) {
8168     // In this situation, we assume void* type. No especially good
8169     // reason, but this is what gcc does, and we do have to pick
8170     // to get a consistent AST.
8171     QualType incompatTy;
8172     incompatTy = S.Context.getPointerType(
8173         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8174     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8175     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8176 
8177     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8178     // for casts between types with incompatible address space qualifiers.
8179     // For the following code the compiler produces casts between global and
8180     // local address spaces of the corresponded innermost pointees:
8181     // local int *global *a;
8182     // global int *global *b;
8183     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8184     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8185         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8186         << RHS.get()->getSourceRange();
8187 
8188     return incompatTy;
8189   }
8190 
8191   // The pointer types are compatible.
8192   // In case of OpenCL ResultTy should have the address space qualifier
8193   // which is a superset of address spaces of both the 2nd and the 3rd
8194   // operands of the conditional operator.
8195   QualType ResultTy = [&, ResultAddrSpace]() {
8196     if (S.getLangOpts().OpenCL) {
8197       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8198       CompositeQuals.setAddressSpace(ResultAddrSpace);
8199       return S.Context
8200           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8201           .withCVRQualifiers(MergedCVRQual);
8202     }
8203     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8204   }();
8205   if (IsBlockPointer)
8206     ResultTy = S.Context.getBlockPointerType(ResultTy);
8207   else
8208     ResultTy = S.Context.getPointerType(ResultTy);
8209 
8210   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8211   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8212   return ResultTy;
8213 }
8214 
8215 /// Return the resulting type when the operands are both block pointers.
8216 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8217                                                           ExprResult &LHS,
8218                                                           ExprResult &RHS,
8219                                                           SourceLocation Loc) {
8220   QualType LHSTy = LHS.get()->getType();
8221   QualType RHSTy = RHS.get()->getType();
8222 
8223   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8224     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8225       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8226       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8227       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8228       return destType;
8229     }
8230     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8231       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8232       << RHS.get()->getSourceRange();
8233     return QualType();
8234   }
8235 
8236   // We have 2 block pointer types.
8237   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8238 }
8239 
8240 /// Return the resulting type when the operands are both pointers.
8241 static QualType
8242 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8243                                             ExprResult &RHS,
8244                                             SourceLocation Loc) {
8245   // get the pointer types
8246   QualType LHSTy = LHS.get()->getType();
8247   QualType RHSTy = RHS.get()->getType();
8248 
8249   // get the "pointed to" types
8250   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8251   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8252 
8253   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8254   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8255     // Figure out necessary qualifiers (C99 6.5.15p6)
8256     QualType destPointee
8257       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8258     QualType destType = S.Context.getPointerType(destPointee);
8259     // Add qualifiers if necessary.
8260     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8261     // Promote to void*.
8262     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8263     return destType;
8264   }
8265   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8266     QualType destPointee
8267       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8268     QualType destType = S.Context.getPointerType(destPointee);
8269     // Add qualifiers if necessary.
8270     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8271     // Promote to void*.
8272     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8273     return destType;
8274   }
8275 
8276   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8277 }
8278 
8279 /// Return false if the first expression is not an integer and the second
8280 /// expression is not a pointer, true otherwise.
8281 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8282                                         Expr* PointerExpr, SourceLocation Loc,
8283                                         bool IsIntFirstExpr) {
8284   if (!PointerExpr->getType()->isPointerType() ||
8285       !Int.get()->getType()->isIntegerType())
8286     return false;
8287 
8288   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8289   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8290 
8291   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8292     << Expr1->getType() << Expr2->getType()
8293     << Expr1->getSourceRange() << Expr2->getSourceRange();
8294   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8295                             CK_IntegralToPointer);
8296   return true;
8297 }
8298 
8299 /// Simple conversion between integer and floating point types.
8300 ///
8301 /// Used when handling the OpenCL conditional operator where the
8302 /// condition is a vector while the other operands are scalar.
8303 ///
8304 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8305 /// types are either integer or floating type. Between the two
8306 /// operands, the type with the higher rank is defined as the "result
8307 /// type". The other operand needs to be promoted to the same type. No
8308 /// other type promotion is allowed. We cannot use
8309 /// UsualArithmeticConversions() for this purpose, since it always
8310 /// promotes promotable types.
8311 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8312                                             ExprResult &RHS,
8313                                             SourceLocation QuestionLoc) {
8314   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8315   if (LHS.isInvalid())
8316     return QualType();
8317   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8318   if (RHS.isInvalid())
8319     return QualType();
8320 
8321   // For conversion purposes, we ignore any qualifiers.
8322   // For example, "const float" and "float" are equivalent.
8323   QualType LHSType =
8324     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8325   QualType RHSType =
8326     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8327 
8328   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8329     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8330       << LHSType << LHS.get()->getSourceRange();
8331     return QualType();
8332   }
8333 
8334   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8335     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8336       << RHSType << RHS.get()->getSourceRange();
8337     return QualType();
8338   }
8339 
8340   // If both types are identical, no conversion is needed.
8341   if (LHSType == RHSType)
8342     return LHSType;
8343 
8344   // Now handle "real" floating types (i.e. float, double, long double).
8345   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8346     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8347                                  /*IsCompAssign = */ false);
8348 
8349   // Finally, we have two differing integer types.
8350   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8351   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8352 }
8353 
8354 /// Convert scalar operands to a vector that matches the
8355 ///        condition in length.
8356 ///
8357 /// Used when handling the OpenCL conditional operator where the
8358 /// condition is a vector while the other operands are scalar.
8359 ///
8360 /// We first compute the "result type" for the scalar operands
8361 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8362 /// into a vector of that type where the length matches the condition
8363 /// vector type. s6.11.6 requires that the element types of the result
8364 /// and the condition must have the same number of bits.
8365 static QualType
8366 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8367                               QualType CondTy, SourceLocation QuestionLoc) {
8368   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8369   if (ResTy.isNull()) return QualType();
8370 
8371   const VectorType *CV = CondTy->getAs<VectorType>();
8372   assert(CV);
8373 
8374   // Determine the vector result type
8375   unsigned NumElements = CV->getNumElements();
8376   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8377 
8378   // Ensure that all types have the same number of bits
8379   if (S.Context.getTypeSize(CV->getElementType())
8380       != S.Context.getTypeSize(ResTy)) {
8381     // Since VectorTy is created internally, it does not pretty print
8382     // with an OpenCL name. Instead, we just print a description.
8383     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8384     SmallString<64> Str;
8385     llvm::raw_svector_ostream OS(Str);
8386     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8387     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8388       << CondTy << OS.str();
8389     return QualType();
8390   }
8391 
8392   // Convert operands to the vector result type
8393   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8394   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8395 
8396   return VectorTy;
8397 }
8398 
8399 /// Return false if this is a valid OpenCL condition vector
8400 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8401                                        SourceLocation QuestionLoc) {
8402   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8403   // integral type.
8404   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8405   assert(CondTy);
8406   QualType EleTy = CondTy->getElementType();
8407   if (EleTy->isIntegerType()) return false;
8408 
8409   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8410     << Cond->getType() << Cond->getSourceRange();
8411   return true;
8412 }
8413 
8414 /// Return false if the vector condition type and the vector
8415 ///        result type are compatible.
8416 ///
8417 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8418 /// number of elements, and their element types have the same number
8419 /// of bits.
8420 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8421                               SourceLocation QuestionLoc) {
8422   const VectorType *CV = CondTy->getAs<VectorType>();
8423   const VectorType *RV = VecResTy->getAs<VectorType>();
8424   assert(CV && RV);
8425 
8426   if (CV->getNumElements() != RV->getNumElements()) {
8427     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8428       << CondTy << VecResTy;
8429     return true;
8430   }
8431 
8432   QualType CVE = CV->getElementType();
8433   QualType RVE = RV->getElementType();
8434 
8435   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8436     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8437       << CondTy << VecResTy;
8438     return true;
8439   }
8440 
8441   return false;
8442 }
8443 
8444 /// Return the resulting type for the conditional operator in
8445 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8446 ///        s6.3.i) when the condition is a vector type.
8447 static QualType
8448 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8449                              ExprResult &LHS, ExprResult &RHS,
8450                              SourceLocation QuestionLoc) {
8451   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8452   if (Cond.isInvalid())
8453     return QualType();
8454   QualType CondTy = Cond.get()->getType();
8455 
8456   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8457     return QualType();
8458 
8459   // If either operand is a vector then find the vector type of the
8460   // result as specified in OpenCL v1.1 s6.3.i.
8461   if (LHS.get()->getType()->isVectorType() ||
8462       RHS.get()->getType()->isVectorType()) {
8463     bool IsBoolVecLang =
8464         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8465     QualType VecResTy =
8466         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8467                               /*isCompAssign*/ false,
8468                               /*AllowBothBool*/ true,
8469                               /*AllowBoolConversions*/ false,
8470                               /*AllowBooleanOperation*/ IsBoolVecLang,
8471                               /*ReportInvalid*/ true);
8472     if (VecResTy.isNull())
8473       return QualType();
8474     // The result type must match the condition type as specified in
8475     // OpenCL v1.1 s6.11.6.
8476     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8477       return QualType();
8478     return VecResTy;
8479   }
8480 
8481   // Both operands are scalar.
8482   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8483 }
8484 
8485 /// Return true if the Expr is block type
8486 static bool checkBlockType(Sema &S, const Expr *E) {
8487   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8488     QualType Ty = CE->getCallee()->getType();
8489     if (Ty->isBlockPointerType()) {
8490       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8491       return true;
8492     }
8493   }
8494   return false;
8495 }
8496 
8497 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8498 /// In that case, LHS = cond.
8499 /// C99 6.5.15
8500 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8501                                         ExprResult &RHS, ExprValueKind &VK,
8502                                         ExprObjectKind &OK,
8503                                         SourceLocation QuestionLoc) {
8504 
8505   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8506   if (!LHSResult.isUsable()) return QualType();
8507   LHS = LHSResult;
8508 
8509   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8510   if (!RHSResult.isUsable()) return QualType();
8511   RHS = RHSResult;
8512 
8513   // C++ is sufficiently different to merit its own checker.
8514   if (getLangOpts().CPlusPlus)
8515     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8516 
8517   VK = VK_PRValue;
8518   OK = OK_Ordinary;
8519 
8520   if (Context.isDependenceAllowed() &&
8521       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8522        RHS.get()->isTypeDependent())) {
8523     assert(!getLangOpts().CPlusPlus);
8524     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8525             RHS.get()->containsErrors()) &&
8526            "should only occur in error-recovery path.");
8527     return Context.DependentTy;
8528   }
8529 
8530   // The OpenCL operator with a vector condition is sufficiently
8531   // different to merit its own checker.
8532   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8533       Cond.get()->getType()->isExtVectorType())
8534     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8535 
8536   // First, check the condition.
8537   Cond = UsualUnaryConversions(Cond.get());
8538   if (Cond.isInvalid())
8539     return QualType();
8540   if (checkCondition(*this, Cond.get(), QuestionLoc))
8541     return QualType();
8542 
8543   // Now check the two expressions.
8544   if (LHS.get()->getType()->isVectorType() ||
8545       RHS.get()->getType()->isVectorType())
8546     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8547                                /*AllowBothBool*/ true,
8548                                /*AllowBoolConversions*/ false,
8549                                /*AllowBooleanOperation*/ false,
8550                                /*ReportInvalid*/ true);
8551 
8552   QualType ResTy =
8553       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8554   if (LHS.isInvalid() || RHS.isInvalid())
8555     return QualType();
8556 
8557   QualType LHSTy = LHS.get()->getType();
8558   QualType RHSTy = RHS.get()->getType();
8559 
8560   // Diagnose attempts to convert between __ibm128, __float128 and long double
8561   // where such conversions currently can't be handled.
8562   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8563     Diag(QuestionLoc,
8564          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8565       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8566     return QualType();
8567   }
8568 
8569   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8570   // selection operator (?:).
8571   if (getLangOpts().OpenCL &&
8572       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8573     return QualType();
8574   }
8575 
8576   // If both operands have arithmetic type, do the usual arithmetic conversions
8577   // to find a common type: C99 6.5.15p3,5.
8578   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8579     // Disallow invalid arithmetic conversions, such as those between bit-
8580     // precise integers types of different sizes, or between a bit-precise
8581     // integer and another type.
8582     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8583       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8584           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8585           << RHS.get()->getSourceRange();
8586       return QualType();
8587     }
8588 
8589     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8590     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8591 
8592     return ResTy;
8593   }
8594 
8595   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8596   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8597     return LHSTy;
8598   }
8599 
8600   // If both operands are the same structure or union type, the result is that
8601   // type.
8602   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8603     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8604       if (LHSRT->getDecl() == RHSRT->getDecl())
8605         // "If both the operands have structure or union type, the result has
8606         // that type."  This implies that CV qualifiers are dropped.
8607         return LHSTy.getUnqualifiedType();
8608     // FIXME: Type of conditional expression must be complete in C mode.
8609   }
8610 
8611   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8612   // The following || allows only one side to be void (a GCC-ism).
8613   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8614     return checkConditionalVoidType(*this, LHS, RHS);
8615   }
8616 
8617   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8618   // the type of the other operand."
8619   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8620   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8621 
8622   // All objective-c pointer type analysis is done here.
8623   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8624                                                         QuestionLoc);
8625   if (LHS.isInvalid() || RHS.isInvalid())
8626     return QualType();
8627   if (!compositeType.isNull())
8628     return compositeType;
8629 
8630 
8631   // Handle block pointer types.
8632   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8633     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8634                                                      QuestionLoc);
8635 
8636   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8637   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8638     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8639                                                        QuestionLoc);
8640 
8641   // GCC compatibility: soften pointer/integer mismatch.  Note that
8642   // null pointers have been filtered out by this point.
8643   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8644       /*IsIntFirstExpr=*/true))
8645     return RHSTy;
8646   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8647       /*IsIntFirstExpr=*/false))
8648     return LHSTy;
8649 
8650   // Allow ?: operations in which both operands have the same
8651   // built-in sizeless type.
8652   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8653     return LHSTy;
8654 
8655   // Emit a better diagnostic if one of the expressions is a null pointer
8656   // constant and the other is not a pointer type. In this case, the user most
8657   // likely forgot to take the address of the other expression.
8658   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8659     return QualType();
8660 
8661   // Otherwise, the operands are not compatible.
8662   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8663     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8664     << RHS.get()->getSourceRange();
8665   return QualType();
8666 }
8667 
8668 /// FindCompositeObjCPointerType - Helper method to find composite type of
8669 /// two objective-c pointer types of the two input expressions.
8670 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8671                                             SourceLocation QuestionLoc) {
8672   QualType LHSTy = LHS.get()->getType();
8673   QualType RHSTy = RHS.get()->getType();
8674 
8675   // Handle things like Class and struct objc_class*.  Here we case the result
8676   // to the pseudo-builtin, because that will be implicitly cast back to the
8677   // redefinition type if an attempt is made to access its fields.
8678   if (LHSTy->isObjCClassType() &&
8679       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8680     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8681     return LHSTy;
8682   }
8683   if (RHSTy->isObjCClassType() &&
8684       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8685     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8686     return RHSTy;
8687   }
8688   // And the same for struct objc_object* / id
8689   if (LHSTy->isObjCIdType() &&
8690       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8691     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8692     return LHSTy;
8693   }
8694   if (RHSTy->isObjCIdType() &&
8695       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8696     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8697     return RHSTy;
8698   }
8699   // And the same for struct objc_selector* / SEL
8700   if (Context.isObjCSelType(LHSTy) &&
8701       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8702     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8703     return LHSTy;
8704   }
8705   if (Context.isObjCSelType(RHSTy) &&
8706       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8707     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8708     return RHSTy;
8709   }
8710   // Check constraints for Objective-C object pointers types.
8711   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8712 
8713     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8714       // Two identical object pointer types are always compatible.
8715       return LHSTy;
8716     }
8717     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8718     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8719     QualType compositeType = LHSTy;
8720 
8721     // If both operands are interfaces and either operand can be
8722     // assigned to the other, use that type as the composite
8723     // type. This allows
8724     //   xxx ? (A*) a : (B*) b
8725     // where B is a subclass of A.
8726     //
8727     // Additionally, as for assignment, if either type is 'id'
8728     // allow silent coercion. Finally, if the types are
8729     // incompatible then make sure to use 'id' as the composite
8730     // type so the result is acceptable for sending messages to.
8731 
8732     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8733     // It could return the composite type.
8734     if (!(compositeType =
8735           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8736       // Nothing more to do.
8737     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8738       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8739     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8740       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8741     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8742                 RHSOPT->isObjCQualifiedIdType()) &&
8743                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8744                                                          true)) {
8745       // Need to handle "id<xx>" explicitly.
8746       // GCC allows qualified id and any Objective-C type to devolve to
8747       // id. Currently localizing to here until clear this should be
8748       // part of ObjCQualifiedIdTypesAreCompatible.
8749       compositeType = Context.getObjCIdType();
8750     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8751       compositeType = Context.getObjCIdType();
8752     } else {
8753       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8754       << LHSTy << RHSTy
8755       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8756       QualType incompatTy = Context.getObjCIdType();
8757       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8758       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8759       return incompatTy;
8760     }
8761     // The object pointer types are compatible.
8762     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8763     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8764     return compositeType;
8765   }
8766   // Check Objective-C object pointer types and 'void *'
8767   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8768     if (getLangOpts().ObjCAutoRefCount) {
8769       // ARC forbids the implicit conversion of object pointers to 'void *',
8770       // so these types are not compatible.
8771       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8772           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8773       LHS = RHS = true;
8774       return QualType();
8775     }
8776     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8777     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8778     QualType destPointee
8779     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8780     QualType destType = Context.getPointerType(destPointee);
8781     // Add qualifiers if necessary.
8782     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8783     // Promote to void*.
8784     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8785     return destType;
8786   }
8787   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8788     if (getLangOpts().ObjCAutoRefCount) {
8789       // ARC forbids the implicit conversion of object pointers to 'void *',
8790       // so these types are not compatible.
8791       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8792           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8793       LHS = RHS = true;
8794       return QualType();
8795     }
8796     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8797     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8798     QualType destPointee
8799     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8800     QualType destType = Context.getPointerType(destPointee);
8801     // Add qualifiers if necessary.
8802     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8803     // Promote to void*.
8804     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8805     return destType;
8806   }
8807   return QualType();
8808 }
8809 
8810 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8811 /// ParenRange in parentheses.
8812 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8813                                const PartialDiagnostic &Note,
8814                                SourceRange ParenRange) {
8815   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8816   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8817       EndLoc.isValid()) {
8818     Self.Diag(Loc, Note)
8819       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8820       << FixItHint::CreateInsertion(EndLoc, ")");
8821   } else {
8822     // We can't display the parentheses, so just show the bare note.
8823     Self.Diag(Loc, Note) << ParenRange;
8824   }
8825 }
8826 
8827 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8828   return BinaryOperator::isAdditiveOp(Opc) ||
8829          BinaryOperator::isMultiplicativeOp(Opc) ||
8830          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8831   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8832   // not any of the logical operators.  Bitwise-xor is commonly used as a
8833   // logical-xor because there is no logical-xor operator.  The logical
8834   // operators, including uses of xor, have a high false positive rate for
8835   // precedence warnings.
8836 }
8837 
8838 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8839 /// expression, either using a built-in or overloaded operator,
8840 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8841 /// expression.
8842 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8843                                    Expr **RHSExprs) {
8844   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8845   E = E->IgnoreImpCasts();
8846   E = E->IgnoreConversionOperatorSingleStep();
8847   E = E->IgnoreImpCasts();
8848   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8849     E = MTE->getSubExpr();
8850     E = E->IgnoreImpCasts();
8851   }
8852 
8853   // Built-in binary operator.
8854   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8855     if (IsArithmeticOp(OP->getOpcode())) {
8856       *Opcode = OP->getOpcode();
8857       *RHSExprs = OP->getRHS();
8858       return true;
8859     }
8860   }
8861 
8862   // Overloaded operator.
8863   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8864     if (Call->getNumArgs() != 2)
8865       return false;
8866 
8867     // Make sure this is really a binary operator that is safe to pass into
8868     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8869     OverloadedOperatorKind OO = Call->getOperator();
8870     if (OO < OO_Plus || OO > OO_Arrow ||
8871         OO == OO_PlusPlus || OO == OO_MinusMinus)
8872       return false;
8873 
8874     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8875     if (IsArithmeticOp(OpKind)) {
8876       *Opcode = OpKind;
8877       *RHSExprs = Call->getArg(1);
8878       return true;
8879     }
8880   }
8881 
8882   return false;
8883 }
8884 
8885 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8886 /// or is a logical expression such as (x==y) which has int type, but is
8887 /// commonly interpreted as boolean.
8888 static bool ExprLooksBoolean(Expr *E) {
8889   E = E->IgnoreParenImpCasts();
8890 
8891   if (E->getType()->isBooleanType())
8892     return true;
8893   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8894     return OP->isComparisonOp() || OP->isLogicalOp();
8895   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8896     return OP->getOpcode() == UO_LNot;
8897   if (E->getType()->isPointerType())
8898     return true;
8899   // FIXME: What about overloaded operator calls returning "unspecified boolean
8900   // type"s (commonly pointer-to-members)?
8901 
8902   return false;
8903 }
8904 
8905 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8906 /// and binary operator are mixed in a way that suggests the programmer assumed
8907 /// the conditional operator has higher precedence, for example:
8908 /// "int x = a + someBinaryCondition ? 1 : 2".
8909 static void DiagnoseConditionalPrecedence(Sema &Self,
8910                                           SourceLocation OpLoc,
8911                                           Expr *Condition,
8912                                           Expr *LHSExpr,
8913                                           Expr *RHSExpr) {
8914   BinaryOperatorKind CondOpcode;
8915   Expr *CondRHS;
8916 
8917   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8918     return;
8919   if (!ExprLooksBoolean(CondRHS))
8920     return;
8921 
8922   // The condition is an arithmetic binary expression, with a right-
8923   // hand side that looks boolean, so warn.
8924 
8925   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8926                         ? diag::warn_precedence_bitwise_conditional
8927                         : diag::warn_precedence_conditional;
8928 
8929   Self.Diag(OpLoc, DiagID)
8930       << Condition->getSourceRange()
8931       << BinaryOperator::getOpcodeStr(CondOpcode);
8932 
8933   SuggestParentheses(
8934       Self, OpLoc,
8935       Self.PDiag(diag::note_precedence_silence)
8936           << BinaryOperator::getOpcodeStr(CondOpcode),
8937       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8938 
8939   SuggestParentheses(Self, OpLoc,
8940                      Self.PDiag(diag::note_precedence_conditional_first),
8941                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8942 }
8943 
8944 /// Compute the nullability of a conditional expression.
8945 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8946                                               QualType LHSTy, QualType RHSTy,
8947                                               ASTContext &Ctx) {
8948   if (!ResTy->isAnyPointerType())
8949     return ResTy;
8950 
8951   auto GetNullability = [&Ctx](QualType Ty) {
8952     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8953     if (Kind) {
8954       // For our purposes, treat _Nullable_result as _Nullable.
8955       if (*Kind == NullabilityKind::NullableResult)
8956         return NullabilityKind::Nullable;
8957       return *Kind;
8958     }
8959     return NullabilityKind::Unspecified;
8960   };
8961 
8962   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8963   NullabilityKind MergedKind;
8964 
8965   // Compute nullability of a binary conditional expression.
8966   if (IsBin) {
8967     if (LHSKind == NullabilityKind::NonNull)
8968       MergedKind = NullabilityKind::NonNull;
8969     else
8970       MergedKind = RHSKind;
8971   // Compute nullability of a normal conditional expression.
8972   } else {
8973     if (LHSKind == NullabilityKind::Nullable ||
8974         RHSKind == NullabilityKind::Nullable)
8975       MergedKind = NullabilityKind::Nullable;
8976     else if (LHSKind == NullabilityKind::NonNull)
8977       MergedKind = RHSKind;
8978     else if (RHSKind == NullabilityKind::NonNull)
8979       MergedKind = LHSKind;
8980     else
8981       MergedKind = NullabilityKind::Unspecified;
8982   }
8983 
8984   // Return if ResTy already has the correct nullability.
8985   if (GetNullability(ResTy) == MergedKind)
8986     return ResTy;
8987 
8988   // Strip all nullability from ResTy.
8989   while (ResTy->getNullability(Ctx))
8990     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8991 
8992   // Create a new AttributedType with the new nullability kind.
8993   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8994   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8995 }
8996 
8997 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8998 /// in the case of a the GNU conditional expr extension.
8999 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9000                                     SourceLocation ColonLoc,
9001                                     Expr *CondExpr, Expr *LHSExpr,
9002                                     Expr *RHSExpr) {
9003   if (!Context.isDependenceAllowed()) {
9004     // C cannot handle TypoExpr nodes in the condition because it
9005     // doesn't handle dependent types properly, so make sure any TypoExprs have
9006     // been dealt with before checking the operands.
9007     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9008     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9009     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9010 
9011     if (!CondResult.isUsable())
9012       return ExprError();
9013 
9014     if (LHSExpr) {
9015       if (!LHSResult.isUsable())
9016         return ExprError();
9017     }
9018 
9019     if (!RHSResult.isUsable())
9020       return ExprError();
9021 
9022     CondExpr = CondResult.get();
9023     LHSExpr = LHSResult.get();
9024     RHSExpr = RHSResult.get();
9025   }
9026 
9027   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9028   // was the condition.
9029   OpaqueValueExpr *opaqueValue = nullptr;
9030   Expr *commonExpr = nullptr;
9031   if (!LHSExpr) {
9032     commonExpr = CondExpr;
9033     // Lower out placeholder types first.  This is important so that we don't
9034     // try to capture a placeholder. This happens in few cases in C++; such
9035     // as Objective-C++'s dictionary subscripting syntax.
9036     if (commonExpr->hasPlaceholderType()) {
9037       ExprResult result = CheckPlaceholderExpr(commonExpr);
9038       if (!result.isUsable()) return ExprError();
9039       commonExpr = result.get();
9040     }
9041     // We usually want to apply unary conversions *before* saving, except
9042     // in the special case of a C++ l-value conditional.
9043     if (!(getLangOpts().CPlusPlus
9044           && !commonExpr->isTypeDependent()
9045           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9046           && commonExpr->isGLValue()
9047           && commonExpr->isOrdinaryOrBitFieldObject()
9048           && RHSExpr->isOrdinaryOrBitFieldObject()
9049           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9050       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9051       if (commonRes.isInvalid())
9052         return ExprError();
9053       commonExpr = commonRes.get();
9054     }
9055 
9056     // If the common expression is a class or array prvalue, materialize it
9057     // so that we can safely refer to it multiple times.
9058     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9059                                     commonExpr->getType()->isArrayType())) {
9060       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9061       if (MatExpr.isInvalid())
9062         return ExprError();
9063       commonExpr = MatExpr.get();
9064     }
9065 
9066     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9067                                                 commonExpr->getType(),
9068                                                 commonExpr->getValueKind(),
9069                                                 commonExpr->getObjectKind(),
9070                                                 commonExpr);
9071     LHSExpr = CondExpr = opaqueValue;
9072   }
9073 
9074   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9075   ExprValueKind VK = VK_PRValue;
9076   ExprObjectKind OK = OK_Ordinary;
9077   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9078   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9079                                              VK, OK, QuestionLoc);
9080   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9081       RHS.isInvalid())
9082     return ExprError();
9083 
9084   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9085                                 RHS.get());
9086 
9087   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9088 
9089   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9090                                          Context);
9091 
9092   if (!commonExpr)
9093     return new (Context)
9094         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9095                             RHS.get(), result, VK, OK);
9096 
9097   return new (Context) BinaryConditionalOperator(
9098       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9099       ColonLoc, result, VK, OK);
9100 }
9101 
9102 // Check if we have a conversion between incompatible cmse function pointer
9103 // types, that is, a conversion between a function pointer with the
9104 // cmse_nonsecure_call attribute and one without.
9105 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9106                                           QualType ToType) {
9107   if (const auto *ToFn =
9108           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9109     if (const auto *FromFn =
9110             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9111       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9112       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9113 
9114       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9115     }
9116   }
9117   return false;
9118 }
9119 
9120 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9121 // being closely modeled after the C99 spec:-). The odd characteristic of this
9122 // routine is it effectively iqnores the qualifiers on the top level pointee.
9123 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9124 // FIXME: add a couple examples in this comment.
9125 static Sema::AssignConvertType
9126 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9127   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9128   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9129 
9130   // get the "pointed to" type (ignoring qualifiers at the top level)
9131   const Type *lhptee, *rhptee;
9132   Qualifiers lhq, rhq;
9133   std::tie(lhptee, lhq) =
9134       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9135   std::tie(rhptee, rhq) =
9136       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9137 
9138   Sema::AssignConvertType ConvTy = Sema::Compatible;
9139 
9140   // C99 6.5.16.1p1: This following citation is common to constraints
9141   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9142   // qualifiers of the type *pointed to* by the right;
9143 
9144   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9145   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9146       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9147     // Ignore lifetime for further calculation.
9148     lhq.removeObjCLifetime();
9149     rhq.removeObjCLifetime();
9150   }
9151 
9152   if (!lhq.compatiblyIncludes(rhq)) {
9153     // Treat address-space mismatches as fatal.
9154     if (!lhq.isAddressSpaceSupersetOf(rhq))
9155       return Sema::IncompatiblePointerDiscardsQualifiers;
9156 
9157     // It's okay to add or remove GC or lifetime qualifiers when converting to
9158     // and from void*.
9159     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9160                         .compatiblyIncludes(
9161                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9162              && (lhptee->isVoidType() || rhptee->isVoidType()))
9163       ; // keep old
9164 
9165     // Treat lifetime mismatches as fatal.
9166     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9167       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9168 
9169     // For GCC/MS compatibility, other qualifier mismatches are treated
9170     // as still compatible in C.
9171     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9172   }
9173 
9174   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9175   // incomplete type and the other is a pointer to a qualified or unqualified
9176   // version of void...
9177   if (lhptee->isVoidType()) {
9178     if (rhptee->isIncompleteOrObjectType())
9179       return ConvTy;
9180 
9181     // As an extension, we allow cast to/from void* to function pointer.
9182     assert(rhptee->isFunctionType());
9183     return Sema::FunctionVoidPointer;
9184   }
9185 
9186   if (rhptee->isVoidType()) {
9187     if (lhptee->isIncompleteOrObjectType())
9188       return ConvTy;
9189 
9190     // As an extension, we allow cast to/from void* to function pointer.
9191     assert(lhptee->isFunctionType());
9192     return Sema::FunctionVoidPointer;
9193   }
9194 
9195   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9196   // unqualified versions of compatible types, ...
9197   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9198   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9199     // Check if the pointee types are compatible ignoring the sign.
9200     // We explicitly check for char so that we catch "char" vs
9201     // "unsigned char" on systems where "char" is unsigned.
9202     if (lhptee->isCharType())
9203       ltrans = S.Context.UnsignedCharTy;
9204     else if (lhptee->hasSignedIntegerRepresentation())
9205       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9206 
9207     if (rhptee->isCharType())
9208       rtrans = S.Context.UnsignedCharTy;
9209     else if (rhptee->hasSignedIntegerRepresentation())
9210       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9211 
9212     if (ltrans == rtrans) {
9213       // Types are compatible ignoring the sign. Qualifier incompatibility
9214       // takes priority over sign incompatibility because the sign
9215       // warning can be disabled.
9216       if (ConvTy != Sema::Compatible)
9217         return ConvTy;
9218 
9219       return Sema::IncompatiblePointerSign;
9220     }
9221 
9222     // If we are a multi-level pointer, it's possible that our issue is simply
9223     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9224     // the eventual target type is the same and the pointers have the same
9225     // level of indirection, this must be the issue.
9226     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9227       do {
9228         std::tie(lhptee, lhq) =
9229           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9230         std::tie(rhptee, rhq) =
9231           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9232 
9233         // Inconsistent address spaces at this point is invalid, even if the
9234         // address spaces would be compatible.
9235         // FIXME: This doesn't catch address space mismatches for pointers of
9236         // different nesting levels, like:
9237         //   __local int *** a;
9238         //   int ** b = a;
9239         // It's not clear how to actually determine when such pointers are
9240         // invalidly incompatible.
9241         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9242           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9243 
9244       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9245 
9246       if (lhptee == rhptee)
9247         return Sema::IncompatibleNestedPointerQualifiers;
9248     }
9249 
9250     // General pointer incompatibility takes priority over qualifiers.
9251     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9252       return Sema::IncompatibleFunctionPointer;
9253     return Sema::IncompatiblePointer;
9254   }
9255   if (!S.getLangOpts().CPlusPlus &&
9256       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9257     return Sema::IncompatibleFunctionPointer;
9258   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9259     return Sema::IncompatibleFunctionPointer;
9260   return ConvTy;
9261 }
9262 
9263 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9264 /// block pointer types are compatible or whether a block and normal pointer
9265 /// are compatible. It is more restrict than comparing two function pointer
9266 // types.
9267 static Sema::AssignConvertType
9268 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9269                                     QualType RHSType) {
9270   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9271   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9272 
9273   QualType lhptee, rhptee;
9274 
9275   // get the "pointed to" type (ignoring qualifiers at the top level)
9276   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9277   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9278 
9279   // In C++, the types have to match exactly.
9280   if (S.getLangOpts().CPlusPlus)
9281     return Sema::IncompatibleBlockPointer;
9282 
9283   Sema::AssignConvertType ConvTy = Sema::Compatible;
9284 
9285   // For blocks we enforce that qualifiers are identical.
9286   Qualifiers LQuals = lhptee.getLocalQualifiers();
9287   Qualifiers RQuals = rhptee.getLocalQualifiers();
9288   if (S.getLangOpts().OpenCL) {
9289     LQuals.removeAddressSpace();
9290     RQuals.removeAddressSpace();
9291   }
9292   if (LQuals != RQuals)
9293     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9294 
9295   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9296   // assignment.
9297   // The current behavior is similar to C++ lambdas. A block might be
9298   // assigned to a variable iff its return type and parameters are compatible
9299   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9300   // an assignment. Presumably it should behave in way that a function pointer
9301   // assignment does in C, so for each parameter and return type:
9302   //  * CVR and address space of LHS should be a superset of CVR and address
9303   //  space of RHS.
9304   //  * unqualified types should be compatible.
9305   if (S.getLangOpts().OpenCL) {
9306     if (!S.Context.typesAreBlockPointerCompatible(
9307             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9308             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9309       return Sema::IncompatibleBlockPointer;
9310   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9311     return Sema::IncompatibleBlockPointer;
9312 
9313   return ConvTy;
9314 }
9315 
9316 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9317 /// for assignment compatibility.
9318 static Sema::AssignConvertType
9319 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9320                                    QualType RHSType) {
9321   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9322   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9323 
9324   if (LHSType->isObjCBuiltinType()) {
9325     // Class is not compatible with ObjC object pointers.
9326     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9327         !RHSType->isObjCQualifiedClassType())
9328       return Sema::IncompatiblePointer;
9329     return Sema::Compatible;
9330   }
9331   if (RHSType->isObjCBuiltinType()) {
9332     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9333         !LHSType->isObjCQualifiedClassType())
9334       return Sema::IncompatiblePointer;
9335     return Sema::Compatible;
9336   }
9337   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9338   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9339 
9340   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9341       // make an exception for id<P>
9342       !LHSType->isObjCQualifiedIdType())
9343     return Sema::CompatiblePointerDiscardsQualifiers;
9344 
9345   if (S.Context.typesAreCompatible(LHSType, RHSType))
9346     return Sema::Compatible;
9347   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9348     return Sema::IncompatibleObjCQualifiedId;
9349   return Sema::IncompatiblePointer;
9350 }
9351 
9352 Sema::AssignConvertType
9353 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9354                                  QualType LHSType, QualType RHSType) {
9355   // Fake up an opaque expression.  We don't actually care about what
9356   // cast operations are required, so if CheckAssignmentConstraints
9357   // adds casts to this they'll be wasted, but fortunately that doesn't
9358   // usually happen on valid code.
9359   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9360   ExprResult RHSPtr = &RHSExpr;
9361   CastKind K;
9362 
9363   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9364 }
9365 
9366 /// This helper function returns true if QT is a vector type that has element
9367 /// type ElementType.
9368 static bool isVector(QualType QT, QualType ElementType) {
9369   if (const VectorType *VT = QT->getAs<VectorType>())
9370     return VT->getElementType().getCanonicalType() == ElementType;
9371   return false;
9372 }
9373 
9374 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9375 /// has code to accommodate several GCC extensions when type checking
9376 /// pointers. Here are some objectionable examples that GCC considers warnings:
9377 ///
9378 ///  int a, *pint;
9379 ///  short *pshort;
9380 ///  struct foo *pfoo;
9381 ///
9382 ///  pint = pshort; // warning: assignment from incompatible pointer type
9383 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9384 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9385 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9386 ///
9387 /// As a result, the code for dealing with pointers is more complex than the
9388 /// C99 spec dictates.
9389 ///
9390 /// Sets 'Kind' for any result kind except Incompatible.
9391 Sema::AssignConvertType
9392 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9393                                  CastKind &Kind, bool ConvertRHS) {
9394   QualType RHSType = RHS.get()->getType();
9395   QualType OrigLHSType = LHSType;
9396 
9397   // Get canonical types.  We're not formatting these types, just comparing
9398   // them.
9399   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9400   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9401 
9402   // Common case: no conversion required.
9403   if (LHSType == RHSType) {
9404     Kind = CK_NoOp;
9405     return Compatible;
9406   }
9407 
9408   // If the LHS has an __auto_type, there are no additional type constraints
9409   // to be worried about.
9410   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9411     if (AT->isGNUAutoType()) {
9412       Kind = CK_NoOp;
9413       return Compatible;
9414     }
9415   }
9416 
9417   // If we have an atomic type, try a non-atomic assignment, then just add an
9418   // atomic qualification step.
9419   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9420     Sema::AssignConvertType result =
9421       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9422     if (result != Compatible)
9423       return result;
9424     if (Kind != CK_NoOp && ConvertRHS)
9425       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9426     Kind = CK_NonAtomicToAtomic;
9427     return Compatible;
9428   }
9429 
9430   // If the left-hand side is a reference type, then we are in a
9431   // (rare!) case where we've allowed the use of references in C,
9432   // e.g., as a parameter type in a built-in function. In this case,
9433   // just make sure that the type referenced is compatible with the
9434   // right-hand side type. The caller is responsible for adjusting
9435   // LHSType so that the resulting expression does not have reference
9436   // type.
9437   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9438     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9439       Kind = CK_LValueBitCast;
9440       return Compatible;
9441     }
9442     return Incompatible;
9443   }
9444 
9445   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9446   // to the same ExtVector type.
9447   if (LHSType->isExtVectorType()) {
9448     if (RHSType->isExtVectorType())
9449       return Incompatible;
9450     if (RHSType->isArithmeticType()) {
9451       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9452       if (ConvertRHS)
9453         RHS = prepareVectorSplat(LHSType, RHS.get());
9454       Kind = CK_VectorSplat;
9455       return Compatible;
9456     }
9457   }
9458 
9459   // Conversions to or from vector type.
9460   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9461     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9462       // Allow assignments of an AltiVec vector type to an equivalent GCC
9463       // vector type and vice versa
9464       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9465         Kind = CK_BitCast;
9466         return Compatible;
9467       }
9468 
9469       // If we are allowing lax vector conversions, and LHS and RHS are both
9470       // vectors, the total size only needs to be the same. This is a bitcast;
9471       // no bits are changed but the result type is different.
9472       if (isLaxVectorConversion(RHSType, LHSType)) {
9473         Kind = CK_BitCast;
9474         return IncompatibleVectors;
9475       }
9476     }
9477 
9478     // When the RHS comes from another lax conversion (e.g. binops between
9479     // scalars and vectors) the result is canonicalized as a vector. When the
9480     // LHS is also a vector, the lax is allowed by the condition above. Handle
9481     // the case where LHS is a scalar.
9482     if (LHSType->isScalarType()) {
9483       const VectorType *VecType = RHSType->getAs<VectorType>();
9484       if (VecType && VecType->getNumElements() == 1 &&
9485           isLaxVectorConversion(RHSType, LHSType)) {
9486         ExprResult *VecExpr = &RHS;
9487         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9488         Kind = CK_BitCast;
9489         return Compatible;
9490       }
9491     }
9492 
9493     // Allow assignments between fixed-length and sizeless SVE vectors.
9494     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9495         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9496       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9497           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9498         Kind = CK_BitCast;
9499         return Compatible;
9500       }
9501 
9502     return Incompatible;
9503   }
9504 
9505   // Diagnose attempts to convert between __ibm128, __float128 and long double
9506   // where such conversions currently can't be handled.
9507   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9508     return Incompatible;
9509 
9510   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9511   // discards the imaginary part.
9512   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9513       !LHSType->getAs<ComplexType>())
9514     return Incompatible;
9515 
9516   // Arithmetic conversions.
9517   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9518       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9519     if (ConvertRHS)
9520       Kind = PrepareScalarCast(RHS, LHSType);
9521     return Compatible;
9522   }
9523 
9524   // Conversions to normal pointers.
9525   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9526     // U* -> T*
9527     if (isa<PointerType>(RHSType)) {
9528       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9529       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9530       if (AddrSpaceL != AddrSpaceR)
9531         Kind = CK_AddressSpaceConversion;
9532       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9533         Kind = CK_NoOp;
9534       else
9535         Kind = CK_BitCast;
9536       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9537     }
9538 
9539     // int -> T*
9540     if (RHSType->isIntegerType()) {
9541       Kind = CK_IntegralToPointer; // FIXME: null?
9542       return IntToPointer;
9543     }
9544 
9545     // C pointers are not compatible with ObjC object pointers,
9546     // with two exceptions:
9547     if (isa<ObjCObjectPointerType>(RHSType)) {
9548       //  - conversions to void*
9549       if (LHSPointer->getPointeeType()->isVoidType()) {
9550         Kind = CK_BitCast;
9551         return Compatible;
9552       }
9553 
9554       //  - conversions from 'Class' to the redefinition type
9555       if (RHSType->isObjCClassType() &&
9556           Context.hasSameType(LHSType,
9557                               Context.getObjCClassRedefinitionType())) {
9558         Kind = CK_BitCast;
9559         return Compatible;
9560       }
9561 
9562       Kind = CK_BitCast;
9563       return IncompatiblePointer;
9564     }
9565 
9566     // U^ -> void*
9567     if (RHSType->getAs<BlockPointerType>()) {
9568       if (LHSPointer->getPointeeType()->isVoidType()) {
9569         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9570         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9571                                 ->getPointeeType()
9572                                 .getAddressSpace();
9573         Kind =
9574             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9575         return Compatible;
9576       }
9577     }
9578 
9579     return Incompatible;
9580   }
9581 
9582   // Conversions to block pointers.
9583   if (isa<BlockPointerType>(LHSType)) {
9584     // U^ -> T^
9585     if (RHSType->isBlockPointerType()) {
9586       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9587                               ->getPointeeType()
9588                               .getAddressSpace();
9589       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9590                               ->getPointeeType()
9591                               .getAddressSpace();
9592       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9593       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9594     }
9595 
9596     // int or null -> T^
9597     if (RHSType->isIntegerType()) {
9598       Kind = CK_IntegralToPointer; // FIXME: null
9599       return IntToBlockPointer;
9600     }
9601 
9602     // id -> T^
9603     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9604       Kind = CK_AnyPointerToBlockPointerCast;
9605       return Compatible;
9606     }
9607 
9608     // void* -> T^
9609     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9610       if (RHSPT->getPointeeType()->isVoidType()) {
9611         Kind = CK_AnyPointerToBlockPointerCast;
9612         return Compatible;
9613       }
9614 
9615     return Incompatible;
9616   }
9617 
9618   // Conversions to Objective-C pointers.
9619   if (isa<ObjCObjectPointerType>(LHSType)) {
9620     // A* -> B*
9621     if (RHSType->isObjCObjectPointerType()) {
9622       Kind = CK_BitCast;
9623       Sema::AssignConvertType result =
9624         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9625       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9626           result == Compatible &&
9627           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9628         result = IncompatibleObjCWeakRef;
9629       return result;
9630     }
9631 
9632     // int or null -> A*
9633     if (RHSType->isIntegerType()) {
9634       Kind = CK_IntegralToPointer; // FIXME: null
9635       return IntToPointer;
9636     }
9637 
9638     // In general, C pointers are not compatible with ObjC object pointers,
9639     // with two exceptions:
9640     if (isa<PointerType>(RHSType)) {
9641       Kind = CK_CPointerToObjCPointerCast;
9642 
9643       //  - conversions from 'void*'
9644       if (RHSType->isVoidPointerType()) {
9645         return Compatible;
9646       }
9647 
9648       //  - conversions to 'Class' from its redefinition type
9649       if (LHSType->isObjCClassType() &&
9650           Context.hasSameType(RHSType,
9651                               Context.getObjCClassRedefinitionType())) {
9652         return Compatible;
9653       }
9654 
9655       return IncompatiblePointer;
9656     }
9657 
9658     // Only under strict condition T^ is compatible with an Objective-C pointer.
9659     if (RHSType->isBlockPointerType() &&
9660         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9661       if (ConvertRHS)
9662         maybeExtendBlockObject(RHS);
9663       Kind = CK_BlockPointerToObjCPointerCast;
9664       return Compatible;
9665     }
9666 
9667     return Incompatible;
9668   }
9669 
9670   // Conversions from pointers that are not covered by the above.
9671   if (isa<PointerType>(RHSType)) {
9672     // T* -> _Bool
9673     if (LHSType == Context.BoolTy) {
9674       Kind = CK_PointerToBoolean;
9675       return Compatible;
9676     }
9677 
9678     // T* -> int
9679     if (LHSType->isIntegerType()) {
9680       Kind = CK_PointerToIntegral;
9681       return PointerToInt;
9682     }
9683 
9684     return Incompatible;
9685   }
9686 
9687   // Conversions from Objective-C pointers that are not covered by the above.
9688   if (isa<ObjCObjectPointerType>(RHSType)) {
9689     // T* -> _Bool
9690     if (LHSType == Context.BoolTy) {
9691       Kind = CK_PointerToBoolean;
9692       return Compatible;
9693     }
9694 
9695     // T* -> int
9696     if (LHSType->isIntegerType()) {
9697       Kind = CK_PointerToIntegral;
9698       return PointerToInt;
9699     }
9700 
9701     return Incompatible;
9702   }
9703 
9704   // struct A -> struct B
9705   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9706     if (Context.typesAreCompatible(LHSType, RHSType)) {
9707       Kind = CK_NoOp;
9708       return Compatible;
9709     }
9710   }
9711 
9712   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9713     Kind = CK_IntToOCLSampler;
9714     return Compatible;
9715   }
9716 
9717   return Incompatible;
9718 }
9719 
9720 /// Constructs a transparent union from an expression that is
9721 /// used to initialize the transparent union.
9722 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9723                                       ExprResult &EResult, QualType UnionType,
9724                                       FieldDecl *Field) {
9725   // Build an initializer list that designates the appropriate member
9726   // of the transparent union.
9727   Expr *E = EResult.get();
9728   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9729                                                    E, SourceLocation());
9730   Initializer->setType(UnionType);
9731   Initializer->setInitializedFieldInUnion(Field);
9732 
9733   // Build a compound literal constructing a value of the transparent
9734   // union type from this initializer list.
9735   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9736   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9737                                         VK_PRValue, Initializer, false);
9738 }
9739 
9740 Sema::AssignConvertType
9741 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9742                                                ExprResult &RHS) {
9743   QualType RHSType = RHS.get()->getType();
9744 
9745   // If the ArgType is a Union type, we want to handle a potential
9746   // transparent_union GCC extension.
9747   const RecordType *UT = ArgType->getAsUnionType();
9748   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9749     return Incompatible;
9750 
9751   // The field to initialize within the transparent union.
9752   RecordDecl *UD = UT->getDecl();
9753   FieldDecl *InitField = nullptr;
9754   // It's compatible if the expression matches any of the fields.
9755   for (auto *it : UD->fields()) {
9756     if (it->getType()->isPointerType()) {
9757       // If the transparent union contains a pointer type, we allow:
9758       // 1) void pointer
9759       // 2) null pointer constant
9760       if (RHSType->isPointerType())
9761         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9762           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9763           InitField = it;
9764           break;
9765         }
9766 
9767       if (RHS.get()->isNullPointerConstant(Context,
9768                                            Expr::NPC_ValueDependentIsNull)) {
9769         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9770                                 CK_NullToPointer);
9771         InitField = it;
9772         break;
9773       }
9774     }
9775 
9776     CastKind Kind;
9777     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9778           == Compatible) {
9779       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9780       InitField = it;
9781       break;
9782     }
9783   }
9784 
9785   if (!InitField)
9786     return Incompatible;
9787 
9788   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9789   return Compatible;
9790 }
9791 
9792 Sema::AssignConvertType
9793 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9794                                        bool Diagnose,
9795                                        bool DiagnoseCFAudited,
9796                                        bool ConvertRHS) {
9797   // We need to be able to tell the caller whether we diagnosed a problem, if
9798   // they ask us to issue diagnostics.
9799   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9800 
9801   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9802   // we can't avoid *all* modifications at the moment, so we need some somewhere
9803   // to put the updated value.
9804   ExprResult LocalRHS = CallerRHS;
9805   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9806 
9807   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9808     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9809       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9810           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9811         Diag(RHS.get()->getExprLoc(),
9812              diag::warn_noderef_to_dereferenceable_pointer)
9813             << RHS.get()->getSourceRange();
9814       }
9815     }
9816   }
9817 
9818   if (getLangOpts().CPlusPlus) {
9819     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9820       // C++ 5.17p3: If the left operand is not of class type, the
9821       // expression is implicitly converted (C++ 4) to the
9822       // cv-unqualified type of the left operand.
9823       QualType RHSType = RHS.get()->getType();
9824       if (Diagnose) {
9825         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9826                                         AA_Assigning);
9827       } else {
9828         ImplicitConversionSequence ICS =
9829             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9830                                   /*SuppressUserConversions=*/false,
9831                                   AllowedExplicit::None,
9832                                   /*InOverloadResolution=*/false,
9833                                   /*CStyle=*/false,
9834                                   /*AllowObjCWritebackConversion=*/false);
9835         if (ICS.isFailure())
9836           return Incompatible;
9837         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9838                                         ICS, AA_Assigning);
9839       }
9840       if (RHS.isInvalid())
9841         return Incompatible;
9842       Sema::AssignConvertType result = Compatible;
9843       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9844           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9845         result = IncompatibleObjCWeakRef;
9846       return result;
9847     }
9848 
9849     // FIXME: Currently, we fall through and treat C++ classes like C
9850     // structures.
9851     // FIXME: We also fall through for atomics; not sure what should
9852     // happen there, though.
9853   } else if (RHS.get()->getType() == Context.OverloadTy) {
9854     // As a set of extensions to C, we support overloading on functions. These
9855     // functions need to be resolved here.
9856     DeclAccessPair DAP;
9857     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9858             RHS.get(), LHSType, /*Complain=*/false, DAP))
9859       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9860     else
9861       return Incompatible;
9862   }
9863 
9864   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9865   // a null pointer constant.
9866   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9867        LHSType->isBlockPointerType()) &&
9868       RHS.get()->isNullPointerConstant(Context,
9869                                        Expr::NPC_ValueDependentIsNull)) {
9870     if (Diagnose || ConvertRHS) {
9871       CastKind Kind;
9872       CXXCastPath Path;
9873       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9874                              /*IgnoreBaseAccess=*/false, Diagnose);
9875       if (ConvertRHS)
9876         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9877     }
9878     return Compatible;
9879   }
9880 
9881   // OpenCL queue_t type assignment.
9882   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9883                                  Context, Expr::NPC_ValueDependentIsNull)) {
9884     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9885     return Compatible;
9886   }
9887 
9888   // This check seems unnatural, however it is necessary to ensure the proper
9889   // conversion of functions/arrays. If the conversion were done for all
9890   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9891   // expressions that suppress this implicit conversion (&, sizeof).
9892   //
9893   // Suppress this for references: C++ 8.5.3p5.
9894   if (!LHSType->isReferenceType()) {
9895     // FIXME: We potentially allocate here even if ConvertRHS is false.
9896     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9897     if (RHS.isInvalid())
9898       return Incompatible;
9899   }
9900   CastKind Kind;
9901   Sema::AssignConvertType result =
9902     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9903 
9904   // C99 6.5.16.1p2: The value of the right operand is converted to the
9905   // type of the assignment expression.
9906   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9907   // so that we can use references in built-in functions even in C.
9908   // The getNonReferenceType() call makes sure that the resulting expression
9909   // does not have reference type.
9910   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9911     QualType Ty = LHSType.getNonLValueExprType(Context);
9912     Expr *E = RHS.get();
9913 
9914     // Check for various Objective-C errors. If we are not reporting
9915     // diagnostics and just checking for errors, e.g., during overload
9916     // resolution, return Incompatible to indicate the failure.
9917     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9918         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9919                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9920       if (!Diagnose)
9921         return Incompatible;
9922     }
9923     if (getLangOpts().ObjC &&
9924         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9925                                            E->getType(), E, Diagnose) ||
9926          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9927       if (!Diagnose)
9928         return Incompatible;
9929       // Replace the expression with a corrected version and continue so we
9930       // can find further errors.
9931       RHS = E;
9932       return Compatible;
9933     }
9934 
9935     if (ConvertRHS)
9936       RHS = ImpCastExprToType(E, Ty, Kind);
9937   }
9938 
9939   return result;
9940 }
9941 
9942 namespace {
9943 /// The original operand to an operator, prior to the application of the usual
9944 /// arithmetic conversions and converting the arguments of a builtin operator
9945 /// candidate.
9946 struct OriginalOperand {
9947   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9948     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9949       Op = MTE->getSubExpr();
9950     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9951       Op = BTE->getSubExpr();
9952     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9953       Orig = ICE->getSubExprAsWritten();
9954       Conversion = ICE->getConversionFunction();
9955     }
9956   }
9957 
9958   QualType getType() const { return Orig->getType(); }
9959 
9960   Expr *Orig;
9961   NamedDecl *Conversion;
9962 };
9963 }
9964 
9965 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9966                                ExprResult &RHS) {
9967   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9968 
9969   Diag(Loc, diag::err_typecheck_invalid_operands)
9970     << OrigLHS.getType() << OrigRHS.getType()
9971     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9972 
9973   // If a user-defined conversion was applied to either of the operands prior
9974   // to applying the built-in operator rules, tell the user about it.
9975   if (OrigLHS.Conversion) {
9976     Diag(OrigLHS.Conversion->getLocation(),
9977          diag::note_typecheck_invalid_operands_converted)
9978       << 0 << LHS.get()->getType();
9979   }
9980   if (OrigRHS.Conversion) {
9981     Diag(OrigRHS.Conversion->getLocation(),
9982          diag::note_typecheck_invalid_operands_converted)
9983       << 1 << RHS.get()->getType();
9984   }
9985 
9986   return QualType();
9987 }
9988 
9989 // Diagnose cases where a scalar was implicitly converted to a vector and
9990 // diagnose the underlying types. Otherwise, diagnose the error
9991 // as invalid vector logical operands for non-C++ cases.
9992 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9993                                             ExprResult &RHS) {
9994   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9995   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9996 
9997   bool LHSNatVec = LHSType->isVectorType();
9998   bool RHSNatVec = RHSType->isVectorType();
9999 
10000   if (!(LHSNatVec && RHSNatVec)) {
10001     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10002     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10003     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10004         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10005         << Vector->getSourceRange();
10006     return QualType();
10007   }
10008 
10009   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10010       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10011       << RHS.get()->getSourceRange();
10012 
10013   return QualType();
10014 }
10015 
10016 /// Try to convert a value of non-vector type to a vector type by converting
10017 /// the type to the element type of the vector and then performing a splat.
10018 /// If the language is OpenCL, we only use conversions that promote scalar
10019 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10020 /// for float->int.
10021 ///
10022 /// OpenCL V2.0 6.2.6.p2:
10023 /// An error shall occur if any scalar operand type has greater rank
10024 /// than the type of the vector element.
10025 ///
10026 /// \param scalar - if non-null, actually perform the conversions
10027 /// \return true if the operation fails (but without diagnosing the failure)
10028 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10029                                      QualType scalarTy,
10030                                      QualType vectorEltTy,
10031                                      QualType vectorTy,
10032                                      unsigned &DiagID) {
10033   // The conversion to apply to the scalar before splatting it,
10034   // if necessary.
10035   CastKind scalarCast = CK_NoOp;
10036 
10037   if (vectorEltTy->isIntegralType(S.Context)) {
10038     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10039         (scalarTy->isIntegerType() &&
10040          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10041       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10042       return true;
10043     }
10044     if (!scalarTy->isIntegralType(S.Context))
10045       return true;
10046     scalarCast = CK_IntegralCast;
10047   } else if (vectorEltTy->isRealFloatingType()) {
10048     if (scalarTy->isRealFloatingType()) {
10049       if (S.getLangOpts().OpenCL &&
10050           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10051         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10052         return true;
10053       }
10054       scalarCast = CK_FloatingCast;
10055     }
10056     else if (scalarTy->isIntegralType(S.Context))
10057       scalarCast = CK_IntegralToFloating;
10058     else
10059       return true;
10060   } else {
10061     return true;
10062   }
10063 
10064   // Adjust scalar if desired.
10065   if (scalar) {
10066     if (scalarCast != CK_NoOp)
10067       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10068     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10069   }
10070   return false;
10071 }
10072 
10073 /// Convert vector E to a vector with the same number of elements but different
10074 /// element type.
10075 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10076   const auto *VecTy = E->getType()->getAs<VectorType>();
10077   assert(VecTy && "Expression E must be a vector");
10078   QualType NewVecTy =
10079       VecTy->isExtVectorType()
10080           ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10081           : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10082                                     VecTy->getVectorKind());
10083 
10084   // Look through the implicit cast. Return the subexpression if its type is
10085   // NewVecTy.
10086   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10087     if (ICE->getSubExpr()->getType() == NewVecTy)
10088       return ICE->getSubExpr();
10089 
10090   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10091   return S.ImpCastExprToType(E, NewVecTy, Cast);
10092 }
10093 
10094 /// Test if a (constant) integer Int can be casted to another integer type
10095 /// IntTy without losing precision.
10096 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10097                                       QualType OtherIntTy) {
10098   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10099 
10100   // Reject cases where the value of the Int is unknown as that would
10101   // possibly cause truncation, but accept cases where the scalar can be
10102   // demoted without loss of precision.
10103   Expr::EvalResult EVResult;
10104   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10105   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10106   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10107   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10108 
10109   if (CstInt) {
10110     // If the scalar is constant and is of a higher order and has more active
10111     // bits that the vector element type, reject it.
10112     llvm::APSInt Result = EVResult.Val.getInt();
10113     unsigned NumBits = IntSigned
10114                            ? (Result.isNegative() ? Result.getMinSignedBits()
10115                                                   : Result.getActiveBits())
10116                            : Result.getActiveBits();
10117     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10118       return true;
10119 
10120     // If the signedness of the scalar type and the vector element type
10121     // differs and the number of bits is greater than that of the vector
10122     // element reject it.
10123     return (IntSigned != OtherIntSigned &&
10124             NumBits > S.Context.getIntWidth(OtherIntTy));
10125   }
10126 
10127   // Reject cases where the value of the scalar is not constant and it's
10128   // order is greater than that of the vector element type.
10129   return (Order < 0);
10130 }
10131 
10132 /// Test if a (constant) integer Int can be casted to floating point type
10133 /// FloatTy without losing precision.
10134 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10135                                      QualType FloatTy) {
10136   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10137 
10138   // Determine if the integer constant can be expressed as a floating point
10139   // number of the appropriate type.
10140   Expr::EvalResult EVResult;
10141   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10142 
10143   uint64_t Bits = 0;
10144   if (CstInt) {
10145     // Reject constants that would be truncated if they were converted to
10146     // the floating point type. Test by simple to/from conversion.
10147     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10148     //        could be avoided if there was a convertFromAPInt method
10149     //        which could signal back if implicit truncation occurred.
10150     llvm::APSInt Result = EVResult.Val.getInt();
10151     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10152     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10153                            llvm::APFloat::rmTowardZero);
10154     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10155                              !IntTy->hasSignedIntegerRepresentation());
10156     bool Ignored = false;
10157     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10158                            &Ignored);
10159     if (Result != ConvertBack)
10160       return true;
10161   } else {
10162     // Reject types that cannot be fully encoded into the mantissa of
10163     // the float.
10164     Bits = S.Context.getTypeSize(IntTy);
10165     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10166         S.Context.getFloatTypeSemantics(FloatTy));
10167     if (Bits > FloatPrec)
10168       return true;
10169   }
10170 
10171   return false;
10172 }
10173 
10174 /// Attempt to convert and splat Scalar into a vector whose types matches
10175 /// Vector following GCC conversion rules. The rule is that implicit
10176 /// conversion can occur when Scalar can be casted to match Vector's element
10177 /// type without causing truncation of Scalar.
10178 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10179                                         ExprResult *Vector) {
10180   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10181   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10182   const auto *VT = VectorTy->castAs<VectorType>();
10183 
10184   assert(!isa<ExtVectorType>(VT) &&
10185          "ExtVectorTypes should not be handled here!");
10186 
10187   QualType VectorEltTy = VT->getElementType();
10188 
10189   // Reject cases where the vector element type or the scalar element type are
10190   // not integral or floating point types.
10191   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10192     return true;
10193 
10194   // The conversion to apply to the scalar before splatting it,
10195   // if necessary.
10196   CastKind ScalarCast = CK_NoOp;
10197 
10198   // Accept cases where the vector elements are integers and the scalar is
10199   // an integer.
10200   // FIXME: Notionally if the scalar was a floating point value with a precise
10201   //        integral representation, we could cast it to an appropriate integer
10202   //        type and then perform the rest of the checks here. GCC will perform
10203   //        this conversion in some cases as determined by the input language.
10204   //        We should accept it on a language independent basis.
10205   if (VectorEltTy->isIntegralType(S.Context) &&
10206       ScalarTy->isIntegralType(S.Context) &&
10207       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10208 
10209     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10210       return true;
10211 
10212     ScalarCast = CK_IntegralCast;
10213   } else if (VectorEltTy->isIntegralType(S.Context) &&
10214              ScalarTy->isRealFloatingType()) {
10215     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10216       ScalarCast = CK_FloatingToIntegral;
10217     else
10218       return true;
10219   } else if (VectorEltTy->isRealFloatingType()) {
10220     if (ScalarTy->isRealFloatingType()) {
10221 
10222       // Reject cases where the scalar type is not a constant and has a higher
10223       // Order than the vector element type.
10224       llvm::APFloat Result(0.0);
10225 
10226       // Determine whether this is a constant scalar. In the event that the
10227       // value is dependent (and thus cannot be evaluated by the constant
10228       // evaluator), skip the evaluation. This will then diagnose once the
10229       // expression is instantiated.
10230       bool CstScalar = Scalar->get()->isValueDependent() ||
10231                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10232       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10233       if (!CstScalar && Order < 0)
10234         return true;
10235 
10236       // If the scalar cannot be safely casted to the vector element type,
10237       // reject it.
10238       if (CstScalar) {
10239         bool Truncated = false;
10240         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10241                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10242         if (Truncated)
10243           return true;
10244       }
10245 
10246       ScalarCast = CK_FloatingCast;
10247     } else if (ScalarTy->isIntegralType(S.Context)) {
10248       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10249         return true;
10250 
10251       ScalarCast = CK_IntegralToFloating;
10252     } else
10253       return true;
10254   } else if (ScalarTy->isEnumeralType())
10255     return true;
10256 
10257   // Adjust scalar if desired.
10258   if (Scalar) {
10259     if (ScalarCast != CK_NoOp)
10260       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10261     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10262   }
10263   return false;
10264 }
10265 
10266 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10267                                    SourceLocation Loc, bool IsCompAssign,
10268                                    bool AllowBothBool,
10269                                    bool AllowBoolConversions,
10270                                    bool AllowBoolOperation,
10271                                    bool ReportInvalid) {
10272   if (!IsCompAssign) {
10273     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10274     if (LHS.isInvalid())
10275       return QualType();
10276   }
10277   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10278   if (RHS.isInvalid())
10279     return QualType();
10280 
10281   // For conversion purposes, we ignore any qualifiers.
10282   // For example, "const float" and "float" are equivalent.
10283   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10284   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10285 
10286   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10287   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10288   assert(LHSVecType || RHSVecType);
10289 
10290   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10291       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10292     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10293 
10294   // AltiVec-style "vector bool op vector bool" combinations are allowed
10295   // for some operators but not others.
10296   if (!AllowBothBool &&
10297       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10298       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10299     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10300 
10301   // This operation may not be performed on boolean vectors.
10302   if (!AllowBoolOperation &&
10303       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10304     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10305 
10306   // If the vector types are identical, return.
10307   if (Context.hasSameType(LHSType, RHSType))
10308     return LHSType;
10309 
10310   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10311   if (LHSVecType && RHSVecType &&
10312       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10313     if (isa<ExtVectorType>(LHSVecType)) {
10314       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10315       return LHSType;
10316     }
10317 
10318     if (!IsCompAssign)
10319       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10320     return RHSType;
10321   }
10322 
10323   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10324   // can be mixed, with the result being the non-bool type.  The non-bool
10325   // operand must have integer element type.
10326   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10327       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10328       (Context.getTypeSize(LHSVecType->getElementType()) ==
10329        Context.getTypeSize(RHSVecType->getElementType()))) {
10330     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10331         LHSVecType->getElementType()->isIntegerType() &&
10332         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10333       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10334       return LHSType;
10335     }
10336     if (!IsCompAssign &&
10337         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10338         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10339         RHSVecType->getElementType()->isIntegerType()) {
10340       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10341       return RHSType;
10342     }
10343   }
10344 
10345   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10346   // since the ambiguity can affect the ABI.
10347   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10348     const VectorType *VecType = SecondType->getAs<VectorType>();
10349     return FirstType->isSizelessBuiltinType() && VecType &&
10350            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10351             VecType->getVectorKind() ==
10352                 VectorType::SveFixedLengthPredicateVector);
10353   };
10354 
10355   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10356     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10357     return QualType();
10358   }
10359 
10360   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10361   // since the ambiguity can affect the ABI.
10362   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10363     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10364     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10365 
10366     if (FirstVecType && SecondVecType)
10367       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10368              (SecondVecType->getVectorKind() ==
10369                   VectorType::SveFixedLengthDataVector ||
10370               SecondVecType->getVectorKind() ==
10371                   VectorType::SveFixedLengthPredicateVector);
10372 
10373     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10374            SecondVecType->getVectorKind() == VectorType::GenericVector;
10375   };
10376 
10377   if (IsSveGnuConversion(LHSType, RHSType) ||
10378       IsSveGnuConversion(RHSType, LHSType)) {
10379     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10380     return QualType();
10381   }
10382 
10383   // If there's a vector type and a scalar, try to convert the scalar to
10384   // the vector element type and splat.
10385   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10386   if (!RHSVecType) {
10387     if (isa<ExtVectorType>(LHSVecType)) {
10388       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10389                                     LHSVecType->getElementType(), LHSType,
10390                                     DiagID))
10391         return LHSType;
10392     } else {
10393       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10394         return LHSType;
10395     }
10396   }
10397   if (!LHSVecType) {
10398     if (isa<ExtVectorType>(RHSVecType)) {
10399       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10400                                     LHSType, RHSVecType->getElementType(),
10401                                     RHSType, DiagID))
10402         return RHSType;
10403     } else {
10404       if (LHS.get()->isLValue() ||
10405           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10406         return RHSType;
10407     }
10408   }
10409 
10410   // FIXME: The code below also handles conversion between vectors and
10411   // non-scalars, we should break this down into fine grained specific checks
10412   // and emit proper diagnostics.
10413   QualType VecType = LHSVecType ? LHSType : RHSType;
10414   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10415   QualType OtherType = LHSVecType ? RHSType : LHSType;
10416   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10417   if (isLaxVectorConversion(OtherType, VecType)) {
10418     // If we're allowing lax vector conversions, only the total (data) size
10419     // needs to be the same. For non compound assignment, if one of the types is
10420     // scalar, the result is always the vector type.
10421     if (!IsCompAssign) {
10422       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10423       return VecType;
10424     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10425     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10426     // type. Note that this is already done by non-compound assignments in
10427     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10428     // <1 x T> -> T. The result is also a vector type.
10429     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10430                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10431       ExprResult *RHSExpr = &RHS;
10432       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10433       return VecType;
10434     }
10435   }
10436 
10437   // Okay, the expression is invalid.
10438 
10439   // If there's a non-vector, non-real operand, diagnose that.
10440   if ((!RHSVecType && !RHSType->isRealType()) ||
10441       (!LHSVecType && !LHSType->isRealType())) {
10442     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10443       << LHSType << RHSType
10444       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10445     return QualType();
10446   }
10447 
10448   // OpenCL V1.1 6.2.6.p1:
10449   // If the operands are of more than one vector type, then an error shall
10450   // occur. Implicit conversions between vector types are not permitted, per
10451   // section 6.2.1.
10452   if (getLangOpts().OpenCL &&
10453       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10454       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10455     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10456                                                            << RHSType;
10457     return QualType();
10458   }
10459 
10460 
10461   // If there is a vector type that is not a ExtVector and a scalar, we reach
10462   // this point if scalar could not be converted to the vector's element type
10463   // without truncation.
10464   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10465       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10466     QualType Scalar = LHSVecType ? RHSType : LHSType;
10467     QualType Vector = LHSVecType ? LHSType : RHSType;
10468     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10469     Diag(Loc,
10470          diag::err_typecheck_vector_not_convertable_implict_truncation)
10471         << ScalarOrVector << Scalar << Vector;
10472 
10473     return QualType();
10474   }
10475 
10476   // Otherwise, use the generic diagnostic.
10477   Diag(Loc, DiagID)
10478     << LHSType << RHSType
10479     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10480   return QualType();
10481 }
10482 
10483 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10484                                            SourceLocation Loc,
10485                                            bool IsCompAssign,
10486                                            ArithConvKind OperationKind) {
10487   if (!IsCompAssign) {
10488     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10489     if (LHS.isInvalid())
10490       return QualType();
10491   }
10492   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10493   if (RHS.isInvalid())
10494     return QualType();
10495 
10496   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10497   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10498 
10499   unsigned DiagID = diag::err_typecheck_invalid_operands;
10500   if ((OperationKind == ACK_Arithmetic) &&
10501       (LHSType->castAs<BuiltinType>()->isSVEBool() ||
10502        RHSType->castAs<BuiltinType>()->isSVEBool())) {
10503     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10504                       << RHS.get()->getSourceRange();
10505     return QualType();
10506   }
10507 
10508   if (Context.hasSameType(LHSType, RHSType))
10509     return LHSType;
10510 
10511   auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10512                                          QualType DestType) {
10513     const QualType DestBaseType = DestType->getSveEltType(Context);
10514     if (DestBaseType->getUnqualifiedDesugaredType() ==
10515         SrcType->getUnqualifiedDesugaredType()) {
10516       unsigned DiagID = diag::err_typecheck_invalid_operands;
10517       if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10518                                     DiagID))
10519         return DestType;
10520     }
10521     return QualType();
10522   };
10523 
10524   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10525     auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10526     if (DestType == QualType())
10527       return InvalidOperands(Loc, LHS, RHS);
10528     return DestType;
10529   }
10530 
10531   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10532     auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10533                                              LHSType, RHSType);
10534     if (DestType == QualType())
10535       return InvalidOperands(Loc, LHS, RHS);
10536     return DestType;
10537   }
10538 
10539   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10540                     << RHS.get()->getSourceRange();
10541   return QualType();
10542 }
10543 
10544 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10545 // expression.  These are mainly cases where the null pointer is used as an
10546 // integer instead of a pointer.
10547 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10548                                 SourceLocation Loc, bool IsCompare) {
10549   // The canonical way to check for a GNU null is with isNullPointerConstant,
10550   // but we use a bit of a hack here for speed; this is a relatively
10551   // hot path, and isNullPointerConstant is slow.
10552   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10553   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10554 
10555   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10556 
10557   // Avoid analyzing cases where the result will either be invalid (and
10558   // diagnosed as such) or entirely valid and not something to warn about.
10559   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10560       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10561     return;
10562 
10563   // Comparison operations would not make sense with a null pointer no matter
10564   // what the other expression is.
10565   if (!IsCompare) {
10566     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10567         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10568         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10569     return;
10570   }
10571 
10572   // The rest of the operations only make sense with a null pointer
10573   // if the other expression is a pointer.
10574   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10575       NonNullType->canDecayToPointerType())
10576     return;
10577 
10578   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10579       << LHSNull /* LHS is NULL */ << NonNullType
10580       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10581 }
10582 
10583 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10584                                           SourceLocation Loc) {
10585   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10586   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10587   if (!LUE || !RUE)
10588     return;
10589   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10590       RUE->getKind() != UETT_SizeOf)
10591     return;
10592 
10593   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10594   QualType LHSTy = LHSArg->getType();
10595   QualType RHSTy;
10596 
10597   if (RUE->isArgumentType())
10598     RHSTy = RUE->getArgumentType().getNonReferenceType();
10599   else
10600     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10601 
10602   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10603     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10604       return;
10605 
10606     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10607     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10608       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10609         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10610             << LHSArgDecl;
10611     }
10612   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10613     QualType ArrayElemTy = ArrayTy->getElementType();
10614     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10615         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10616         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10617         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10618       return;
10619     S.Diag(Loc, diag::warn_division_sizeof_array)
10620         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10621     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10622       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10623         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10624             << LHSArgDecl;
10625     }
10626 
10627     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10628   }
10629 }
10630 
10631 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10632                                                ExprResult &RHS,
10633                                                SourceLocation Loc, bool IsDiv) {
10634   // Check for division/remainder by zero.
10635   Expr::EvalResult RHSValue;
10636   if (!RHS.get()->isValueDependent() &&
10637       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10638       RHSValue.Val.getInt() == 0)
10639     S.DiagRuntimeBehavior(Loc, RHS.get(),
10640                           S.PDiag(diag::warn_remainder_division_by_zero)
10641                             << IsDiv << RHS.get()->getSourceRange());
10642 }
10643 
10644 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10645                                            SourceLocation Loc,
10646                                            bool IsCompAssign, bool IsDiv) {
10647   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10648 
10649   QualType LHSTy = LHS.get()->getType();
10650   QualType RHSTy = RHS.get()->getType();
10651   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10652     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10653                                /*AllowBothBool*/ getLangOpts().AltiVec,
10654                                /*AllowBoolConversions*/ false,
10655                                /*AllowBooleanOperation*/ false,
10656                                /*ReportInvalid*/ true);
10657   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10658     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10659                                        ACK_Arithmetic);
10660   if (!IsDiv &&
10661       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10662     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10663   // For division, only matrix-by-scalar is supported. Other combinations with
10664   // matrix types are invalid.
10665   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10666     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10667 
10668   QualType compType = UsualArithmeticConversions(
10669       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10670   if (LHS.isInvalid() || RHS.isInvalid())
10671     return QualType();
10672 
10673 
10674   if (compType.isNull() || !compType->isArithmeticType())
10675     return InvalidOperands(Loc, LHS, RHS);
10676   if (IsDiv) {
10677     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10678     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10679   }
10680   return compType;
10681 }
10682 
10683 QualType Sema::CheckRemainderOperands(
10684   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10685   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10686 
10687   if (LHS.get()->getType()->isVectorType() ||
10688       RHS.get()->getType()->isVectorType()) {
10689     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10690         RHS.get()->getType()->hasIntegerRepresentation())
10691       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10692                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10693                                  /*AllowBoolConversions*/ false,
10694                                  /*AllowBooleanOperation*/ false,
10695                                  /*ReportInvalid*/ true);
10696     return InvalidOperands(Loc, LHS, RHS);
10697   }
10698 
10699   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10700       RHS.get()->getType()->isVLSTBuiltinType()) {
10701     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10702         RHS.get()->getType()->hasIntegerRepresentation())
10703       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10704                                          ACK_Arithmetic);
10705 
10706     return InvalidOperands(Loc, LHS, RHS);
10707   }
10708 
10709   QualType compType = UsualArithmeticConversions(
10710       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10711   if (LHS.isInvalid() || RHS.isInvalid())
10712     return QualType();
10713 
10714   if (compType.isNull() || !compType->isIntegerType())
10715     return InvalidOperands(Loc, LHS, RHS);
10716   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10717   return compType;
10718 }
10719 
10720 /// Diagnose invalid arithmetic on two void pointers.
10721 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10722                                                 Expr *LHSExpr, Expr *RHSExpr) {
10723   S.Diag(Loc, S.getLangOpts().CPlusPlus
10724                 ? diag::err_typecheck_pointer_arith_void_type
10725                 : diag::ext_gnu_void_ptr)
10726     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10727                             << RHSExpr->getSourceRange();
10728 }
10729 
10730 /// Diagnose invalid arithmetic on a void pointer.
10731 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10732                                             Expr *Pointer) {
10733   S.Diag(Loc, S.getLangOpts().CPlusPlus
10734                 ? diag::err_typecheck_pointer_arith_void_type
10735                 : diag::ext_gnu_void_ptr)
10736     << 0 /* one pointer */ << Pointer->getSourceRange();
10737 }
10738 
10739 /// Diagnose invalid arithmetic on a null pointer.
10740 ///
10741 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10742 /// idiom, which we recognize as a GNU extension.
10743 ///
10744 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10745                                             Expr *Pointer, bool IsGNUIdiom) {
10746   if (IsGNUIdiom)
10747     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10748       << Pointer->getSourceRange();
10749   else
10750     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10751       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10752 }
10753 
10754 /// Diagnose invalid subraction on a null pointer.
10755 ///
10756 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10757                                              Expr *Pointer, bool BothNull) {
10758   // Null - null is valid in C++ [expr.add]p7
10759   if (BothNull && S.getLangOpts().CPlusPlus)
10760     return;
10761 
10762   // Is this s a macro from a system header?
10763   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10764     return;
10765 
10766   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10767       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10768 }
10769 
10770 /// Diagnose invalid arithmetic on two function pointers.
10771 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10772                                                     Expr *LHS, Expr *RHS) {
10773   assert(LHS->getType()->isAnyPointerType());
10774   assert(RHS->getType()->isAnyPointerType());
10775   S.Diag(Loc, S.getLangOpts().CPlusPlus
10776                 ? diag::err_typecheck_pointer_arith_function_type
10777                 : diag::ext_gnu_ptr_func_arith)
10778     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10779     // We only show the second type if it differs from the first.
10780     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10781                                                    RHS->getType())
10782     << RHS->getType()->getPointeeType()
10783     << LHS->getSourceRange() << RHS->getSourceRange();
10784 }
10785 
10786 /// Diagnose invalid arithmetic on a function pointer.
10787 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10788                                                 Expr *Pointer) {
10789   assert(Pointer->getType()->isAnyPointerType());
10790   S.Diag(Loc, S.getLangOpts().CPlusPlus
10791                 ? diag::err_typecheck_pointer_arith_function_type
10792                 : diag::ext_gnu_ptr_func_arith)
10793     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10794     << 0 /* one pointer, so only one type */
10795     << Pointer->getSourceRange();
10796 }
10797 
10798 /// Emit error if Operand is incomplete pointer type
10799 ///
10800 /// \returns True if pointer has incomplete type
10801 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10802                                                  Expr *Operand) {
10803   QualType ResType = Operand->getType();
10804   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10805     ResType = ResAtomicType->getValueType();
10806 
10807   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10808   QualType PointeeTy = ResType->getPointeeType();
10809   return S.RequireCompleteSizedType(
10810       Loc, PointeeTy,
10811       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10812       Operand->getSourceRange());
10813 }
10814 
10815 /// Check the validity of an arithmetic pointer operand.
10816 ///
10817 /// If the operand has pointer type, this code will check for pointer types
10818 /// which are invalid in arithmetic operations. These will be diagnosed
10819 /// appropriately, including whether or not the use is supported as an
10820 /// extension.
10821 ///
10822 /// \returns True when the operand is valid to use (even if as an extension).
10823 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10824                                             Expr *Operand) {
10825   QualType ResType = Operand->getType();
10826   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10827     ResType = ResAtomicType->getValueType();
10828 
10829   if (!ResType->isAnyPointerType()) return true;
10830 
10831   QualType PointeeTy = ResType->getPointeeType();
10832   if (PointeeTy->isVoidType()) {
10833     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10834     return !S.getLangOpts().CPlusPlus;
10835   }
10836   if (PointeeTy->isFunctionType()) {
10837     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10838     return !S.getLangOpts().CPlusPlus;
10839   }
10840 
10841   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10842 
10843   return true;
10844 }
10845 
10846 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10847 /// operands.
10848 ///
10849 /// This routine will diagnose any invalid arithmetic on pointer operands much
10850 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10851 /// for emitting a single diagnostic even for operations where both LHS and RHS
10852 /// are (potentially problematic) pointers.
10853 ///
10854 /// \returns True when the operand is valid to use (even if as an extension).
10855 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10856                                                 Expr *LHSExpr, Expr *RHSExpr) {
10857   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10858   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10859   if (!isLHSPointer && !isRHSPointer) return true;
10860 
10861   QualType LHSPointeeTy, RHSPointeeTy;
10862   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10863   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10864 
10865   // if both are pointers check if operation is valid wrt address spaces
10866   if (isLHSPointer && isRHSPointer) {
10867     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10868       S.Diag(Loc,
10869              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10870           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10871           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10872       return false;
10873     }
10874   }
10875 
10876   // Check for arithmetic on pointers to incomplete types.
10877   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10878   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10879   if (isLHSVoidPtr || isRHSVoidPtr) {
10880     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10881     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10882     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10883 
10884     return !S.getLangOpts().CPlusPlus;
10885   }
10886 
10887   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10888   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10889   if (isLHSFuncPtr || isRHSFuncPtr) {
10890     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10891     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10892                                                                 RHSExpr);
10893     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10894 
10895     return !S.getLangOpts().CPlusPlus;
10896   }
10897 
10898   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10899     return false;
10900   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10901     return false;
10902 
10903   return true;
10904 }
10905 
10906 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10907 /// literal.
10908 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10909                                   Expr *LHSExpr, Expr *RHSExpr) {
10910   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10911   Expr* IndexExpr = RHSExpr;
10912   if (!StrExpr) {
10913     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10914     IndexExpr = LHSExpr;
10915   }
10916 
10917   bool IsStringPlusInt = StrExpr &&
10918       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10919   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10920     return;
10921 
10922   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10923   Self.Diag(OpLoc, diag::warn_string_plus_int)
10924       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10925 
10926   // Only print a fixit for "str" + int, not for int + "str".
10927   if (IndexExpr == RHSExpr) {
10928     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10929     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10930         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10931         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10932         << FixItHint::CreateInsertion(EndLoc, "]");
10933   } else
10934     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10935 }
10936 
10937 /// Emit a warning when adding a char literal to a string.
10938 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10939                                    Expr *LHSExpr, Expr *RHSExpr) {
10940   const Expr *StringRefExpr = LHSExpr;
10941   const CharacterLiteral *CharExpr =
10942       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10943 
10944   if (!CharExpr) {
10945     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10946     StringRefExpr = RHSExpr;
10947   }
10948 
10949   if (!CharExpr || !StringRefExpr)
10950     return;
10951 
10952   const QualType StringType = StringRefExpr->getType();
10953 
10954   // Return if not a PointerType.
10955   if (!StringType->isAnyPointerType())
10956     return;
10957 
10958   // Return if not a CharacterType.
10959   if (!StringType->getPointeeType()->isAnyCharacterType())
10960     return;
10961 
10962   ASTContext &Ctx = Self.getASTContext();
10963   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10964 
10965   const QualType CharType = CharExpr->getType();
10966   if (!CharType->isAnyCharacterType() &&
10967       CharType->isIntegerType() &&
10968       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10969     Self.Diag(OpLoc, diag::warn_string_plus_char)
10970         << DiagRange << Ctx.CharTy;
10971   } else {
10972     Self.Diag(OpLoc, diag::warn_string_plus_char)
10973         << DiagRange << CharExpr->getType();
10974   }
10975 
10976   // Only print a fixit for str + char, not for char + str.
10977   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10978     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10979     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10980         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10981         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10982         << FixItHint::CreateInsertion(EndLoc, "]");
10983   } else {
10984     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10985   }
10986 }
10987 
10988 /// Emit error when two pointers are incompatible.
10989 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10990                                            Expr *LHSExpr, Expr *RHSExpr) {
10991   assert(LHSExpr->getType()->isAnyPointerType());
10992   assert(RHSExpr->getType()->isAnyPointerType());
10993   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10994     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10995     << RHSExpr->getSourceRange();
10996 }
10997 
10998 // C99 6.5.6
10999 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11000                                      SourceLocation Loc, BinaryOperatorKind Opc,
11001                                      QualType* CompLHSTy) {
11002   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11003 
11004   if (LHS.get()->getType()->isVectorType() ||
11005       RHS.get()->getType()->isVectorType()) {
11006     QualType compType =
11007         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11008                             /*AllowBothBool*/ getLangOpts().AltiVec,
11009                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11010                             /*AllowBooleanOperation*/ false,
11011                             /*ReportInvalid*/ true);
11012     if (CompLHSTy) *CompLHSTy = compType;
11013     return compType;
11014   }
11015 
11016   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11017       RHS.get()->getType()->isVLSTBuiltinType()) {
11018     QualType compType =
11019         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11020     if (CompLHSTy)
11021       *CompLHSTy = compType;
11022     return compType;
11023   }
11024 
11025   if (LHS.get()->getType()->isConstantMatrixType() ||
11026       RHS.get()->getType()->isConstantMatrixType()) {
11027     QualType compType =
11028         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11029     if (CompLHSTy)
11030       *CompLHSTy = compType;
11031     return compType;
11032   }
11033 
11034   QualType compType = UsualArithmeticConversions(
11035       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11036   if (LHS.isInvalid() || RHS.isInvalid())
11037     return QualType();
11038 
11039   // Diagnose "string literal" '+' int and string '+' "char literal".
11040   if (Opc == BO_Add) {
11041     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11042     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11043   }
11044 
11045   // handle the common case first (both operands are arithmetic).
11046   if (!compType.isNull() && compType->isArithmeticType()) {
11047     if (CompLHSTy) *CompLHSTy = compType;
11048     return compType;
11049   }
11050 
11051   // Type-checking.  Ultimately the pointer's going to be in PExp;
11052   // note that we bias towards the LHS being the pointer.
11053   Expr *PExp = LHS.get(), *IExp = RHS.get();
11054 
11055   bool isObjCPointer;
11056   if (PExp->getType()->isPointerType()) {
11057     isObjCPointer = false;
11058   } else if (PExp->getType()->isObjCObjectPointerType()) {
11059     isObjCPointer = true;
11060   } else {
11061     std::swap(PExp, IExp);
11062     if (PExp->getType()->isPointerType()) {
11063       isObjCPointer = false;
11064     } else if (PExp->getType()->isObjCObjectPointerType()) {
11065       isObjCPointer = true;
11066     } else {
11067       return InvalidOperands(Loc, LHS, RHS);
11068     }
11069   }
11070   assert(PExp->getType()->isAnyPointerType());
11071 
11072   if (!IExp->getType()->isIntegerType())
11073     return InvalidOperands(Loc, LHS, RHS);
11074 
11075   // Adding to a null pointer results in undefined behavior.
11076   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11077           Context, Expr::NPC_ValueDependentIsNotNull)) {
11078     // In C++ adding zero to a null pointer is defined.
11079     Expr::EvalResult KnownVal;
11080     if (!getLangOpts().CPlusPlus ||
11081         (!IExp->isValueDependent() &&
11082          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11083           KnownVal.Val.getInt() != 0))) {
11084       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11085       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11086           Context, BO_Add, PExp, IExp);
11087       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11088     }
11089   }
11090 
11091   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11092     return QualType();
11093 
11094   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11095     return QualType();
11096 
11097   // Check array bounds for pointer arithemtic
11098   CheckArrayAccess(PExp, IExp);
11099 
11100   if (CompLHSTy) {
11101     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11102     if (LHSTy.isNull()) {
11103       LHSTy = LHS.get()->getType();
11104       if (LHSTy->isPromotableIntegerType())
11105         LHSTy = Context.getPromotedIntegerType(LHSTy);
11106     }
11107     *CompLHSTy = LHSTy;
11108   }
11109 
11110   return PExp->getType();
11111 }
11112 
11113 // C99 6.5.6
11114 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11115                                         SourceLocation Loc,
11116                                         QualType* CompLHSTy) {
11117   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11118 
11119   if (LHS.get()->getType()->isVectorType() ||
11120       RHS.get()->getType()->isVectorType()) {
11121     QualType compType =
11122         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11123                             /*AllowBothBool*/ getLangOpts().AltiVec,
11124                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11125                             /*AllowBooleanOperation*/ false,
11126                             /*ReportInvalid*/ true);
11127     if (CompLHSTy) *CompLHSTy = compType;
11128     return compType;
11129   }
11130 
11131   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11132       RHS.get()->getType()->isVLSTBuiltinType()) {
11133     QualType compType =
11134         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11135     if (CompLHSTy)
11136       *CompLHSTy = compType;
11137     return compType;
11138   }
11139 
11140   if (LHS.get()->getType()->isConstantMatrixType() ||
11141       RHS.get()->getType()->isConstantMatrixType()) {
11142     QualType compType =
11143         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11144     if (CompLHSTy)
11145       *CompLHSTy = compType;
11146     return compType;
11147   }
11148 
11149   QualType compType = UsualArithmeticConversions(
11150       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11151   if (LHS.isInvalid() || RHS.isInvalid())
11152     return QualType();
11153 
11154   // Enforce type constraints: C99 6.5.6p3.
11155 
11156   // Handle the common case first (both operands are arithmetic).
11157   if (!compType.isNull() && compType->isArithmeticType()) {
11158     if (CompLHSTy) *CompLHSTy = compType;
11159     return compType;
11160   }
11161 
11162   // Either ptr - int   or   ptr - ptr.
11163   if (LHS.get()->getType()->isAnyPointerType()) {
11164     QualType lpointee = LHS.get()->getType()->getPointeeType();
11165 
11166     // Diagnose bad cases where we step over interface counts.
11167     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11168         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11169       return QualType();
11170 
11171     // The result type of a pointer-int computation is the pointer type.
11172     if (RHS.get()->getType()->isIntegerType()) {
11173       // Subtracting from a null pointer should produce a warning.
11174       // The last argument to the diagnose call says this doesn't match the
11175       // GNU int-to-pointer idiom.
11176       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11177                                            Expr::NPC_ValueDependentIsNotNull)) {
11178         // In C++ adding zero to a null pointer is defined.
11179         Expr::EvalResult KnownVal;
11180         if (!getLangOpts().CPlusPlus ||
11181             (!RHS.get()->isValueDependent() &&
11182              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11183               KnownVal.Val.getInt() != 0))) {
11184           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11185         }
11186       }
11187 
11188       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11189         return QualType();
11190 
11191       // Check array bounds for pointer arithemtic
11192       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11193                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11194 
11195       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11196       return LHS.get()->getType();
11197     }
11198 
11199     // Handle pointer-pointer subtractions.
11200     if (const PointerType *RHSPTy
11201           = RHS.get()->getType()->getAs<PointerType>()) {
11202       QualType rpointee = RHSPTy->getPointeeType();
11203 
11204       if (getLangOpts().CPlusPlus) {
11205         // Pointee types must be the same: C++ [expr.add]
11206         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11207           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11208         }
11209       } else {
11210         // Pointee types must be compatible C99 6.5.6p3
11211         if (!Context.typesAreCompatible(
11212                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11213                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11214           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11215           return QualType();
11216         }
11217       }
11218 
11219       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11220                                                LHS.get(), RHS.get()))
11221         return QualType();
11222 
11223       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11224           Context, Expr::NPC_ValueDependentIsNotNull);
11225       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11226           Context, Expr::NPC_ValueDependentIsNotNull);
11227 
11228       // Subtracting nullptr or from nullptr is suspect
11229       if (LHSIsNullPtr)
11230         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11231       if (RHSIsNullPtr)
11232         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11233 
11234       // The pointee type may have zero size.  As an extension, a structure or
11235       // union may have zero size or an array may have zero length.  In this
11236       // case subtraction does not make sense.
11237       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11238         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11239         if (ElementSize.isZero()) {
11240           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11241             << rpointee.getUnqualifiedType()
11242             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11243         }
11244       }
11245 
11246       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11247       return Context.getPointerDiffType();
11248     }
11249   }
11250 
11251   return InvalidOperands(Loc, LHS, RHS);
11252 }
11253 
11254 static bool isScopedEnumerationType(QualType T) {
11255   if (const EnumType *ET = T->getAs<EnumType>())
11256     return ET->getDecl()->isScoped();
11257   return false;
11258 }
11259 
11260 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11261                                    SourceLocation Loc, BinaryOperatorKind Opc,
11262                                    QualType LHSType) {
11263   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11264   // so skip remaining warnings as we don't want to modify values within Sema.
11265   if (S.getLangOpts().OpenCL)
11266     return;
11267 
11268   // Check right/shifter operand
11269   Expr::EvalResult RHSResult;
11270   if (RHS.get()->isValueDependent() ||
11271       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11272     return;
11273   llvm::APSInt Right = RHSResult.Val.getInt();
11274 
11275   if (Right.isNegative()) {
11276     S.DiagRuntimeBehavior(Loc, RHS.get(),
11277                           S.PDiag(diag::warn_shift_negative)
11278                             << RHS.get()->getSourceRange());
11279     return;
11280   }
11281 
11282   QualType LHSExprType = LHS.get()->getType();
11283   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11284   if (LHSExprType->isBitIntType())
11285     LeftSize = S.Context.getIntWidth(LHSExprType);
11286   else if (LHSExprType->isFixedPointType()) {
11287     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11288     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11289   }
11290   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11291   if (Right.uge(LeftBits)) {
11292     S.DiagRuntimeBehavior(Loc, RHS.get(),
11293                           S.PDiag(diag::warn_shift_gt_typewidth)
11294                             << RHS.get()->getSourceRange());
11295     return;
11296   }
11297 
11298   // FIXME: We probably need to handle fixed point types specially here.
11299   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11300     return;
11301 
11302   // When left shifting an ICE which is signed, we can check for overflow which
11303   // according to C++ standards prior to C++2a has undefined behavior
11304   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11305   // more than the maximum value representable in the result type, so never
11306   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11307   // expression is still probably a bug.)
11308   Expr::EvalResult LHSResult;
11309   if (LHS.get()->isValueDependent() ||
11310       LHSType->hasUnsignedIntegerRepresentation() ||
11311       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11312     return;
11313   llvm::APSInt Left = LHSResult.Val.getInt();
11314 
11315   // If LHS does not have a signed type and non-negative value
11316   // then, the behavior is undefined before C++2a. Warn about it.
11317   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11318       !S.getLangOpts().CPlusPlus20) {
11319     S.DiagRuntimeBehavior(Loc, LHS.get(),
11320                           S.PDiag(diag::warn_shift_lhs_negative)
11321                             << LHS.get()->getSourceRange());
11322     return;
11323   }
11324 
11325   llvm::APInt ResultBits =
11326       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11327   if (LeftBits.uge(ResultBits))
11328     return;
11329   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11330   Result = Result.shl(Right);
11331 
11332   // Print the bit representation of the signed integer as an unsigned
11333   // hexadecimal number.
11334   SmallString<40> HexResult;
11335   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11336 
11337   // If we are only missing a sign bit, this is less likely to result in actual
11338   // bugs -- if the result is cast back to an unsigned type, it will have the
11339   // expected value. Thus we place this behind a different warning that can be
11340   // turned off separately if needed.
11341   if (LeftBits == ResultBits - 1) {
11342     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11343         << HexResult << LHSType
11344         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11345     return;
11346   }
11347 
11348   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11349     << HexResult.str() << Result.getMinSignedBits() << LHSType
11350     << Left.getBitWidth() << LHS.get()->getSourceRange()
11351     << RHS.get()->getSourceRange();
11352 }
11353 
11354 /// Return the resulting type when a vector is shifted
11355 ///        by a scalar or vector shift amount.
11356 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11357                                  SourceLocation Loc, bool IsCompAssign) {
11358   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11359   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11360       !LHS.get()->getType()->isVectorType()) {
11361     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11362       << RHS.get()->getType() << LHS.get()->getType()
11363       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11364     return QualType();
11365   }
11366 
11367   if (!IsCompAssign) {
11368     LHS = S.UsualUnaryConversions(LHS.get());
11369     if (LHS.isInvalid()) return QualType();
11370   }
11371 
11372   RHS = S.UsualUnaryConversions(RHS.get());
11373   if (RHS.isInvalid()) return QualType();
11374 
11375   QualType LHSType = LHS.get()->getType();
11376   // Note that LHS might be a scalar because the routine calls not only in
11377   // OpenCL case.
11378   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11379   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11380 
11381   // Note that RHS might not be a vector.
11382   QualType RHSType = RHS.get()->getType();
11383   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11384   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11385 
11386   // Do not allow shifts for boolean vectors.
11387   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11388       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11389     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11390         << LHS.get()->getType() << RHS.get()->getType()
11391         << LHS.get()->getSourceRange();
11392     return QualType();
11393   }
11394 
11395   // The operands need to be integers.
11396   if (!LHSEleType->isIntegerType()) {
11397     S.Diag(Loc, diag::err_typecheck_expect_int)
11398       << LHS.get()->getType() << LHS.get()->getSourceRange();
11399     return QualType();
11400   }
11401 
11402   if (!RHSEleType->isIntegerType()) {
11403     S.Diag(Loc, diag::err_typecheck_expect_int)
11404       << RHS.get()->getType() << RHS.get()->getSourceRange();
11405     return QualType();
11406   }
11407 
11408   if (!LHSVecTy) {
11409     assert(RHSVecTy);
11410     if (IsCompAssign)
11411       return RHSType;
11412     if (LHSEleType != RHSEleType) {
11413       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11414       LHSEleType = RHSEleType;
11415     }
11416     QualType VecTy =
11417         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11418     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11419     LHSType = VecTy;
11420   } else if (RHSVecTy) {
11421     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11422     // are applied component-wise. So if RHS is a vector, then ensure
11423     // that the number of elements is the same as LHS...
11424     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11425       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11426         << LHS.get()->getType() << RHS.get()->getType()
11427         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11428       return QualType();
11429     }
11430     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11431       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11432       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11433       if (LHSBT != RHSBT &&
11434           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11435         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11436             << LHS.get()->getType() << RHS.get()->getType()
11437             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11438       }
11439     }
11440   } else {
11441     // ...else expand RHS to match the number of elements in LHS.
11442     QualType VecTy =
11443       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11444     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11445   }
11446 
11447   return LHSType;
11448 }
11449 
11450 // C99 6.5.7
11451 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11452                                   SourceLocation Loc, BinaryOperatorKind Opc,
11453                                   bool IsCompAssign) {
11454   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11455 
11456   // Vector shifts promote their scalar inputs to vector type.
11457   if (LHS.get()->getType()->isVectorType() ||
11458       RHS.get()->getType()->isVectorType()) {
11459     if (LangOpts.ZVector) {
11460       // The shift operators for the z vector extensions work basically
11461       // like general shifts, except that neither the LHS nor the RHS is
11462       // allowed to be a "vector bool".
11463       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11464         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11465           return InvalidOperands(Loc, LHS, RHS);
11466       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11467         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11468           return InvalidOperands(Loc, LHS, RHS);
11469     }
11470     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11471   }
11472 
11473   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11474       RHS.get()->getType()->isVLSTBuiltinType())
11475     return InvalidOperands(Loc, LHS, RHS);
11476 
11477   // Shifts don't perform usual arithmetic conversions, they just do integer
11478   // promotions on each operand. C99 6.5.7p3
11479 
11480   // For the LHS, do usual unary conversions, but then reset them away
11481   // if this is a compound assignment.
11482   ExprResult OldLHS = LHS;
11483   LHS = UsualUnaryConversions(LHS.get());
11484   if (LHS.isInvalid())
11485     return QualType();
11486   QualType LHSType = LHS.get()->getType();
11487   if (IsCompAssign) LHS = OldLHS;
11488 
11489   // The RHS is simpler.
11490   RHS = UsualUnaryConversions(RHS.get());
11491   if (RHS.isInvalid())
11492     return QualType();
11493   QualType RHSType = RHS.get()->getType();
11494 
11495   // C99 6.5.7p2: Each of the operands shall have integer type.
11496   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11497   if ((!LHSType->isFixedPointOrIntegerType() &&
11498        !LHSType->hasIntegerRepresentation()) ||
11499       !RHSType->hasIntegerRepresentation())
11500     return InvalidOperands(Loc, LHS, RHS);
11501 
11502   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11503   // hasIntegerRepresentation() above instead of this.
11504   if (isScopedEnumerationType(LHSType) ||
11505       isScopedEnumerationType(RHSType)) {
11506     return InvalidOperands(Loc, LHS, RHS);
11507   }
11508   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11509 
11510   // "The type of the result is that of the promoted left operand."
11511   return LHSType;
11512 }
11513 
11514 /// Diagnose bad pointer comparisons.
11515 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11516                                               ExprResult &LHS, ExprResult &RHS,
11517                                               bool IsError) {
11518   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11519                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11520     << LHS.get()->getType() << RHS.get()->getType()
11521     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11522 }
11523 
11524 /// Returns false if the pointers are converted to a composite type,
11525 /// true otherwise.
11526 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11527                                            ExprResult &LHS, ExprResult &RHS) {
11528   // C++ [expr.rel]p2:
11529   //   [...] Pointer conversions (4.10) and qualification
11530   //   conversions (4.4) are performed on pointer operands (or on
11531   //   a pointer operand and a null pointer constant) to bring
11532   //   them to their composite pointer type. [...]
11533   //
11534   // C++ [expr.eq]p1 uses the same notion for (in)equality
11535   // comparisons of pointers.
11536 
11537   QualType LHSType = LHS.get()->getType();
11538   QualType RHSType = RHS.get()->getType();
11539   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11540          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11541 
11542   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11543   if (T.isNull()) {
11544     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11545         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11546       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11547     else
11548       S.InvalidOperands(Loc, LHS, RHS);
11549     return true;
11550   }
11551 
11552   return false;
11553 }
11554 
11555 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11556                                                     ExprResult &LHS,
11557                                                     ExprResult &RHS,
11558                                                     bool IsError) {
11559   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11560                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11561     << LHS.get()->getType() << RHS.get()->getType()
11562     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11563 }
11564 
11565 static bool isObjCObjectLiteral(ExprResult &E) {
11566   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11567   case Stmt::ObjCArrayLiteralClass:
11568   case Stmt::ObjCDictionaryLiteralClass:
11569   case Stmt::ObjCStringLiteralClass:
11570   case Stmt::ObjCBoxedExprClass:
11571     return true;
11572   default:
11573     // Note that ObjCBoolLiteral is NOT an object literal!
11574     return false;
11575   }
11576 }
11577 
11578 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11579   const ObjCObjectPointerType *Type =
11580     LHS->getType()->getAs<ObjCObjectPointerType>();
11581 
11582   // If this is not actually an Objective-C object, bail out.
11583   if (!Type)
11584     return false;
11585 
11586   // Get the LHS object's interface type.
11587   QualType InterfaceType = Type->getPointeeType();
11588 
11589   // If the RHS isn't an Objective-C object, bail out.
11590   if (!RHS->getType()->isObjCObjectPointerType())
11591     return false;
11592 
11593   // Try to find the -isEqual: method.
11594   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11595   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11596                                                       InterfaceType,
11597                                                       /*IsInstance=*/true);
11598   if (!Method) {
11599     if (Type->isObjCIdType()) {
11600       // For 'id', just check the global pool.
11601       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11602                                                   /*receiverId=*/true);
11603     } else {
11604       // Check protocols.
11605       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11606                                              /*IsInstance=*/true);
11607     }
11608   }
11609 
11610   if (!Method)
11611     return false;
11612 
11613   QualType T = Method->parameters()[0]->getType();
11614   if (!T->isObjCObjectPointerType())
11615     return false;
11616 
11617   QualType R = Method->getReturnType();
11618   if (!R->isScalarType())
11619     return false;
11620 
11621   return true;
11622 }
11623 
11624 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11625   FromE = FromE->IgnoreParenImpCasts();
11626   switch (FromE->getStmtClass()) {
11627     default:
11628       break;
11629     case Stmt::ObjCStringLiteralClass:
11630       // "string literal"
11631       return LK_String;
11632     case Stmt::ObjCArrayLiteralClass:
11633       // "array literal"
11634       return LK_Array;
11635     case Stmt::ObjCDictionaryLiteralClass:
11636       // "dictionary literal"
11637       return LK_Dictionary;
11638     case Stmt::BlockExprClass:
11639       return LK_Block;
11640     case Stmt::ObjCBoxedExprClass: {
11641       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11642       switch (Inner->getStmtClass()) {
11643         case Stmt::IntegerLiteralClass:
11644         case Stmt::FloatingLiteralClass:
11645         case Stmt::CharacterLiteralClass:
11646         case Stmt::ObjCBoolLiteralExprClass:
11647         case Stmt::CXXBoolLiteralExprClass:
11648           // "numeric literal"
11649           return LK_Numeric;
11650         case Stmt::ImplicitCastExprClass: {
11651           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11652           // Boolean literals can be represented by implicit casts.
11653           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11654             return LK_Numeric;
11655           break;
11656         }
11657         default:
11658           break;
11659       }
11660       return LK_Boxed;
11661     }
11662   }
11663   return LK_None;
11664 }
11665 
11666 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11667                                           ExprResult &LHS, ExprResult &RHS,
11668                                           BinaryOperator::Opcode Opc){
11669   Expr *Literal;
11670   Expr *Other;
11671   if (isObjCObjectLiteral(LHS)) {
11672     Literal = LHS.get();
11673     Other = RHS.get();
11674   } else {
11675     Literal = RHS.get();
11676     Other = LHS.get();
11677   }
11678 
11679   // Don't warn on comparisons against nil.
11680   Other = Other->IgnoreParenCasts();
11681   if (Other->isNullPointerConstant(S.getASTContext(),
11682                                    Expr::NPC_ValueDependentIsNotNull))
11683     return;
11684 
11685   // This should be kept in sync with warn_objc_literal_comparison.
11686   // LK_String should always be after the other literals, since it has its own
11687   // warning flag.
11688   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11689   assert(LiteralKind != Sema::LK_Block);
11690   if (LiteralKind == Sema::LK_None) {
11691     llvm_unreachable("Unknown Objective-C object literal kind");
11692   }
11693 
11694   if (LiteralKind == Sema::LK_String)
11695     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11696       << Literal->getSourceRange();
11697   else
11698     S.Diag(Loc, diag::warn_objc_literal_comparison)
11699       << LiteralKind << Literal->getSourceRange();
11700 
11701   if (BinaryOperator::isEqualityOp(Opc) &&
11702       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11703     SourceLocation Start = LHS.get()->getBeginLoc();
11704     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11705     CharSourceRange OpRange =
11706       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11707 
11708     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11709       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11710       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11711       << FixItHint::CreateInsertion(End, "]");
11712   }
11713 }
11714 
11715 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11716 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11717                                            ExprResult &RHS, SourceLocation Loc,
11718                                            BinaryOperatorKind Opc) {
11719   // Check that left hand side is !something.
11720   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11721   if (!UO || UO->getOpcode() != UO_LNot) return;
11722 
11723   // Only check if the right hand side is non-bool arithmetic type.
11724   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11725 
11726   // Make sure that the something in !something is not bool.
11727   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11728   if (SubExpr->isKnownToHaveBooleanValue()) return;
11729 
11730   // Emit warning.
11731   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11732   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11733       << Loc << IsBitwiseOp;
11734 
11735   // First note suggest !(x < y)
11736   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11737   SourceLocation FirstClose = RHS.get()->getEndLoc();
11738   FirstClose = S.getLocForEndOfToken(FirstClose);
11739   if (FirstClose.isInvalid())
11740     FirstOpen = SourceLocation();
11741   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11742       << IsBitwiseOp
11743       << FixItHint::CreateInsertion(FirstOpen, "(")
11744       << FixItHint::CreateInsertion(FirstClose, ")");
11745 
11746   // Second note suggests (!x) < y
11747   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11748   SourceLocation SecondClose = LHS.get()->getEndLoc();
11749   SecondClose = S.getLocForEndOfToken(SecondClose);
11750   if (SecondClose.isInvalid())
11751     SecondOpen = SourceLocation();
11752   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11753       << FixItHint::CreateInsertion(SecondOpen, "(")
11754       << FixItHint::CreateInsertion(SecondClose, ")");
11755 }
11756 
11757 // Returns true if E refers to a non-weak array.
11758 static bool checkForArray(const Expr *E) {
11759   const ValueDecl *D = nullptr;
11760   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11761     D = DR->getDecl();
11762   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11763     if (Mem->isImplicitAccess())
11764       D = Mem->getMemberDecl();
11765   }
11766   if (!D)
11767     return false;
11768   return D->getType()->isArrayType() && !D->isWeak();
11769 }
11770 
11771 /// Diagnose some forms of syntactically-obvious tautological comparison.
11772 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11773                                            Expr *LHS, Expr *RHS,
11774                                            BinaryOperatorKind Opc) {
11775   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11776   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11777 
11778   QualType LHSType = LHS->getType();
11779   QualType RHSType = RHS->getType();
11780   if (LHSType->hasFloatingRepresentation() ||
11781       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11782       S.inTemplateInstantiation())
11783     return;
11784 
11785   // Comparisons between two array types are ill-formed for operator<=>, so
11786   // we shouldn't emit any additional warnings about it.
11787   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11788     return;
11789 
11790   // For non-floating point types, check for self-comparisons of the form
11791   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11792   // often indicate logic errors in the program.
11793   //
11794   // NOTE: Don't warn about comparison expressions resulting from macro
11795   // expansion. Also don't warn about comparisons which are only self
11796   // comparisons within a template instantiation. The warnings should catch
11797   // obvious cases in the definition of the template anyways. The idea is to
11798   // warn when the typed comparison operator will always evaluate to the same
11799   // result.
11800 
11801   // Used for indexing into %select in warn_comparison_always
11802   enum {
11803     AlwaysConstant,
11804     AlwaysTrue,
11805     AlwaysFalse,
11806     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11807   };
11808 
11809   // C++2a [depr.array.comp]:
11810   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11811   //   operands of array type are deprecated.
11812   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11813       RHSStripped->getType()->isArrayType()) {
11814     S.Diag(Loc, diag::warn_depr_array_comparison)
11815         << LHS->getSourceRange() << RHS->getSourceRange()
11816         << LHSStripped->getType() << RHSStripped->getType();
11817     // Carry on to produce the tautological comparison warning, if this
11818     // expression is potentially-evaluated, we can resolve the array to a
11819     // non-weak declaration, and so on.
11820   }
11821 
11822   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11823     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11824       unsigned Result;
11825       switch (Opc) {
11826       case BO_EQ:
11827       case BO_LE:
11828       case BO_GE:
11829         Result = AlwaysTrue;
11830         break;
11831       case BO_NE:
11832       case BO_LT:
11833       case BO_GT:
11834         Result = AlwaysFalse;
11835         break;
11836       case BO_Cmp:
11837         Result = AlwaysEqual;
11838         break;
11839       default:
11840         Result = AlwaysConstant;
11841         break;
11842       }
11843       S.DiagRuntimeBehavior(Loc, nullptr,
11844                             S.PDiag(diag::warn_comparison_always)
11845                                 << 0 /*self-comparison*/
11846                                 << Result);
11847     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11848       // What is it always going to evaluate to?
11849       unsigned Result;
11850       switch (Opc) {
11851       case BO_EQ: // e.g. array1 == array2
11852         Result = AlwaysFalse;
11853         break;
11854       case BO_NE: // e.g. array1 != array2
11855         Result = AlwaysTrue;
11856         break;
11857       default: // e.g. array1 <= array2
11858         // The best we can say is 'a constant'
11859         Result = AlwaysConstant;
11860         break;
11861       }
11862       S.DiagRuntimeBehavior(Loc, nullptr,
11863                             S.PDiag(diag::warn_comparison_always)
11864                                 << 1 /*array comparison*/
11865                                 << Result);
11866     }
11867   }
11868 
11869   if (isa<CastExpr>(LHSStripped))
11870     LHSStripped = LHSStripped->IgnoreParenCasts();
11871   if (isa<CastExpr>(RHSStripped))
11872     RHSStripped = RHSStripped->IgnoreParenCasts();
11873 
11874   // Warn about comparisons against a string constant (unless the other
11875   // operand is null); the user probably wants string comparison function.
11876   Expr *LiteralString = nullptr;
11877   Expr *LiteralStringStripped = nullptr;
11878   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11879       !RHSStripped->isNullPointerConstant(S.Context,
11880                                           Expr::NPC_ValueDependentIsNull)) {
11881     LiteralString = LHS;
11882     LiteralStringStripped = LHSStripped;
11883   } else if ((isa<StringLiteral>(RHSStripped) ||
11884               isa<ObjCEncodeExpr>(RHSStripped)) &&
11885              !LHSStripped->isNullPointerConstant(S.Context,
11886                                           Expr::NPC_ValueDependentIsNull)) {
11887     LiteralString = RHS;
11888     LiteralStringStripped = RHSStripped;
11889   }
11890 
11891   if (LiteralString) {
11892     S.DiagRuntimeBehavior(Loc, nullptr,
11893                           S.PDiag(diag::warn_stringcompare)
11894                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11895                               << LiteralString->getSourceRange());
11896   }
11897 }
11898 
11899 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11900   switch (CK) {
11901   default: {
11902 #ifndef NDEBUG
11903     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11904                  << "\n";
11905 #endif
11906     llvm_unreachable("unhandled cast kind");
11907   }
11908   case CK_UserDefinedConversion:
11909     return ICK_Identity;
11910   case CK_LValueToRValue:
11911     return ICK_Lvalue_To_Rvalue;
11912   case CK_ArrayToPointerDecay:
11913     return ICK_Array_To_Pointer;
11914   case CK_FunctionToPointerDecay:
11915     return ICK_Function_To_Pointer;
11916   case CK_IntegralCast:
11917     return ICK_Integral_Conversion;
11918   case CK_FloatingCast:
11919     return ICK_Floating_Conversion;
11920   case CK_IntegralToFloating:
11921   case CK_FloatingToIntegral:
11922     return ICK_Floating_Integral;
11923   case CK_IntegralComplexCast:
11924   case CK_FloatingComplexCast:
11925   case CK_FloatingComplexToIntegralComplex:
11926   case CK_IntegralComplexToFloatingComplex:
11927     return ICK_Complex_Conversion;
11928   case CK_FloatingComplexToReal:
11929   case CK_FloatingRealToComplex:
11930   case CK_IntegralComplexToReal:
11931   case CK_IntegralRealToComplex:
11932     return ICK_Complex_Real;
11933   }
11934 }
11935 
11936 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11937                                              QualType FromType,
11938                                              SourceLocation Loc) {
11939   // Check for a narrowing implicit conversion.
11940   StandardConversionSequence SCS;
11941   SCS.setAsIdentityConversion();
11942   SCS.setToType(0, FromType);
11943   SCS.setToType(1, ToType);
11944   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11945     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11946 
11947   APValue PreNarrowingValue;
11948   QualType PreNarrowingType;
11949   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11950                                PreNarrowingType,
11951                                /*IgnoreFloatToIntegralConversion*/ true)) {
11952   case NK_Dependent_Narrowing:
11953     // Implicit conversion to a narrower type, but the expression is
11954     // value-dependent so we can't tell whether it's actually narrowing.
11955   case NK_Not_Narrowing:
11956     return false;
11957 
11958   case NK_Constant_Narrowing:
11959     // Implicit conversion to a narrower type, and the value is not a constant
11960     // expression.
11961     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11962         << /*Constant*/ 1
11963         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11964     return true;
11965 
11966   case NK_Variable_Narrowing:
11967     // Implicit conversion to a narrower type, and the value is not a constant
11968     // expression.
11969   case NK_Type_Narrowing:
11970     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11971         << /*Constant*/ 0 << FromType << ToType;
11972     // TODO: It's not a constant expression, but what if the user intended it
11973     // to be? Can we produce notes to help them figure out why it isn't?
11974     return true;
11975   }
11976   llvm_unreachable("unhandled case in switch");
11977 }
11978 
11979 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11980                                                          ExprResult &LHS,
11981                                                          ExprResult &RHS,
11982                                                          SourceLocation Loc) {
11983   QualType LHSType = LHS.get()->getType();
11984   QualType RHSType = RHS.get()->getType();
11985   // Dig out the original argument type and expression before implicit casts
11986   // were applied. These are the types/expressions we need to check the
11987   // [expr.spaceship] requirements against.
11988   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11989   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11990   QualType LHSStrippedType = LHSStripped.get()->getType();
11991   QualType RHSStrippedType = RHSStripped.get()->getType();
11992 
11993   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11994   // other is not, the program is ill-formed.
11995   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11996     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11997     return QualType();
11998   }
11999 
12000   // FIXME: Consider combining this with checkEnumArithmeticConversions.
12001   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12002                     RHSStrippedType->isEnumeralType();
12003   if (NumEnumArgs == 1) {
12004     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12005     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12006     if (OtherTy->hasFloatingRepresentation()) {
12007       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12008       return QualType();
12009     }
12010   }
12011   if (NumEnumArgs == 2) {
12012     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12013     // type E, the operator yields the result of converting the operands
12014     // to the underlying type of E and applying <=> to the converted operands.
12015     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12016       S.InvalidOperands(Loc, LHS, RHS);
12017       return QualType();
12018     }
12019     QualType IntType =
12020         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12021     assert(IntType->isArithmeticType());
12022 
12023     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12024     // promote the boolean type, and all other promotable integer types, to
12025     // avoid this.
12026     if (IntType->isPromotableIntegerType())
12027       IntType = S.Context.getPromotedIntegerType(IntType);
12028 
12029     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12030     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12031     LHSType = RHSType = IntType;
12032   }
12033 
12034   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12035   // usual arithmetic conversions are applied to the operands.
12036   QualType Type =
12037       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12038   if (LHS.isInvalid() || RHS.isInvalid())
12039     return QualType();
12040   if (Type.isNull())
12041     return S.InvalidOperands(Loc, LHS, RHS);
12042 
12043   Optional<ComparisonCategoryType> CCT =
12044       getComparisonCategoryForBuiltinCmp(Type);
12045   if (!CCT)
12046     return S.InvalidOperands(Loc, LHS, RHS);
12047 
12048   bool HasNarrowing = checkThreeWayNarrowingConversion(
12049       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12050   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12051                                                    RHS.get()->getBeginLoc());
12052   if (HasNarrowing)
12053     return QualType();
12054 
12055   assert(!Type.isNull() && "composite type for <=> has not been set");
12056 
12057   return S.CheckComparisonCategoryType(
12058       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12059 }
12060 
12061 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12062                                                  ExprResult &RHS,
12063                                                  SourceLocation Loc,
12064                                                  BinaryOperatorKind Opc) {
12065   if (Opc == BO_Cmp)
12066     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12067 
12068   // C99 6.5.8p3 / C99 6.5.9p4
12069   QualType Type =
12070       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12071   if (LHS.isInvalid() || RHS.isInvalid())
12072     return QualType();
12073   if (Type.isNull())
12074     return S.InvalidOperands(Loc, LHS, RHS);
12075   assert(Type->isArithmeticType() || Type->isEnumeralType());
12076 
12077   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12078     return S.InvalidOperands(Loc, LHS, RHS);
12079 
12080   // Check for comparisons of floating point operands using != and ==.
12081   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12082     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12083 
12084   // The result of comparisons is 'bool' in C++, 'int' in C.
12085   return S.Context.getLogicalOperationType();
12086 }
12087 
12088 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12089   if (!NullE.get()->getType()->isAnyPointerType())
12090     return;
12091   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12092   if (!E.get()->getType()->isAnyPointerType() &&
12093       E.get()->isNullPointerConstant(Context,
12094                                      Expr::NPC_ValueDependentIsNotNull) ==
12095         Expr::NPCK_ZeroExpression) {
12096     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12097       if (CL->getValue() == 0)
12098         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12099             << NullValue
12100             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12101                                             NullValue ? "NULL" : "(void *)0");
12102     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12103         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12104         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12105         if (T == Context.CharTy)
12106           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12107               << NullValue
12108               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12109                                               NullValue ? "NULL" : "(void *)0");
12110       }
12111   }
12112 }
12113 
12114 // C99 6.5.8, C++ [expr.rel]
12115 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12116                                     SourceLocation Loc,
12117                                     BinaryOperatorKind Opc) {
12118   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12119   bool IsThreeWay = Opc == BO_Cmp;
12120   bool IsOrdered = IsRelational || IsThreeWay;
12121   auto IsAnyPointerType = [](ExprResult E) {
12122     QualType Ty = E.get()->getType();
12123     return Ty->isPointerType() || Ty->isMemberPointerType();
12124   };
12125 
12126   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12127   // type, array-to-pointer, ..., conversions are performed on both operands to
12128   // bring them to their composite type.
12129   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12130   // any type-related checks.
12131   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12132     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12133     if (LHS.isInvalid())
12134       return QualType();
12135     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12136     if (RHS.isInvalid())
12137       return QualType();
12138   } else {
12139     LHS = DefaultLvalueConversion(LHS.get());
12140     if (LHS.isInvalid())
12141       return QualType();
12142     RHS = DefaultLvalueConversion(RHS.get());
12143     if (RHS.isInvalid())
12144       return QualType();
12145   }
12146 
12147   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12148   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12149     CheckPtrComparisonWithNullChar(LHS, RHS);
12150     CheckPtrComparisonWithNullChar(RHS, LHS);
12151   }
12152 
12153   // Handle vector comparisons separately.
12154   if (LHS.get()->getType()->isVectorType() ||
12155       RHS.get()->getType()->isVectorType())
12156     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12157 
12158   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12159       RHS.get()->getType()->isVLSTBuiltinType())
12160     return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12161 
12162   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12163   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12164 
12165   QualType LHSType = LHS.get()->getType();
12166   QualType RHSType = RHS.get()->getType();
12167   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12168       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12169     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12170 
12171   const Expr::NullPointerConstantKind LHSNullKind =
12172       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12173   const Expr::NullPointerConstantKind RHSNullKind =
12174       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12175   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12176   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12177 
12178   auto computeResultTy = [&]() {
12179     if (Opc != BO_Cmp)
12180       return Context.getLogicalOperationType();
12181     assert(getLangOpts().CPlusPlus);
12182     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12183 
12184     QualType CompositeTy = LHS.get()->getType();
12185     assert(!CompositeTy->isReferenceType());
12186 
12187     Optional<ComparisonCategoryType> CCT =
12188         getComparisonCategoryForBuiltinCmp(CompositeTy);
12189     if (!CCT)
12190       return InvalidOperands(Loc, LHS, RHS);
12191 
12192     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12193       // P0946R0: Comparisons between a null pointer constant and an object
12194       // pointer result in std::strong_equality, which is ill-formed under
12195       // P1959R0.
12196       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12197           << (LHSIsNull ? LHS.get()->getSourceRange()
12198                         : RHS.get()->getSourceRange());
12199       return QualType();
12200     }
12201 
12202     return CheckComparisonCategoryType(
12203         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12204   };
12205 
12206   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12207     bool IsEquality = Opc == BO_EQ;
12208     if (RHSIsNull)
12209       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12210                                    RHS.get()->getSourceRange());
12211     else
12212       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12213                                    LHS.get()->getSourceRange());
12214   }
12215 
12216   if (IsOrdered && LHSType->isFunctionPointerType() &&
12217       RHSType->isFunctionPointerType()) {
12218     // Valid unless a relational comparison of function pointers
12219     bool IsError = Opc == BO_Cmp;
12220     auto DiagID =
12221         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12222         : getLangOpts().CPlusPlus
12223             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12224             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12225     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12226                       << RHS.get()->getSourceRange();
12227     if (IsError)
12228       return QualType();
12229   }
12230 
12231   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12232       (RHSType->isIntegerType() && !RHSIsNull)) {
12233     // Skip normal pointer conversion checks in this case; we have better
12234     // diagnostics for this below.
12235   } else if (getLangOpts().CPlusPlus) {
12236     // Equality comparison of a function pointer to a void pointer is invalid,
12237     // but we allow it as an extension.
12238     // FIXME: If we really want to allow this, should it be part of composite
12239     // pointer type computation so it works in conditionals too?
12240     if (!IsOrdered &&
12241         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12242          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12243       // This is a gcc extension compatibility comparison.
12244       // In a SFINAE context, we treat this as a hard error to maintain
12245       // conformance with the C++ standard.
12246       diagnoseFunctionPointerToVoidComparison(
12247           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12248 
12249       if (isSFINAEContext())
12250         return QualType();
12251 
12252       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12253       return computeResultTy();
12254     }
12255 
12256     // C++ [expr.eq]p2:
12257     //   If at least one operand is a pointer [...] bring them to their
12258     //   composite pointer type.
12259     // C++ [expr.spaceship]p6
12260     //  If at least one of the operands is of pointer type, [...] bring them
12261     //  to their composite pointer type.
12262     // C++ [expr.rel]p2:
12263     //   If both operands are pointers, [...] bring them to their composite
12264     //   pointer type.
12265     // For <=>, the only valid non-pointer types are arrays and functions, and
12266     // we already decayed those, so this is really the same as the relational
12267     // comparison rule.
12268     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12269             (IsOrdered ? 2 : 1) &&
12270         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12271                                          RHSType->isObjCObjectPointerType()))) {
12272       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12273         return QualType();
12274       return computeResultTy();
12275     }
12276   } else if (LHSType->isPointerType() &&
12277              RHSType->isPointerType()) { // C99 6.5.8p2
12278     // All of the following pointer-related warnings are GCC extensions, except
12279     // when handling null pointer constants.
12280     QualType LCanPointeeTy =
12281       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12282     QualType RCanPointeeTy =
12283       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12284 
12285     // C99 6.5.9p2 and C99 6.5.8p2
12286     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12287                                    RCanPointeeTy.getUnqualifiedType())) {
12288       if (IsRelational) {
12289         // Pointers both need to point to complete or incomplete types
12290         if ((LCanPointeeTy->isIncompleteType() !=
12291              RCanPointeeTy->isIncompleteType()) &&
12292             !getLangOpts().C11) {
12293           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12294               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12295               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12296               << RCanPointeeTy->isIncompleteType();
12297         }
12298       }
12299     } else if (!IsRelational &&
12300                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12301       // Valid unless comparison between non-null pointer and function pointer
12302       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12303           && !LHSIsNull && !RHSIsNull)
12304         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12305                                                 /*isError*/false);
12306     } else {
12307       // Invalid
12308       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12309     }
12310     if (LCanPointeeTy != RCanPointeeTy) {
12311       // Treat NULL constant as a special case in OpenCL.
12312       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12313         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12314           Diag(Loc,
12315                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12316               << LHSType << RHSType << 0 /* comparison */
12317               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12318         }
12319       }
12320       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12321       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12322       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12323                                                : CK_BitCast;
12324       if (LHSIsNull && !RHSIsNull)
12325         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12326       else
12327         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12328     }
12329     return computeResultTy();
12330   }
12331 
12332   if (getLangOpts().CPlusPlus) {
12333     // C++ [expr.eq]p4:
12334     //   Two operands of type std::nullptr_t or one operand of type
12335     //   std::nullptr_t and the other a null pointer constant compare equal.
12336     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12337       if (LHSType->isNullPtrType()) {
12338         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12339         return computeResultTy();
12340       }
12341       if (RHSType->isNullPtrType()) {
12342         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12343         return computeResultTy();
12344       }
12345     }
12346 
12347     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12348     // These aren't covered by the composite pointer type rules.
12349     if (!IsOrdered && RHSType->isNullPtrType() &&
12350         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12351       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12352       return computeResultTy();
12353     }
12354     if (!IsOrdered && LHSType->isNullPtrType() &&
12355         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12356       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12357       return computeResultTy();
12358     }
12359 
12360     if (IsRelational &&
12361         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12362          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12363       // HACK: Relational comparison of nullptr_t against a pointer type is
12364       // invalid per DR583, but we allow it within std::less<> and friends,
12365       // since otherwise common uses of it break.
12366       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12367       // friends to have std::nullptr_t overload candidates.
12368       DeclContext *DC = CurContext;
12369       if (isa<FunctionDecl>(DC))
12370         DC = DC->getParent();
12371       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12372         if (CTSD->isInStdNamespace() &&
12373             llvm::StringSwitch<bool>(CTSD->getName())
12374                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12375                 .Default(false)) {
12376           if (RHSType->isNullPtrType())
12377             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12378           else
12379             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12380           return computeResultTy();
12381         }
12382       }
12383     }
12384 
12385     // C++ [expr.eq]p2:
12386     //   If at least one operand is a pointer to member, [...] bring them to
12387     //   their composite pointer type.
12388     if (!IsOrdered &&
12389         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12390       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12391         return QualType();
12392       else
12393         return computeResultTy();
12394     }
12395   }
12396 
12397   // Handle block pointer types.
12398   if (!IsOrdered && LHSType->isBlockPointerType() &&
12399       RHSType->isBlockPointerType()) {
12400     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12401     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12402 
12403     if (!LHSIsNull && !RHSIsNull &&
12404         !Context.typesAreCompatible(lpointee, rpointee)) {
12405       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12406         << LHSType << RHSType << LHS.get()->getSourceRange()
12407         << RHS.get()->getSourceRange();
12408     }
12409     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12410     return computeResultTy();
12411   }
12412 
12413   // Allow block pointers to be compared with null pointer constants.
12414   if (!IsOrdered
12415       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12416           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12417     if (!LHSIsNull && !RHSIsNull) {
12418       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12419              ->getPointeeType()->isVoidType())
12420             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12421                 ->getPointeeType()->isVoidType())))
12422         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12423           << LHSType << RHSType << LHS.get()->getSourceRange()
12424           << RHS.get()->getSourceRange();
12425     }
12426     if (LHSIsNull && !RHSIsNull)
12427       LHS = ImpCastExprToType(LHS.get(), RHSType,
12428                               RHSType->isPointerType() ? CK_BitCast
12429                                 : CK_AnyPointerToBlockPointerCast);
12430     else
12431       RHS = ImpCastExprToType(RHS.get(), LHSType,
12432                               LHSType->isPointerType() ? CK_BitCast
12433                                 : CK_AnyPointerToBlockPointerCast);
12434     return computeResultTy();
12435   }
12436 
12437   if (LHSType->isObjCObjectPointerType() ||
12438       RHSType->isObjCObjectPointerType()) {
12439     const PointerType *LPT = LHSType->getAs<PointerType>();
12440     const PointerType *RPT = RHSType->getAs<PointerType>();
12441     if (LPT || RPT) {
12442       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12443       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12444 
12445       if (!LPtrToVoid && !RPtrToVoid &&
12446           !Context.typesAreCompatible(LHSType, RHSType)) {
12447         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12448                                           /*isError*/false);
12449       }
12450       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12451       // the RHS, but we have test coverage for this behavior.
12452       // FIXME: Consider using convertPointersToCompositeType in C++.
12453       if (LHSIsNull && !RHSIsNull) {
12454         Expr *E = LHS.get();
12455         if (getLangOpts().ObjCAutoRefCount)
12456           CheckObjCConversion(SourceRange(), RHSType, E,
12457                               CCK_ImplicitConversion);
12458         LHS = ImpCastExprToType(E, RHSType,
12459                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12460       }
12461       else {
12462         Expr *E = RHS.get();
12463         if (getLangOpts().ObjCAutoRefCount)
12464           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12465                               /*Diagnose=*/true,
12466                               /*DiagnoseCFAudited=*/false, Opc);
12467         RHS = ImpCastExprToType(E, LHSType,
12468                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12469       }
12470       return computeResultTy();
12471     }
12472     if (LHSType->isObjCObjectPointerType() &&
12473         RHSType->isObjCObjectPointerType()) {
12474       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12475         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12476                                           /*isError*/false);
12477       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12478         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12479 
12480       if (LHSIsNull && !RHSIsNull)
12481         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12482       else
12483         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12484       return computeResultTy();
12485     }
12486 
12487     if (!IsOrdered && LHSType->isBlockPointerType() &&
12488         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12489       LHS = ImpCastExprToType(LHS.get(), RHSType,
12490                               CK_BlockPointerToObjCPointerCast);
12491       return computeResultTy();
12492     } else if (!IsOrdered &&
12493                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12494                RHSType->isBlockPointerType()) {
12495       RHS = ImpCastExprToType(RHS.get(), LHSType,
12496                               CK_BlockPointerToObjCPointerCast);
12497       return computeResultTy();
12498     }
12499   }
12500   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12501       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12502     unsigned DiagID = 0;
12503     bool isError = false;
12504     if (LangOpts.DebuggerSupport) {
12505       // Under a debugger, allow the comparison of pointers to integers,
12506       // since users tend to want to compare addresses.
12507     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12508                (RHSIsNull && RHSType->isIntegerType())) {
12509       if (IsOrdered) {
12510         isError = getLangOpts().CPlusPlus;
12511         DiagID =
12512           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12513                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12514       }
12515     } else if (getLangOpts().CPlusPlus) {
12516       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12517       isError = true;
12518     } else if (IsOrdered)
12519       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12520     else
12521       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12522 
12523     if (DiagID) {
12524       Diag(Loc, DiagID)
12525         << LHSType << RHSType << LHS.get()->getSourceRange()
12526         << RHS.get()->getSourceRange();
12527       if (isError)
12528         return QualType();
12529     }
12530 
12531     if (LHSType->isIntegerType())
12532       LHS = ImpCastExprToType(LHS.get(), RHSType,
12533                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12534     else
12535       RHS = ImpCastExprToType(RHS.get(), LHSType,
12536                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12537     return computeResultTy();
12538   }
12539 
12540   // Handle block pointers.
12541   if (!IsOrdered && RHSIsNull
12542       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12543     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12544     return computeResultTy();
12545   }
12546   if (!IsOrdered && LHSIsNull
12547       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12548     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12549     return computeResultTy();
12550   }
12551 
12552   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12553     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12554       return computeResultTy();
12555     }
12556 
12557     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12558       return computeResultTy();
12559     }
12560 
12561     if (LHSIsNull && RHSType->isQueueT()) {
12562       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12563       return computeResultTy();
12564     }
12565 
12566     if (LHSType->isQueueT() && RHSIsNull) {
12567       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12568       return computeResultTy();
12569     }
12570   }
12571 
12572   return InvalidOperands(Loc, LHS, RHS);
12573 }
12574 
12575 // Return a signed ext_vector_type that is of identical size and number of
12576 // elements. For floating point vectors, return an integer type of identical
12577 // size and number of elements. In the non ext_vector_type case, search from
12578 // the largest type to the smallest type to avoid cases where long long == long,
12579 // where long gets picked over long long.
12580 QualType Sema::GetSignedVectorType(QualType V) {
12581   const VectorType *VTy = V->castAs<VectorType>();
12582   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12583 
12584   if (isa<ExtVectorType>(VTy)) {
12585     if (VTy->isExtVectorBoolType())
12586       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12587     if (TypeSize == Context.getTypeSize(Context.CharTy))
12588       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12589     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12590       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12591     if (TypeSize == Context.getTypeSize(Context.IntTy))
12592       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12593     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12594       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12595     if (TypeSize == Context.getTypeSize(Context.LongTy))
12596       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12597     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12598            "Unhandled vector element size in vector compare");
12599     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12600   }
12601 
12602   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12603     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12604                                  VectorType::GenericVector);
12605   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12606     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12607                                  VectorType::GenericVector);
12608   if (TypeSize == Context.getTypeSize(Context.LongTy))
12609     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12610                                  VectorType::GenericVector);
12611   if (TypeSize == Context.getTypeSize(Context.IntTy))
12612     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12613                                  VectorType::GenericVector);
12614   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12615     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12616                                  VectorType::GenericVector);
12617   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12618          "Unhandled vector element size in vector compare");
12619   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12620                                VectorType::GenericVector);
12621 }
12622 
12623 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12624   const BuiltinType *VTy = V->castAs<BuiltinType>();
12625   assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12626 
12627   const QualType ETy = V->getSveEltType(Context);
12628   const auto TypeSize = Context.getTypeSize(ETy);
12629 
12630   const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12631   const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12632   return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12633 }
12634 
12635 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12636 /// operates on extended vector types.  Instead of producing an IntTy result,
12637 /// like a scalar comparison, a vector comparison produces a vector of integer
12638 /// types.
12639 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12640                                           SourceLocation Loc,
12641                                           BinaryOperatorKind Opc) {
12642   if (Opc == BO_Cmp) {
12643     Diag(Loc, diag::err_three_way_vector_comparison);
12644     return QualType();
12645   }
12646 
12647   // Check to make sure we're operating on vectors of the same type and width,
12648   // Allowing one side to be a scalar of element type.
12649   QualType vType =
12650       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12651                           /*AllowBothBool*/ true,
12652                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12653                           /*AllowBooleanOperation*/ true,
12654                           /*ReportInvalid*/ true);
12655   if (vType.isNull())
12656     return vType;
12657 
12658   QualType LHSType = LHS.get()->getType();
12659 
12660   // Determine the return type of a vector compare. By default clang will return
12661   // a scalar for all vector compares except vector bool and vector pixel.
12662   // With the gcc compiler we will always return a vector type and with the xl
12663   // compiler we will always return a scalar type. This switch allows choosing
12664   // which behavior is prefered.
12665   if (getLangOpts().AltiVec) {
12666     switch (getLangOpts().getAltivecSrcCompat()) {
12667     case LangOptions::AltivecSrcCompatKind::Mixed:
12668       // If AltiVec, the comparison results in a numeric type, i.e.
12669       // bool for C++, int for C
12670       if (vType->castAs<VectorType>()->getVectorKind() ==
12671           VectorType::AltiVecVector)
12672         return Context.getLogicalOperationType();
12673       else
12674         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12675       break;
12676     case LangOptions::AltivecSrcCompatKind::GCC:
12677       // For GCC we always return the vector type.
12678       break;
12679     case LangOptions::AltivecSrcCompatKind::XL:
12680       return Context.getLogicalOperationType();
12681       break;
12682     }
12683   }
12684 
12685   // For non-floating point types, check for self-comparisons of the form
12686   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12687   // often indicate logic errors in the program.
12688   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12689 
12690   // Check for comparisons of floating point operands using != and ==.
12691   if (BinaryOperator::isEqualityOp(Opc) &&
12692       LHSType->hasFloatingRepresentation()) {
12693     assert(RHS.get()->getType()->hasFloatingRepresentation());
12694     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12695   }
12696 
12697   // Return a signed type for the vector.
12698   return GetSignedVectorType(vType);
12699 }
12700 
12701 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12702                                                   ExprResult &RHS,
12703                                                   SourceLocation Loc,
12704                                                   BinaryOperatorKind Opc) {
12705   if (Opc == BO_Cmp) {
12706     Diag(Loc, diag::err_three_way_vector_comparison);
12707     return QualType();
12708   }
12709 
12710   // Check to make sure we're operating on vectors of the same type and width,
12711   // Allowing one side to be a scalar of element type.
12712   QualType vType = CheckSizelessVectorOperands(
12713       LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12714 
12715   if (vType.isNull())
12716     return vType;
12717 
12718   QualType LHSType = LHS.get()->getType();
12719 
12720   // For non-floating point types, check for self-comparisons of the form
12721   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12722   // often indicate logic errors in the program.
12723   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12724 
12725   // Check for comparisons of floating point operands using != and ==.
12726   if (BinaryOperator::isEqualityOp(Opc) &&
12727       LHSType->hasFloatingRepresentation()) {
12728     assert(RHS.get()->getType()->hasFloatingRepresentation());
12729     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12730   }
12731 
12732   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12733   const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12734 
12735   if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12736       RHSBuiltinTy->isSVEBool())
12737     return LHSType;
12738 
12739   // Return a signed type for the vector.
12740   return GetSignedSizelessVectorType(vType);
12741 }
12742 
12743 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12744                                     const ExprResult &XorRHS,
12745                                     const SourceLocation Loc) {
12746   // Do not diagnose macros.
12747   if (Loc.isMacroID())
12748     return;
12749 
12750   // Do not diagnose if both LHS and RHS are macros.
12751   if (XorLHS.get()->getExprLoc().isMacroID() &&
12752       XorRHS.get()->getExprLoc().isMacroID())
12753     return;
12754 
12755   bool Negative = false;
12756   bool ExplicitPlus = false;
12757   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12758   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12759 
12760   if (!LHSInt)
12761     return;
12762   if (!RHSInt) {
12763     // Check negative literals.
12764     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12765       UnaryOperatorKind Opc = UO->getOpcode();
12766       if (Opc != UO_Minus && Opc != UO_Plus)
12767         return;
12768       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12769       if (!RHSInt)
12770         return;
12771       Negative = (Opc == UO_Minus);
12772       ExplicitPlus = !Negative;
12773     } else {
12774       return;
12775     }
12776   }
12777 
12778   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12779   llvm::APInt RightSideValue = RHSInt->getValue();
12780   if (LeftSideValue != 2 && LeftSideValue != 10)
12781     return;
12782 
12783   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12784     return;
12785 
12786   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12787       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12788   llvm::StringRef ExprStr =
12789       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12790 
12791   CharSourceRange XorRange =
12792       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12793   llvm::StringRef XorStr =
12794       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12795   // Do not diagnose if xor keyword/macro is used.
12796   if (XorStr == "xor")
12797     return;
12798 
12799   std::string LHSStr = std::string(Lexer::getSourceText(
12800       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12801       S.getSourceManager(), S.getLangOpts()));
12802   std::string RHSStr = std::string(Lexer::getSourceText(
12803       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12804       S.getSourceManager(), S.getLangOpts()));
12805 
12806   if (Negative) {
12807     RightSideValue = -RightSideValue;
12808     RHSStr = "-" + RHSStr;
12809   } else if (ExplicitPlus) {
12810     RHSStr = "+" + RHSStr;
12811   }
12812 
12813   StringRef LHSStrRef = LHSStr;
12814   StringRef RHSStrRef = RHSStr;
12815   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12816   // literals.
12817   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12818       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12819       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12820       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12821       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12822       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12823       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12824     return;
12825 
12826   bool SuggestXor =
12827       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12828   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12829   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12830   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12831     std::string SuggestedExpr = "1 << " + RHSStr;
12832     bool Overflow = false;
12833     llvm::APInt One = (LeftSideValue - 1);
12834     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12835     if (Overflow) {
12836       if (RightSideIntValue < 64)
12837         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12838             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12839             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12840       else if (RightSideIntValue == 64)
12841         S.Diag(Loc, diag::warn_xor_used_as_pow)
12842             << ExprStr << toString(XorValue, 10, true);
12843       else
12844         return;
12845     } else {
12846       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12847           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12848           << toString(PowValue, 10, true)
12849           << FixItHint::CreateReplacement(
12850                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12851     }
12852 
12853     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12854         << ("0x2 ^ " + RHSStr) << SuggestXor;
12855   } else if (LeftSideValue == 10) {
12856     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12857     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12858         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12859         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12860     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12861         << ("0xA ^ " + RHSStr) << SuggestXor;
12862   }
12863 }
12864 
12865 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12866                                           SourceLocation Loc) {
12867   // Ensure that either both operands are of the same vector type, or
12868   // one operand is of a vector type and the other is of its element type.
12869   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12870                                        /*AllowBothBool*/ true,
12871                                        /*AllowBoolConversions*/ false,
12872                                        /*AllowBooleanOperation*/ false,
12873                                        /*ReportInvalid*/ false);
12874   if (vType.isNull())
12875     return InvalidOperands(Loc, LHS, RHS);
12876   if (getLangOpts().OpenCL &&
12877       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12878       vType->hasFloatingRepresentation())
12879     return InvalidOperands(Loc, LHS, RHS);
12880   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12881   //        usage of the logical operators && and || with vectors in C. This
12882   //        check could be notionally dropped.
12883   if (!getLangOpts().CPlusPlus &&
12884       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12885     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12886 
12887   return GetSignedVectorType(LHS.get()->getType());
12888 }
12889 
12890 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12891                                               SourceLocation Loc,
12892                                               bool IsCompAssign) {
12893   if (!IsCompAssign) {
12894     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12895     if (LHS.isInvalid())
12896       return QualType();
12897   }
12898   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12899   if (RHS.isInvalid())
12900     return QualType();
12901 
12902   // For conversion purposes, we ignore any qualifiers.
12903   // For example, "const float" and "float" are equivalent.
12904   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12905   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12906 
12907   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12908   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12909   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12910 
12911   if (Context.hasSameType(LHSType, RHSType))
12912     return LHSType;
12913 
12914   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12915   // case we have to return InvalidOperands.
12916   ExprResult OriginalLHS = LHS;
12917   ExprResult OriginalRHS = RHS;
12918   if (LHSMatType && !RHSMatType) {
12919     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12920     if (!RHS.isInvalid())
12921       return LHSType;
12922 
12923     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12924   }
12925 
12926   if (!LHSMatType && RHSMatType) {
12927     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12928     if (!LHS.isInvalid())
12929       return RHSType;
12930     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12931   }
12932 
12933   return InvalidOperands(Loc, LHS, RHS);
12934 }
12935 
12936 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12937                                            SourceLocation Loc,
12938                                            bool IsCompAssign) {
12939   if (!IsCompAssign) {
12940     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12941     if (LHS.isInvalid())
12942       return QualType();
12943   }
12944   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12945   if (RHS.isInvalid())
12946     return QualType();
12947 
12948   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12949   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12950   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12951 
12952   if (LHSMatType && RHSMatType) {
12953     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12954       return InvalidOperands(Loc, LHS, RHS);
12955 
12956     if (!Context.hasSameType(LHSMatType->getElementType(),
12957                              RHSMatType->getElementType()))
12958       return InvalidOperands(Loc, LHS, RHS);
12959 
12960     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12961                                          LHSMatType->getNumRows(),
12962                                          RHSMatType->getNumColumns());
12963   }
12964   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12965 }
12966 
12967 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
12968   switch (Opc) {
12969   default:
12970     return false;
12971   case BO_And:
12972   case BO_AndAssign:
12973   case BO_Or:
12974   case BO_OrAssign:
12975   case BO_Xor:
12976   case BO_XorAssign:
12977     return true;
12978   }
12979 }
12980 
12981 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12982                                            SourceLocation Loc,
12983                                            BinaryOperatorKind Opc) {
12984   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12985 
12986   bool IsCompAssign =
12987       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12988 
12989   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12990 
12991   if (LHS.get()->getType()->isVectorType() ||
12992       RHS.get()->getType()->isVectorType()) {
12993     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12994         RHS.get()->getType()->hasIntegerRepresentation())
12995       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12996                                  /*AllowBothBool*/ true,
12997                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
12998                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
12999                                  /*ReportInvalid*/ true);
13000     return InvalidOperands(Loc, LHS, RHS);
13001   }
13002 
13003   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13004       RHS.get()->getType()->isVLSTBuiltinType()) {
13005     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13006         RHS.get()->getType()->hasIntegerRepresentation())
13007       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13008                                          ACK_BitwiseOp);
13009     return InvalidOperands(Loc, LHS, RHS);
13010   }
13011 
13012   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13013       RHS.get()->getType()->isVLSTBuiltinType()) {
13014     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13015         RHS.get()->getType()->hasIntegerRepresentation())
13016       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13017                                          ACK_BitwiseOp);
13018     return InvalidOperands(Loc, LHS, RHS);
13019   }
13020 
13021   if (Opc == BO_And)
13022     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13023 
13024   if (LHS.get()->getType()->hasFloatingRepresentation() ||
13025       RHS.get()->getType()->hasFloatingRepresentation())
13026     return InvalidOperands(Loc, LHS, RHS);
13027 
13028   ExprResult LHSResult = LHS, RHSResult = RHS;
13029   QualType compType = UsualArithmeticConversions(
13030       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13031   if (LHSResult.isInvalid() || RHSResult.isInvalid())
13032     return QualType();
13033   LHS = LHSResult.get();
13034   RHS = RHSResult.get();
13035 
13036   if (Opc == BO_Xor)
13037     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13038 
13039   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13040     return compType;
13041   return InvalidOperands(Loc, LHS, RHS);
13042 }
13043 
13044 // C99 6.5.[13,14]
13045 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13046                                            SourceLocation Loc,
13047                                            BinaryOperatorKind Opc) {
13048   // Check vector operands differently.
13049   if (LHS.get()->getType()->isVectorType() ||
13050       RHS.get()->getType()->isVectorType())
13051     return CheckVectorLogicalOperands(LHS, RHS, Loc);
13052 
13053   bool EnumConstantInBoolContext = false;
13054   for (const ExprResult &HS : {LHS, RHS}) {
13055     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13056       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13057       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13058         EnumConstantInBoolContext = true;
13059     }
13060   }
13061 
13062   if (EnumConstantInBoolContext)
13063     Diag(Loc, diag::warn_enum_constant_in_bool_context);
13064 
13065   // Diagnose cases where the user write a logical and/or but probably meant a
13066   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13067   // is a constant.
13068   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13069       !LHS.get()->getType()->isBooleanType() &&
13070       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13071       // Don't warn in macros or template instantiations.
13072       !Loc.isMacroID() && !inTemplateInstantiation()) {
13073     // If the RHS can be constant folded, and if it constant folds to something
13074     // that isn't 0 or 1 (which indicate a potential logical operation that
13075     // happened to fold to true/false) then warn.
13076     // Parens on the RHS are ignored.
13077     Expr::EvalResult EVResult;
13078     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13079       llvm::APSInt Result = EVResult.Val.getInt();
13080       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13081            !RHS.get()->getExprLoc().isMacroID()) ||
13082           (Result != 0 && Result != 1)) {
13083         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13084             << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13085         // Suggest replacing the logical operator with the bitwise version
13086         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13087             << (Opc == BO_LAnd ? "&" : "|")
13088             << FixItHint::CreateReplacement(
13089                    SourceRange(Loc, getLocForEndOfToken(Loc)),
13090                    Opc == BO_LAnd ? "&" : "|");
13091         if (Opc == BO_LAnd)
13092           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13093           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13094               << FixItHint::CreateRemoval(
13095                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13096                                  RHS.get()->getEndLoc()));
13097       }
13098     }
13099   }
13100 
13101   if (!Context.getLangOpts().CPlusPlus) {
13102     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13103     // not operate on the built-in scalar and vector float types.
13104     if (Context.getLangOpts().OpenCL &&
13105         Context.getLangOpts().OpenCLVersion < 120) {
13106       if (LHS.get()->getType()->isFloatingType() ||
13107           RHS.get()->getType()->isFloatingType())
13108         return InvalidOperands(Loc, LHS, RHS);
13109     }
13110 
13111     LHS = UsualUnaryConversions(LHS.get());
13112     if (LHS.isInvalid())
13113       return QualType();
13114 
13115     RHS = UsualUnaryConversions(RHS.get());
13116     if (RHS.isInvalid())
13117       return QualType();
13118 
13119     if (!LHS.get()->getType()->isScalarType() ||
13120         !RHS.get()->getType()->isScalarType())
13121       return InvalidOperands(Loc, LHS, RHS);
13122 
13123     return Context.IntTy;
13124   }
13125 
13126   // The following is safe because we only use this method for
13127   // non-overloadable operands.
13128 
13129   // C++ [expr.log.and]p1
13130   // C++ [expr.log.or]p1
13131   // The operands are both contextually converted to type bool.
13132   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13133   if (LHSRes.isInvalid())
13134     return InvalidOperands(Loc, LHS, RHS);
13135   LHS = LHSRes;
13136 
13137   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13138   if (RHSRes.isInvalid())
13139     return InvalidOperands(Loc, LHS, RHS);
13140   RHS = RHSRes;
13141 
13142   // C++ [expr.log.and]p2
13143   // C++ [expr.log.or]p2
13144   // The result is a bool.
13145   return Context.BoolTy;
13146 }
13147 
13148 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13149   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13150   if (!ME) return false;
13151   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13152   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13153       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13154   if (!Base) return false;
13155   return Base->getMethodDecl() != nullptr;
13156 }
13157 
13158 /// Is the given expression (which must be 'const') a reference to a
13159 /// variable which was originally non-const, but which has become
13160 /// 'const' due to being captured within a block?
13161 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13162 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13163   assert(E->isLValue() && E->getType().isConstQualified());
13164   E = E->IgnoreParens();
13165 
13166   // Must be a reference to a declaration from an enclosing scope.
13167   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13168   if (!DRE) return NCCK_None;
13169   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13170 
13171   // The declaration must be a variable which is not declared 'const'.
13172   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13173   if (!var) return NCCK_None;
13174   if (var->getType().isConstQualified()) return NCCK_None;
13175   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13176 
13177   // Decide whether the first capture was for a block or a lambda.
13178   DeclContext *DC = S.CurContext, *Prev = nullptr;
13179   // Decide whether the first capture was for a block or a lambda.
13180   while (DC) {
13181     // For init-capture, it is possible that the variable belongs to the
13182     // template pattern of the current context.
13183     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13184       if (var->isInitCapture() &&
13185           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13186         break;
13187     if (DC == var->getDeclContext())
13188       break;
13189     Prev = DC;
13190     DC = DC->getParent();
13191   }
13192   // Unless we have an init-capture, we've gone one step too far.
13193   if (!var->isInitCapture())
13194     DC = Prev;
13195   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13196 }
13197 
13198 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13199   Ty = Ty.getNonReferenceType();
13200   if (IsDereference && Ty->isPointerType())
13201     Ty = Ty->getPointeeType();
13202   return !Ty.isConstQualified();
13203 }
13204 
13205 // Update err_typecheck_assign_const and note_typecheck_assign_const
13206 // when this enum is changed.
13207 enum {
13208   ConstFunction,
13209   ConstVariable,
13210   ConstMember,
13211   ConstMethod,
13212   NestedConstMember,
13213   ConstUnknown,  // Keep as last element
13214 };
13215 
13216 /// Emit the "read-only variable not assignable" error and print notes to give
13217 /// more information about why the variable is not assignable, such as pointing
13218 /// to the declaration of a const variable, showing that a method is const, or
13219 /// that the function is returning a const reference.
13220 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13221                                     SourceLocation Loc) {
13222   SourceRange ExprRange = E->getSourceRange();
13223 
13224   // Only emit one error on the first const found.  All other consts will emit
13225   // a note to the error.
13226   bool DiagnosticEmitted = false;
13227 
13228   // Track if the current expression is the result of a dereference, and if the
13229   // next checked expression is the result of a dereference.
13230   bool IsDereference = false;
13231   bool NextIsDereference = false;
13232 
13233   // Loop to process MemberExpr chains.
13234   while (true) {
13235     IsDereference = NextIsDereference;
13236 
13237     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13238     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13239       NextIsDereference = ME->isArrow();
13240       const ValueDecl *VD = ME->getMemberDecl();
13241       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13242         // Mutable fields can be modified even if the class is const.
13243         if (Field->isMutable()) {
13244           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13245           break;
13246         }
13247 
13248         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13249           if (!DiagnosticEmitted) {
13250             S.Diag(Loc, diag::err_typecheck_assign_const)
13251                 << ExprRange << ConstMember << false /*static*/ << Field
13252                 << Field->getType();
13253             DiagnosticEmitted = true;
13254           }
13255           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13256               << ConstMember << false /*static*/ << Field << Field->getType()
13257               << Field->getSourceRange();
13258         }
13259         E = ME->getBase();
13260         continue;
13261       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13262         if (VDecl->getType().isConstQualified()) {
13263           if (!DiagnosticEmitted) {
13264             S.Diag(Loc, diag::err_typecheck_assign_const)
13265                 << ExprRange << ConstMember << true /*static*/ << VDecl
13266                 << VDecl->getType();
13267             DiagnosticEmitted = true;
13268           }
13269           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13270               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13271               << VDecl->getSourceRange();
13272         }
13273         // Static fields do not inherit constness from parents.
13274         break;
13275       }
13276       break; // End MemberExpr
13277     } else if (const ArraySubscriptExpr *ASE =
13278                    dyn_cast<ArraySubscriptExpr>(E)) {
13279       E = ASE->getBase()->IgnoreParenImpCasts();
13280       continue;
13281     } else if (const ExtVectorElementExpr *EVE =
13282                    dyn_cast<ExtVectorElementExpr>(E)) {
13283       E = EVE->getBase()->IgnoreParenImpCasts();
13284       continue;
13285     }
13286     break;
13287   }
13288 
13289   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13290     // Function calls
13291     const FunctionDecl *FD = CE->getDirectCallee();
13292     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13293       if (!DiagnosticEmitted) {
13294         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13295                                                       << ConstFunction << FD;
13296         DiagnosticEmitted = true;
13297       }
13298       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13299              diag::note_typecheck_assign_const)
13300           << ConstFunction << FD << FD->getReturnType()
13301           << FD->getReturnTypeSourceRange();
13302     }
13303   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13304     // Point to variable declaration.
13305     if (const ValueDecl *VD = DRE->getDecl()) {
13306       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13307         if (!DiagnosticEmitted) {
13308           S.Diag(Loc, diag::err_typecheck_assign_const)
13309               << ExprRange << ConstVariable << VD << VD->getType();
13310           DiagnosticEmitted = true;
13311         }
13312         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13313             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13314       }
13315     }
13316   } else if (isa<CXXThisExpr>(E)) {
13317     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13318       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13319         if (MD->isConst()) {
13320           if (!DiagnosticEmitted) {
13321             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13322                                                           << ConstMethod << MD;
13323             DiagnosticEmitted = true;
13324           }
13325           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13326               << ConstMethod << MD << MD->getSourceRange();
13327         }
13328       }
13329     }
13330   }
13331 
13332   if (DiagnosticEmitted)
13333     return;
13334 
13335   // Can't determine a more specific message, so display the generic error.
13336   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13337 }
13338 
13339 enum OriginalExprKind {
13340   OEK_Variable,
13341   OEK_Member,
13342   OEK_LValue
13343 };
13344 
13345 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13346                                          const RecordType *Ty,
13347                                          SourceLocation Loc, SourceRange Range,
13348                                          OriginalExprKind OEK,
13349                                          bool &DiagnosticEmitted) {
13350   std::vector<const RecordType *> RecordTypeList;
13351   RecordTypeList.push_back(Ty);
13352   unsigned NextToCheckIndex = 0;
13353   // We walk the record hierarchy breadth-first to ensure that we print
13354   // diagnostics in field nesting order.
13355   while (RecordTypeList.size() > NextToCheckIndex) {
13356     bool IsNested = NextToCheckIndex > 0;
13357     for (const FieldDecl *Field :
13358          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13359       // First, check every field for constness.
13360       QualType FieldTy = Field->getType();
13361       if (FieldTy.isConstQualified()) {
13362         if (!DiagnosticEmitted) {
13363           S.Diag(Loc, diag::err_typecheck_assign_const)
13364               << Range << NestedConstMember << OEK << VD
13365               << IsNested << Field;
13366           DiagnosticEmitted = true;
13367         }
13368         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13369             << NestedConstMember << IsNested << Field
13370             << FieldTy << Field->getSourceRange();
13371       }
13372 
13373       // Then we append it to the list to check next in order.
13374       FieldTy = FieldTy.getCanonicalType();
13375       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13376         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13377           RecordTypeList.push_back(FieldRecTy);
13378       }
13379     }
13380     ++NextToCheckIndex;
13381   }
13382 }
13383 
13384 /// Emit an error for the case where a record we are trying to assign to has a
13385 /// const-qualified field somewhere in its hierarchy.
13386 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13387                                          SourceLocation Loc) {
13388   QualType Ty = E->getType();
13389   assert(Ty->isRecordType() && "lvalue was not record?");
13390   SourceRange Range = E->getSourceRange();
13391   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13392   bool DiagEmitted = false;
13393 
13394   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13395     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13396             Range, OEK_Member, DiagEmitted);
13397   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13398     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13399             Range, OEK_Variable, DiagEmitted);
13400   else
13401     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13402             Range, OEK_LValue, DiagEmitted);
13403   if (!DiagEmitted)
13404     DiagnoseConstAssignment(S, E, Loc);
13405 }
13406 
13407 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13408 /// emit an error and return true.  If so, return false.
13409 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13410   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13411 
13412   S.CheckShadowingDeclModification(E, Loc);
13413 
13414   SourceLocation OrigLoc = Loc;
13415   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13416                                                               &Loc);
13417   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13418     IsLV = Expr::MLV_InvalidMessageExpression;
13419   if (IsLV == Expr::MLV_Valid)
13420     return false;
13421 
13422   unsigned DiagID = 0;
13423   bool NeedType = false;
13424   switch (IsLV) { // C99 6.5.16p2
13425   case Expr::MLV_ConstQualified:
13426     // Use a specialized diagnostic when we're assigning to an object
13427     // from an enclosing function or block.
13428     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13429       if (NCCK == NCCK_Block)
13430         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13431       else
13432         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13433       break;
13434     }
13435 
13436     // In ARC, use some specialized diagnostics for occasions where we
13437     // infer 'const'.  These are always pseudo-strong variables.
13438     if (S.getLangOpts().ObjCAutoRefCount) {
13439       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13440       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13441         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13442 
13443         // Use the normal diagnostic if it's pseudo-__strong but the
13444         // user actually wrote 'const'.
13445         if (var->isARCPseudoStrong() &&
13446             (!var->getTypeSourceInfo() ||
13447              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13448           // There are three pseudo-strong cases:
13449           //  - self
13450           ObjCMethodDecl *method = S.getCurMethodDecl();
13451           if (method && var == method->getSelfDecl()) {
13452             DiagID = method->isClassMethod()
13453               ? diag::err_typecheck_arc_assign_self_class_method
13454               : diag::err_typecheck_arc_assign_self;
13455 
13456           //  - Objective-C externally_retained attribute.
13457           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13458                      isa<ParmVarDecl>(var)) {
13459             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13460 
13461           //  - fast enumeration variables
13462           } else {
13463             DiagID = diag::err_typecheck_arr_assign_enumeration;
13464           }
13465 
13466           SourceRange Assign;
13467           if (Loc != OrigLoc)
13468             Assign = SourceRange(OrigLoc, OrigLoc);
13469           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13470           // We need to preserve the AST regardless, so migration tool
13471           // can do its job.
13472           return false;
13473         }
13474       }
13475     }
13476 
13477     // If none of the special cases above are triggered, then this is a
13478     // simple const assignment.
13479     if (DiagID == 0) {
13480       DiagnoseConstAssignment(S, E, Loc);
13481       return true;
13482     }
13483 
13484     break;
13485   case Expr::MLV_ConstAddrSpace:
13486     DiagnoseConstAssignment(S, E, Loc);
13487     return true;
13488   case Expr::MLV_ConstQualifiedField:
13489     DiagnoseRecursiveConstFields(S, E, Loc);
13490     return true;
13491   case Expr::MLV_ArrayType:
13492   case Expr::MLV_ArrayTemporary:
13493     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13494     NeedType = true;
13495     break;
13496   case Expr::MLV_NotObjectType:
13497     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13498     NeedType = true;
13499     break;
13500   case Expr::MLV_LValueCast:
13501     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13502     break;
13503   case Expr::MLV_Valid:
13504     llvm_unreachable("did not take early return for MLV_Valid");
13505   case Expr::MLV_InvalidExpression:
13506   case Expr::MLV_MemberFunction:
13507   case Expr::MLV_ClassTemporary:
13508     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13509     break;
13510   case Expr::MLV_IncompleteType:
13511   case Expr::MLV_IncompleteVoidType:
13512     return S.RequireCompleteType(Loc, E->getType(),
13513              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13514   case Expr::MLV_DuplicateVectorComponents:
13515     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13516     break;
13517   case Expr::MLV_NoSetterProperty:
13518     llvm_unreachable("readonly properties should be processed differently");
13519   case Expr::MLV_InvalidMessageExpression:
13520     DiagID = diag::err_readonly_message_assignment;
13521     break;
13522   case Expr::MLV_SubObjCPropertySetting:
13523     DiagID = diag::err_no_subobject_property_setting;
13524     break;
13525   }
13526 
13527   SourceRange Assign;
13528   if (Loc != OrigLoc)
13529     Assign = SourceRange(OrigLoc, OrigLoc);
13530   if (NeedType)
13531     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13532   else
13533     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13534   return true;
13535 }
13536 
13537 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13538                                          SourceLocation Loc,
13539                                          Sema &Sema) {
13540   if (Sema.inTemplateInstantiation())
13541     return;
13542   if (Sema.isUnevaluatedContext())
13543     return;
13544   if (Loc.isInvalid() || Loc.isMacroID())
13545     return;
13546   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13547     return;
13548 
13549   // C / C++ fields
13550   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13551   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13552   if (ML && MR) {
13553     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13554       return;
13555     const ValueDecl *LHSDecl =
13556         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13557     const ValueDecl *RHSDecl =
13558         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13559     if (LHSDecl != RHSDecl)
13560       return;
13561     if (LHSDecl->getType().isVolatileQualified())
13562       return;
13563     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13564       if (RefTy->getPointeeType().isVolatileQualified())
13565         return;
13566 
13567     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13568   }
13569 
13570   // Objective-C instance variables
13571   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13572   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13573   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13574     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13575     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13576     if (RL && RR && RL->getDecl() == RR->getDecl())
13577       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13578   }
13579 }
13580 
13581 // C99 6.5.16.1
13582 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13583                                        SourceLocation Loc,
13584                                        QualType CompoundType) {
13585   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13586 
13587   // Verify that LHS is a modifiable lvalue, and emit error if not.
13588   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13589     return QualType();
13590 
13591   QualType LHSType = LHSExpr->getType();
13592   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13593                                              CompoundType;
13594   // OpenCL v1.2 s6.1.1.1 p2:
13595   // The half data type can only be used to declare a pointer to a buffer that
13596   // contains half values
13597   if (getLangOpts().OpenCL &&
13598       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13599       LHSType->isHalfType()) {
13600     Diag(Loc, diag::err_opencl_half_load_store) << 1
13601         << LHSType.getUnqualifiedType();
13602     return QualType();
13603   }
13604 
13605   AssignConvertType ConvTy;
13606   if (CompoundType.isNull()) {
13607     Expr *RHSCheck = RHS.get();
13608 
13609     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13610 
13611     QualType LHSTy(LHSType);
13612     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13613     if (RHS.isInvalid())
13614       return QualType();
13615     // Special case of NSObject attributes on c-style pointer types.
13616     if (ConvTy == IncompatiblePointer &&
13617         ((Context.isObjCNSObjectType(LHSType) &&
13618           RHSType->isObjCObjectPointerType()) ||
13619          (Context.isObjCNSObjectType(RHSType) &&
13620           LHSType->isObjCObjectPointerType())))
13621       ConvTy = Compatible;
13622 
13623     if (ConvTy == Compatible &&
13624         LHSType->isObjCObjectType())
13625         Diag(Loc, diag::err_objc_object_assignment)
13626           << LHSType;
13627 
13628     // If the RHS is a unary plus or minus, check to see if they = and + are
13629     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13630     // instead of "x += 4".
13631     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13632       RHSCheck = ICE->getSubExpr();
13633     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13634       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13635           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13636           // Only if the two operators are exactly adjacent.
13637           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13638           // And there is a space or other character before the subexpr of the
13639           // unary +/-.  We don't want to warn on "x=-1".
13640           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13641           UO->getSubExpr()->getBeginLoc().isFileID()) {
13642         Diag(Loc, diag::warn_not_compound_assign)
13643           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13644           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13645       }
13646     }
13647 
13648     if (ConvTy == Compatible) {
13649       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13650         // Warn about retain cycles where a block captures the LHS, but
13651         // not if the LHS is a simple variable into which the block is
13652         // being stored...unless that variable can be captured by reference!
13653         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13654         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13655         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13656           checkRetainCycles(LHSExpr, RHS.get());
13657       }
13658 
13659       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13660           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13661         // It is safe to assign a weak reference into a strong variable.
13662         // Although this code can still have problems:
13663         //   id x = self.weakProp;
13664         //   id y = self.weakProp;
13665         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13666         // paths through the function. This should be revisited if
13667         // -Wrepeated-use-of-weak is made flow-sensitive.
13668         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13669         // variable, which will be valid for the current autorelease scope.
13670         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13671                              RHS.get()->getBeginLoc()))
13672           getCurFunction()->markSafeWeakUse(RHS.get());
13673 
13674       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13675         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13676       }
13677     }
13678   } else {
13679     // Compound assignment "x += y"
13680     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13681   }
13682 
13683   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13684                                RHS.get(), AA_Assigning))
13685     return QualType();
13686 
13687   CheckForNullPointerDereference(*this, LHSExpr);
13688 
13689   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13690     if (CompoundType.isNull()) {
13691       // C++2a [expr.ass]p5:
13692       //   A simple-assignment whose left operand is of a volatile-qualified
13693       //   type is deprecated unless the assignment is either a discarded-value
13694       //   expression or an unevaluated operand
13695       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13696     } else {
13697       // C++2a [expr.ass]p6:
13698       //   [Compound-assignment] expressions are deprecated if E1 has
13699       //   volatile-qualified type
13700       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13701     }
13702   }
13703 
13704   // C11 6.5.16p3: The type of an assignment expression is the type of the
13705   // left operand would have after lvalue conversion.
13706   // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13707   // qualified type, the value has the unqualified version of the type of the
13708   // lvalue; additionally, if the lvalue has atomic type, the value has the
13709   // non-atomic version of the type of the lvalue.
13710   // C++ 5.17p1: the type of the assignment expression is that of its left
13711   // operand.
13712   return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13713 }
13714 
13715 // Only ignore explicit casts to void.
13716 static bool IgnoreCommaOperand(const Expr *E) {
13717   E = E->IgnoreParens();
13718 
13719   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13720     if (CE->getCastKind() == CK_ToVoid) {
13721       return true;
13722     }
13723 
13724     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13725     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13726         CE->getSubExpr()->getType()->isDependentType()) {
13727       return true;
13728     }
13729   }
13730 
13731   return false;
13732 }
13733 
13734 // Look for instances where it is likely the comma operator is confused with
13735 // another operator.  There is an explicit list of acceptable expressions for
13736 // the left hand side of the comma operator, otherwise emit a warning.
13737 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13738   // No warnings in macros
13739   if (Loc.isMacroID())
13740     return;
13741 
13742   // Don't warn in template instantiations.
13743   if (inTemplateInstantiation())
13744     return;
13745 
13746   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13747   // instead, skip more than needed, then call back into here with the
13748   // CommaVisitor in SemaStmt.cpp.
13749   // The listed locations are the initialization and increment portions
13750   // of a for loop.  The additional checks are on the condition of
13751   // if statements, do/while loops, and for loops.
13752   // Differences in scope flags for C89 mode requires the extra logic.
13753   const unsigned ForIncrementFlags =
13754       getLangOpts().C99 || getLangOpts().CPlusPlus
13755           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13756           : Scope::ContinueScope | Scope::BreakScope;
13757   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13758   const unsigned ScopeFlags = getCurScope()->getFlags();
13759   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13760       (ScopeFlags & ForInitFlags) == ForInitFlags)
13761     return;
13762 
13763   // If there are multiple comma operators used together, get the RHS of the
13764   // of the comma operator as the LHS.
13765   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13766     if (BO->getOpcode() != BO_Comma)
13767       break;
13768     LHS = BO->getRHS();
13769   }
13770 
13771   // Only allow some expressions on LHS to not warn.
13772   if (IgnoreCommaOperand(LHS))
13773     return;
13774 
13775   Diag(Loc, diag::warn_comma_operator);
13776   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13777       << LHS->getSourceRange()
13778       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13779                                     LangOpts.CPlusPlus ? "static_cast<void>("
13780                                                        : "(void)(")
13781       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13782                                     ")");
13783 }
13784 
13785 // C99 6.5.17
13786 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13787                                    SourceLocation Loc) {
13788   LHS = S.CheckPlaceholderExpr(LHS.get());
13789   RHS = S.CheckPlaceholderExpr(RHS.get());
13790   if (LHS.isInvalid() || RHS.isInvalid())
13791     return QualType();
13792 
13793   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13794   // operands, but not unary promotions.
13795   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13796 
13797   // So we treat the LHS as a ignored value, and in C++ we allow the
13798   // containing site to determine what should be done with the RHS.
13799   LHS = S.IgnoredValueConversions(LHS.get());
13800   if (LHS.isInvalid())
13801     return QualType();
13802 
13803   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13804 
13805   if (!S.getLangOpts().CPlusPlus) {
13806     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13807     if (RHS.isInvalid())
13808       return QualType();
13809     if (!RHS.get()->getType()->isVoidType())
13810       S.RequireCompleteType(Loc, RHS.get()->getType(),
13811                             diag::err_incomplete_type);
13812   }
13813 
13814   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13815     S.DiagnoseCommaOperator(LHS.get(), Loc);
13816 
13817   return RHS.get()->getType();
13818 }
13819 
13820 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13821 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13822 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13823                                                ExprValueKind &VK,
13824                                                ExprObjectKind &OK,
13825                                                SourceLocation OpLoc,
13826                                                bool IsInc, bool IsPrefix) {
13827   if (Op->isTypeDependent())
13828     return S.Context.DependentTy;
13829 
13830   QualType ResType = Op->getType();
13831   // Atomic types can be used for increment / decrement where the non-atomic
13832   // versions can, so ignore the _Atomic() specifier for the purpose of
13833   // checking.
13834   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13835     ResType = ResAtomicType->getValueType();
13836 
13837   assert(!ResType.isNull() && "no type for increment/decrement expression");
13838 
13839   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13840     // Decrement of bool is not allowed.
13841     if (!IsInc) {
13842       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13843       return QualType();
13844     }
13845     // Increment of bool sets it to true, but is deprecated.
13846     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13847                                               : diag::warn_increment_bool)
13848       << Op->getSourceRange();
13849   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13850     // Error on enum increments and decrements in C++ mode
13851     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13852     return QualType();
13853   } else if (ResType->isRealType()) {
13854     // OK!
13855   } else if (ResType->isPointerType()) {
13856     // C99 6.5.2.4p2, 6.5.6p2
13857     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13858       return QualType();
13859   } else if (ResType->isObjCObjectPointerType()) {
13860     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13861     // Otherwise, we just need a complete type.
13862     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13863         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13864       return QualType();
13865   } else if (ResType->isAnyComplexType()) {
13866     // C99 does not support ++/-- on complex types, we allow as an extension.
13867     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13868       << ResType << Op->getSourceRange();
13869   } else if (ResType->isPlaceholderType()) {
13870     ExprResult PR = S.CheckPlaceholderExpr(Op);
13871     if (PR.isInvalid()) return QualType();
13872     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13873                                           IsInc, IsPrefix);
13874   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13875     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13876   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13877              (ResType->castAs<VectorType>()->getVectorKind() !=
13878               VectorType::AltiVecBool)) {
13879     // The z vector extensions allow ++ and -- for non-bool vectors.
13880   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13881             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13882     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13883   } else {
13884     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13885       << ResType << int(IsInc) << Op->getSourceRange();
13886     return QualType();
13887   }
13888   // At this point, we know we have a real, complex or pointer type.
13889   // Now make sure the operand is a modifiable lvalue.
13890   if (CheckForModifiableLvalue(Op, OpLoc, S))
13891     return QualType();
13892   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13893     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13894     //   An operand with volatile-qualified type is deprecated
13895     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13896         << IsInc << ResType;
13897   }
13898   // In C++, a prefix increment is the same type as the operand. Otherwise
13899   // (in C or with postfix), the increment is the unqualified type of the
13900   // operand.
13901   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13902     VK = VK_LValue;
13903     OK = Op->getObjectKind();
13904     return ResType;
13905   } else {
13906     VK = VK_PRValue;
13907     return ResType.getUnqualifiedType();
13908   }
13909 }
13910 
13911 
13912 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13913 /// This routine allows us to typecheck complex/recursive expressions
13914 /// where the declaration is needed for type checking. We only need to
13915 /// handle cases when the expression references a function designator
13916 /// or is an lvalue. Here are some examples:
13917 ///  - &(x) => x
13918 ///  - &*****f => f for f a function designator.
13919 ///  - &s.xx => s
13920 ///  - &s.zz[1].yy -> s, if zz is an array
13921 ///  - *(x + 1) -> x, if x is an array
13922 ///  - &"123"[2] -> 0
13923 ///  - & __real__ x -> x
13924 ///
13925 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13926 /// members.
13927 static ValueDecl *getPrimaryDecl(Expr *E) {
13928   switch (E->getStmtClass()) {
13929   case Stmt::DeclRefExprClass:
13930     return cast<DeclRefExpr>(E)->getDecl();
13931   case Stmt::MemberExprClass:
13932     // If this is an arrow operator, the address is an offset from
13933     // the base's value, so the object the base refers to is
13934     // irrelevant.
13935     if (cast<MemberExpr>(E)->isArrow())
13936       return nullptr;
13937     // Otherwise, the expression refers to a part of the base
13938     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13939   case Stmt::ArraySubscriptExprClass: {
13940     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13941     // promotion of register arrays earlier.
13942     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13943     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13944       if (ICE->getSubExpr()->getType()->isArrayType())
13945         return getPrimaryDecl(ICE->getSubExpr());
13946     }
13947     return nullptr;
13948   }
13949   case Stmt::UnaryOperatorClass: {
13950     UnaryOperator *UO = cast<UnaryOperator>(E);
13951 
13952     switch(UO->getOpcode()) {
13953     case UO_Real:
13954     case UO_Imag:
13955     case UO_Extension:
13956       return getPrimaryDecl(UO->getSubExpr());
13957     default:
13958       return nullptr;
13959     }
13960   }
13961   case Stmt::ParenExprClass:
13962     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13963   case Stmt::ImplicitCastExprClass:
13964     // If the result of an implicit cast is an l-value, we care about
13965     // the sub-expression; otherwise, the result here doesn't matter.
13966     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13967   case Stmt::CXXUuidofExprClass:
13968     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13969   default:
13970     return nullptr;
13971   }
13972 }
13973 
13974 namespace {
13975 enum {
13976   AO_Bit_Field = 0,
13977   AO_Vector_Element = 1,
13978   AO_Property_Expansion = 2,
13979   AO_Register_Variable = 3,
13980   AO_Matrix_Element = 4,
13981   AO_No_Error = 5
13982 };
13983 }
13984 /// Diagnose invalid operand for address of operations.
13985 ///
13986 /// \param Type The type of operand which cannot have its address taken.
13987 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13988                                          Expr *E, unsigned Type) {
13989   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13990 }
13991 
13992 /// CheckAddressOfOperand - The operand of & must be either a function
13993 /// designator or an lvalue designating an object. If it is an lvalue, the
13994 /// object cannot be declared with storage class register or be a bit field.
13995 /// Note: The usual conversions are *not* applied to the operand of the &
13996 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13997 /// In C++, the operand might be an overloaded function name, in which case
13998 /// we allow the '&' but retain the overloaded-function type.
13999 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14000   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14001     if (PTy->getKind() == BuiltinType::Overload) {
14002       Expr *E = OrigOp.get()->IgnoreParens();
14003       if (!isa<OverloadExpr>(E)) {
14004         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14005         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14006           << OrigOp.get()->getSourceRange();
14007         return QualType();
14008       }
14009 
14010       OverloadExpr *Ovl = cast<OverloadExpr>(E);
14011       if (isa<UnresolvedMemberExpr>(Ovl))
14012         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14013           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14014             << OrigOp.get()->getSourceRange();
14015           return QualType();
14016         }
14017 
14018       return Context.OverloadTy;
14019     }
14020 
14021     if (PTy->getKind() == BuiltinType::UnknownAny)
14022       return Context.UnknownAnyTy;
14023 
14024     if (PTy->getKind() == BuiltinType::BoundMember) {
14025       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14026         << OrigOp.get()->getSourceRange();
14027       return QualType();
14028     }
14029 
14030     OrigOp = CheckPlaceholderExpr(OrigOp.get());
14031     if (OrigOp.isInvalid()) return QualType();
14032   }
14033 
14034   if (OrigOp.get()->isTypeDependent())
14035     return Context.DependentTy;
14036 
14037   assert(!OrigOp.get()->hasPlaceholderType());
14038 
14039   // Make sure to ignore parentheses in subsequent checks
14040   Expr *op = OrigOp.get()->IgnoreParens();
14041 
14042   // In OpenCL captures for blocks called as lambda functions
14043   // are located in the private address space. Blocks used in
14044   // enqueue_kernel can be located in a different address space
14045   // depending on a vendor implementation. Thus preventing
14046   // taking an address of the capture to avoid invalid AS casts.
14047   if (LangOpts.OpenCL) {
14048     auto* VarRef = dyn_cast<DeclRefExpr>(op);
14049     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14050       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14051       return QualType();
14052     }
14053   }
14054 
14055   if (getLangOpts().C99) {
14056     // Implement C99-only parts of addressof rules.
14057     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14058       if (uOp->getOpcode() == UO_Deref)
14059         // Per C99 6.5.3.2, the address of a deref always returns a valid result
14060         // (assuming the deref expression is valid).
14061         return uOp->getSubExpr()->getType();
14062     }
14063     // Technically, there should be a check for array subscript
14064     // expressions here, but the result of one is always an lvalue anyway.
14065   }
14066   ValueDecl *dcl = getPrimaryDecl(op);
14067 
14068   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14069     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14070                                            op->getBeginLoc()))
14071       return QualType();
14072 
14073   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14074   unsigned AddressOfError = AO_No_Error;
14075 
14076   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14077     bool sfinae = (bool)isSFINAEContext();
14078     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14079                                   : diag::ext_typecheck_addrof_temporary)
14080       << op->getType() << op->getSourceRange();
14081     if (sfinae)
14082       return QualType();
14083     // Materialize the temporary as an lvalue so that we can take its address.
14084     OrigOp = op =
14085         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14086   } else if (isa<ObjCSelectorExpr>(op)) {
14087     return Context.getPointerType(op->getType());
14088   } else if (lval == Expr::LV_MemberFunction) {
14089     // If it's an instance method, make a member pointer.
14090     // The expression must have exactly the form &A::foo.
14091 
14092     // If the underlying expression isn't a decl ref, give up.
14093     if (!isa<DeclRefExpr>(op)) {
14094       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14095         << OrigOp.get()->getSourceRange();
14096       return QualType();
14097     }
14098     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14099     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14100 
14101     // The id-expression was parenthesized.
14102     if (OrigOp.get() != DRE) {
14103       Diag(OpLoc, diag::err_parens_pointer_member_function)
14104         << OrigOp.get()->getSourceRange();
14105 
14106     // The method was named without a qualifier.
14107     } else if (!DRE->getQualifier()) {
14108       if (MD->getParent()->getName().empty())
14109         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14110           << op->getSourceRange();
14111       else {
14112         SmallString<32> Str;
14113         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14114         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14115           << op->getSourceRange()
14116           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14117       }
14118     }
14119 
14120     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14121     if (isa<CXXDestructorDecl>(MD))
14122       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14123 
14124     QualType MPTy = Context.getMemberPointerType(
14125         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14126     // Under the MS ABI, lock down the inheritance model now.
14127     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14128       (void)isCompleteType(OpLoc, MPTy);
14129     return MPTy;
14130   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14131     // C99 6.5.3.2p1
14132     // The operand must be either an l-value or a function designator
14133     if (!op->getType()->isFunctionType()) {
14134       // Use a special diagnostic for loads from property references.
14135       if (isa<PseudoObjectExpr>(op)) {
14136         AddressOfError = AO_Property_Expansion;
14137       } else {
14138         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14139           << op->getType() << op->getSourceRange();
14140         return QualType();
14141       }
14142     }
14143   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14144     // The operand cannot be a bit-field
14145     AddressOfError = AO_Bit_Field;
14146   } else if (op->getObjectKind() == OK_VectorComponent) {
14147     // The operand cannot be an element of a vector
14148     AddressOfError = AO_Vector_Element;
14149   } else if (op->getObjectKind() == OK_MatrixComponent) {
14150     // The operand cannot be an element of a matrix.
14151     AddressOfError = AO_Matrix_Element;
14152   } else if (dcl) { // C99 6.5.3.2p1
14153     // We have an lvalue with a decl. Make sure the decl is not declared
14154     // with the register storage-class specifier.
14155     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14156       // in C++ it is not error to take address of a register
14157       // variable (c++03 7.1.1P3)
14158       if (vd->getStorageClass() == SC_Register &&
14159           !getLangOpts().CPlusPlus) {
14160         AddressOfError = AO_Register_Variable;
14161       }
14162     } else if (isa<MSPropertyDecl>(dcl)) {
14163       AddressOfError = AO_Property_Expansion;
14164     } else if (isa<FunctionTemplateDecl>(dcl)) {
14165       return Context.OverloadTy;
14166     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14167       // Okay: we can take the address of a field.
14168       // Could be a pointer to member, though, if there is an explicit
14169       // scope qualifier for the class.
14170       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14171         DeclContext *Ctx = dcl->getDeclContext();
14172         if (Ctx && Ctx->isRecord()) {
14173           if (dcl->getType()->isReferenceType()) {
14174             Diag(OpLoc,
14175                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14176               << dcl->getDeclName() << dcl->getType();
14177             return QualType();
14178           }
14179 
14180           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14181             Ctx = Ctx->getParent();
14182 
14183           QualType MPTy = Context.getMemberPointerType(
14184               op->getType(),
14185               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14186           // Under the MS ABI, lock down the inheritance model now.
14187           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14188             (void)isCompleteType(OpLoc, MPTy);
14189           return MPTy;
14190         }
14191       }
14192     } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14193                     MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14194       llvm_unreachable("Unknown/unexpected decl type");
14195   }
14196 
14197   if (AddressOfError != AO_No_Error) {
14198     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14199     return QualType();
14200   }
14201 
14202   if (lval == Expr::LV_IncompleteVoidType) {
14203     // Taking the address of a void variable is technically illegal, but we
14204     // allow it in cases which are otherwise valid.
14205     // Example: "extern void x; void* y = &x;".
14206     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14207   }
14208 
14209   // If the operand has type "type", the result has type "pointer to type".
14210   if (op->getType()->isObjCObjectType())
14211     return Context.getObjCObjectPointerType(op->getType());
14212 
14213   CheckAddressOfPackedMember(op);
14214 
14215   return Context.getPointerType(op->getType());
14216 }
14217 
14218 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14219   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14220   if (!DRE)
14221     return;
14222   const Decl *D = DRE->getDecl();
14223   if (!D)
14224     return;
14225   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14226   if (!Param)
14227     return;
14228   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14229     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14230       return;
14231   if (FunctionScopeInfo *FD = S.getCurFunction())
14232     if (!FD->ModifiedNonNullParams.count(Param))
14233       FD->ModifiedNonNullParams.insert(Param);
14234 }
14235 
14236 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14237 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14238                                         SourceLocation OpLoc) {
14239   if (Op->isTypeDependent())
14240     return S.Context.DependentTy;
14241 
14242   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14243   if (ConvResult.isInvalid())
14244     return QualType();
14245   Op = ConvResult.get();
14246   QualType OpTy = Op->getType();
14247   QualType Result;
14248 
14249   if (isa<CXXReinterpretCastExpr>(Op)) {
14250     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14251     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14252                                      Op->getSourceRange());
14253   }
14254 
14255   if (const PointerType *PT = OpTy->getAs<PointerType>())
14256   {
14257     Result = PT->getPointeeType();
14258   }
14259   else if (const ObjCObjectPointerType *OPT =
14260              OpTy->getAs<ObjCObjectPointerType>())
14261     Result = OPT->getPointeeType();
14262   else {
14263     ExprResult PR = S.CheckPlaceholderExpr(Op);
14264     if (PR.isInvalid()) return QualType();
14265     if (PR.get() != Op)
14266       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14267   }
14268 
14269   if (Result.isNull()) {
14270     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14271       << OpTy << Op->getSourceRange();
14272     return QualType();
14273   }
14274 
14275   // Note that per both C89 and C99, indirection is always legal, even if Result
14276   // is an incomplete type or void.  It would be possible to warn about
14277   // dereferencing a void pointer, but it's completely well-defined, and such a
14278   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14279   // for pointers to 'void' but is fine for any other pointer type:
14280   //
14281   // C++ [expr.unary.op]p1:
14282   //   [...] the expression to which [the unary * operator] is applied shall
14283   //   be a pointer to an object type, or a pointer to a function type
14284   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14285     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14286       << OpTy << Op->getSourceRange();
14287 
14288   // Dereferences are usually l-values...
14289   VK = VK_LValue;
14290 
14291   // ...except that certain expressions are never l-values in C.
14292   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14293     VK = VK_PRValue;
14294 
14295   return Result;
14296 }
14297 
14298 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14299   BinaryOperatorKind Opc;
14300   switch (Kind) {
14301   default: llvm_unreachable("Unknown binop!");
14302   case tok::periodstar:           Opc = BO_PtrMemD; break;
14303   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14304   case tok::star:                 Opc = BO_Mul; break;
14305   case tok::slash:                Opc = BO_Div; break;
14306   case tok::percent:              Opc = BO_Rem; break;
14307   case tok::plus:                 Opc = BO_Add; break;
14308   case tok::minus:                Opc = BO_Sub; break;
14309   case tok::lessless:             Opc = BO_Shl; break;
14310   case tok::greatergreater:       Opc = BO_Shr; break;
14311   case tok::lessequal:            Opc = BO_LE; break;
14312   case tok::less:                 Opc = BO_LT; break;
14313   case tok::greaterequal:         Opc = BO_GE; break;
14314   case tok::greater:              Opc = BO_GT; break;
14315   case tok::exclaimequal:         Opc = BO_NE; break;
14316   case tok::equalequal:           Opc = BO_EQ; break;
14317   case tok::spaceship:            Opc = BO_Cmp; break;
14318   case tok::amp:                  Opc = BO_And; break;
14319   case tok::caret:                Opc = BO_Xor; break;
14320   case tok::pipe:                 Opc = BO_Or; break;
14321   case tok::ampamp:               Opc = BO_LAnd; break;
14322   case tok::pipepipe:             Opc = BO_LOr; break;
14323   case tok::equal:                Opc = BO_Assign; break;
14324   case tok::starequal:            Opc = BO_MulAssign; break;
14325   case tok::slashequal:           Opc = BO_DivAssign; break;
14326   case tok::percentequal:         Opc = BO_RemAssign; break;
14327   case tok::plusequal:            Opc = BO_AddAssign; break;
14328   case tok::minusequal:           Opc = BO_SubAssign; break;
14329   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14330   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14331   case tok::ampequal:             Opc = BO_AndAssign; break;
14332   case tok::caretequal:           Opc = BO_XorAssign; break;
14333   case tok::pipeequal:            Opc = BO_OrAssign; break;
14334   case tok::comma:                Opc = BO_Comma; break;
14335   }
14336   return Opc;
14337 }
14338 
14339 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14340   tok::TokenKind Kind) {
14341   UnaryOperatorKind Opc;
14342   switch (Kind) {
14343   default: llvm_unreachable("Unknown unary op!");
14344   case tok::plusplus:     Opc = UO_PreInc; break;
14345   case tok::minusminus:   Opc = UO_PreDec; break;
14346   case tok::amp:          Opc = UO_AddrOf; break;
14347   case tok::star:         Opc = UO_Deref; break;
14348   case tok::plus:         Opc = UO_Plus; break;
14349   case tok::minus:        Opc = UO_Minus; break;
14350   case tok::tilde:        Opc = UO_Not; break;
14351   case tok::exclaim:      Opc = UO_LNot; break;
14352   case tok::kw___real:    Opc = UO_Real; break;
14353   case tok::kw___imag:    Opc = UO_Imag; break;
14354   case tok::kw___extension__: Opc = UO_Extension; break;
14355   }
14356   return Opc;
14357 }
14358 
14359 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14360 /// This warning suppressed in the event of macro expansions.
14361 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14362                                    SourceLocation OpLoc, bool IsBuiltin) {
14363   if (S.inTemplateInstantiation())
14364     return;
14365   if (S.isUnevaluatedContext())
14366     return;
14367   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14368     return;
14369   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14370   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14371   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14372   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14373   if (!LHSDeclRef || !RHSDeclRef ||
14374       LHSDeclRef->getLocation().isMacroID() ||
14375       RHSDeclRef->getLocation().isMacroID())
14376     return;
14377   const ValueDecl *LHSDecl =
14378     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14379   const ValueDecl *RHSDecl =
14380     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14381   if (LHSDecl != RHSDecl)
14382     return;
14383   if (LHSDecl->getType().isVolatileQualified())
14384     return;
14385   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14386     if (RefTy->getPointeeType().isVolatileQualified())
14387       return;
14388 
14389   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14390                           : diag::warn_self_assignment_overloaded)
14391       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14392       << RHSExpr->getSourceRange();
14393 }
14394 
14395 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14396 /// is usually indicative of introspection within the Objective-C pointer.
14397 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14398                                           SourceLocation OpLoc) {
14399   if (!S.getLangOpts().ObjC)
14400     return;
14401 
14402   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14403   const Expr *LHS = L.get();
14404   const Expr *RHS = R.get();
14405 
14406   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14407     ObjCPointerExpr = LHS;
14408     OtherExpr = RHS;
14409   }
14410   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14411     ObjCPointerExpr = RHS;
14412     OtherExpr = LHS;
14413   }
14414 
14415   // This warning is deliberately made very specific to reduce false
14416   // positives with logic that uses '&' for hashing.  This logic mainly
14417   // looks for code trying to introspect into tagged pointers, which
14418   // code should generally never do.
14419   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14420     unsigned Diag = diag::warn_objc_pointer_masking;
14421     // Determine if we are introspecting the result of performSelectorXXX.
14422     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14423     // Special case messages to -performSelector and friends, which
14424     // can return non-pointer values boxed in a pointer value.
14425     // Some clients may wish to silence warnings in this subcase.
14426     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14427       Selector S = ME->getSelector();
14428       StringRef SelArg0 = S.getNameForSlot(0);
14429       if (SelArg0.startswith("performSelector"))
14430         Diag = diag::warn_objc_pointer_masking_performSelector;
14431     }
14432 
14433     S.Diag(OpLoc, Diag)
14434       << ObjCPointerExpr->getSourceRange();
14435   }
14436 }
14437 
14438 static NamedDecl *getDeclFromExpr(Expr *E) {
14439   if (!E)
14440     return nullptr;
14441   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14442     return DRE->getDecl();
14443   if (auto *ME = dyn_cast<MemberExpr>(E))
14444     return ME->getMemberDecl();
14445   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14446     return IRE->getDecl();
14447   return nullptr;
14448 }
14449 
14450 // This helper function promotes a binary operator's operands (which are of a
14451 // half vector type) to a vector of floats and then truncates the result to
14452 // a vector of either half or short.
14453 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14454                                       BinaryOperatorKind Opc, QualType ResultTy,
14455                                       ExprValueKind VK, ExprObjectKind OK,
14456                                       bool IsCompAssign, SourceLocation OpLoc,
14457                                       FPOptionsOverride FPFeatures) {
14458   auto &Context = S.getASTContext();
14459   assert((isVector(ResultTy, Context.HalfTy) ||
14460           isVector(ResultTy, Context.ShortTy)) &&
14461          "Result must be a vector of half or short");
14462   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14463          isVector(RHS.get()->getType(), Context.HalfTy) &&
14464          "both operands expected to be a half vector");
14465 
14466   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14467   QualType BinOpResTy = RHS.get()->getType();
14468 
14469   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14470   // change BinOpResTy to a vector of ints.
14471   if (isVector(ResultTy, Context.ShortTy))
14472     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14473 
14474   if (IsCompAssign)
14475     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14476                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14477                                           BinOpResTy, BinOpResTy);
14478 
14479   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14480   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14481                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14482   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14483 }
14484 
14485 static std::pair<ExprResult, ExprResult>
14486 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14487                            Expr *RHSExpr) {
14488   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14489   if (!S.Context.isDependenceAllowed()) {
14490     // C cannot handle TypoExpr nodes on either side of a binop because it
14491     // doesn't handle dependent types properly, so make sure any TypoExprs have
14492     // been dealt with before checking the operands.
14493     LHS = S.CorrectDelayedTyposInExpr(LHS);
14494     RHS = S.CorrectDelayedTyposInExpr(
14495         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14496         [Opc, LHS](Expr *E) {
14497           if (Opc != BO_Assign)
14498             return ExprResult(E);
14499           // Avoid correcting the RHS to the same Expr as the LHS.
14500           Decl *D = getDeclFromExpr(E);
14501           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14502         });
14503   }
14504   return std::make_pair(LHS, RHS);
14505 }
14506 
14507 /// Returns true if conversion between vectors of halfs and vectors of floats
14508 /// is needed.
14509 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14510                                      Expr *E0, Expr *E1 = nullptr) {
14511   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14512       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14513     return false;
14514 
14515   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14516     QualType Ty = E->IgnoreImplicit()->getType();
14517 
14518     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14519     // to vectors of floats. Although the element type of the vectors is __fp16,
14520     // the vectors shouldn't be treated as storage-only types. See the
14521     // discussion here: https://reviews.llvm.org/rG825235c140e7
14522     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14523       if (VT->getVectorKind() == VectorType::NeonVector)
14524         return false;
14525       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14526     }
14527     return false;
14528   };
14529 
14530   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14531 }
14532 
14533 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14534 /// operator @p Opc at location @c TokLoc. This routine only supports
14535 /// built-in operations; ActOnBinOp handles overloaded operators.
14536 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14537                                     BinaryOperatorKind Opc,
14538                                     Expr *LHSExpr, Expr *RHSExpr) {
14539   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14540     // The syntax only allows initializer lists on the RHS of assignment,
14541     // so we don't need to worry about accepting invalid code for
14542     // non-assignment operators.
14543     // C++11 5.17p9:
14544     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14545     //   of x = {} is x = T().
14546     InitializationKind Kind = InitializationKind::CreateDirectList(
14547         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14548     InitializedEntity Entity =
14549         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14550     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14551     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14552     if (Init.isInvalid())
14553       return Init;
14554     RHSExpr = Init.get();
14555   }
14556 
14557   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14558   QualType ResultTy;     // Result type of the binary operator.
14559   // The following two variables are used for compound assignment operators
14560   QualType CompLHSTy;    // Type of LHS after promotions for computation
14561   QualType CompResultTy; // Type of computation result
14562   ExprValueKind VK = VK_PRValue;
14563   ExprObjectKind OK = OK_Ordinary;
14564   bool ConvertHalfVec = false;
14565 
14566   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14567   if (!LHS.isUsable() || !RHS.isUsable())
14568     return ExprError();
14569 
14570   if (getLangOpts().OpenCL) {
14571     QualType LHSTy = LHSExpr->getType();
14572     QualType RHSTy = RHSExpr->getType();
14573     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14574     // the ATOMIC_VAR_INIT macro.
14575     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14576       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14577       if (BO_Assign == Opc)
14578         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14579       else
14580         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14581       return ExprError();
14582     }
14583 
14584     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14585     // only with a builtin functions and therefore should be disallowed here.
14586     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14587         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14588         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14589         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14590       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14591       return ExprError();
14592     }
14593   }
14594 
14595   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14596   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14597 
14598   switch (Opc) {
14599   case BO_Assign:
14600     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14601     if (getLangOpts().CPlusPlus &&
14602         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14603       VK = LHS.get()->getValueKind();
14604       OK = LHS.get()->getObjectKind();
14605     }
14606     if (!ResultTy.isNull()) {
14607       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14608       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14609 
14610       // Avoid copying a block to the heap if the block is assigned to a local
14611       // auto variable that is declared in the same scope as the block. This
14612       // optimization is unsafe if the local variable is declared in an outer
14613       // scope. For example:
14614       //
14615       // BlockTy b;
14616       // {
14617       //   b = ^{...};
14618       // }
14619       // // It is unsafe to invoke the block here if it wasn't copied to the
14620       // // heap.
14621       // b();
14622 
14623       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14624         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14625           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14626             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14627               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14628 
14629       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14630         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14631                               NTCUC_Assignment, NTCUK_Copy);
14632     }
14633     RecordModifiableNonNullParam(*this, LHS.get());
14634     break;
14635   case BO_PtrMemD:
14636   case BO_PtrMemI:
14637     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14638                                             Opc == BO_PtrMemI);
14639     break;
14640   case BO_Mul:
14641   case BO_Div:
14642     ConvertHalfVec = true;
14643     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14644                                            Opc == BO_Div);
14645     break;
14646   case BO_Rem:
14647     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14648     break;
14649   case BO_Add:
14650     ConvertHalfVec = true;
14651     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14652     break;
14653   case BO_Sub:
14654     ConvertHalfVec = true;
14655     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14656     break;
14657   case BO_Shl:
14658   case BO_Shr:
14659     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14660     break;
14661   case BO_LE:
14662   case BO_LT:
14663   case BO_GE:
14664   case BO_GT:
14665     ConvertHalfVec = true;
14666     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14667     break;
14668   case BO_EQ:
14669   case BO_NE:
14670     ConvertHalfVec = true;
14671     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14672     break;
14673   case BO_Cmp:
14674     ConvertHalfVec = true;
14675     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14676     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14677     break;
14678   case BO_And:
14679     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14680     LLVM_FALLTHROUGH;
14681   case BO_Xor:
14682   case BO_Or:
14683     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14684     break;
14685   case BO_LAnd:
14686   case BO_LOr:
14687     ConvertHalfVec = true;
14688     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14689     break;
14690   case BO_MulAssign:
14691   case BO_DivAssign:
14692     ConvertHalfVec = true;
14693     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14694                                                Opc == BO_DivAssign);
14695     CompLHSTy = CompResultTy;
14696     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14697       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14698     break;
14699   case BO_RemAssign:
14700     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14701     CompLHSTy = CompResultTy;
14702     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14703       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14704     break;
14705   case BO_AddAssign:
14706     ConvertHalfVec = true;
14707     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14708     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14709       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14710     break;
14711   case BO_SubAssign:
14712     ConvertHalfVec = true;
14713     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14714     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14715       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14716     break;
14717   case BO_ShlAssign:
14718   case BO_ShrAssign:
14719     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14720     CompLHSTy = CompResultTy;
14721     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14722       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14723     break;
14724   case BO_AndAssign:
14725   case BO_OrAssign: // fallthrough
14726     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14727     LLVM_FALLTHROUGH;
14728   case BO_XorAssign:
14729     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14730     CompLHSTy = CompResultTy;
14731     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14732       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14733     break;
14734   case BO_Comma:
14735     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14736     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14737       VK = RHS.get()->getValueKind();
14738       OK = RHS.get()->getObjectKind();
14739     }
14740     break;
14741   }
14742   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14743     return ExprError();
14744 
14745   // Some of the binary operations require promoting operands of half vector to
14746   // float vectors and truncating the result back to half vector. For now, we do
14747   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14748   // arm64).
14749   assert(
14750       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14751                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14752       "both sides are half vectors or neither sides are");
14753   ConvertHalfVec =
14754       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14755 
14756   // Check for array bounds violations for both sides of the BinaryOperator
14757   CheckArrayAccess(LHS.get());
14758   CheckArrayAccess(RHS.get());
14759 
14760   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14761     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14762                                                  &Context.Idents.get("object_setClass"),
14763                                                  SourceLocation(), LookupOrdinaryName);
14764     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14765       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14766       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14767           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14768                                         "object_setClass(")
14769           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14770                                           ",")
14771           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14772     }
14773     else
14774       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14775   }
14776   else if (const ObjCIvarRefExpr *OIRE =
14777            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14778     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14779 
14780   // Opc is not a compound assignment if CompResultTy is null.
14781   if (CompResultTy.isNull()) {
14782     if (ConvertHalfVec)
14783       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14784                                  OpLoc, CurFPFeatureOverrides());
14785     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14786                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14787   }
14788 
14789   // Handle compound assignments.
14790   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14791       OK_ObjCProperty) {
14792     VK = VK_LValue;
14793     OK = LHS.get()->getObjectKind();
14794   }
14795 
14796   // The LHS is not converted to the result type for fixed-point compound
14797   // assignment as the common type is computed on demand. Reset the CompLHSTy
14798   // to the LHS type we would have gotten after unary conversions.
14799   if (CompResultTy->isFixedPointType())
14800     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14801 
14802   if (ConvertHalfVec)
14803     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14804                                OpLoc, CurFPFeatureOverrides());
14805 
14806   return CompoundAssignOperator::Create(
14807       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14808       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14809 }
14810 
14811 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14812 /// operators are mixed in a way that suggests that the programmer forgot that
14813 /// comparison operators have higher precedence. The most typical example of
14814 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14815 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14816                                       SourceLocation OpLoc, Expr *LHSExpr,
14817                                       Expr *RHSExpr) {
14818   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14819   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14820 
14821   // Check that one of the sides is a comparison operator and the other isn't.
14822   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14823   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14824   if (isLeftComp == isRightComp)
14825     return;
14826 
14827   // Bitwise operations are sometimes used as eager logical ops.
14828   // Don't diagnose this.
14829   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14830   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14831   if (isLeftBitwise || isRightBitwise)
14832     return;
14833 
14834   SourceRange DiagRange = isLeftComp
14835                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14836                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14837   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14838   SourceRange ParensRange =
14839       isLeftComp
14840           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14841           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14842 
14843   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14844     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14845   SuggestParentheses(Self, OpLoc,
14846     Self.PDiag(diag::note_precedence_silence) << OpStr,
14847     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14848   SuggestParentheses(Self, OpLoc,
14849     Self.PDiag(diag::note_precedence_bitwise_first)
14850       << BinaryOperator::getOpcodeStr(Opc),
14851     ParensRange);
14852 }
14853 
14854 /// It accepts a '&&' expr that is inside a '||' one.
14855 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14856 /// in parentheses.
14857 static void
14858 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14859                                        BinaryOperator *Bop) {
14860   assert(Bop->getOpcode() == BO_LAnd);
14861   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14862       << Bop->getSourceRange() << OpLoc;
14863   SuggestParentheses(Self, Bop->getOperatorLoc(),
14864     Self.PDiag(diag::note_precedence_silence)
14865       << Bop->getOpcodeStr(),
14866     Bop->getSourceRange());
14867 }
14868 
14869 /// Returns true if the given expression can be evaluated as a constant
14870 /// 'true'.
14871 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14872   bool Res;
14873   return !E->isValueDependent() &&
14874          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14875 }
14876 
14877 /// Returns true if the given expression can be evaluated as a constant
14878 /// 'false'.
14879 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14880   bool Res;
14881   return !E->isValueDependent() &&
14882          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14883 }
14884 
14885 /// Look for '&&' in the left hand of a '||' expr.
14886 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14887                                              Expr *LHSExpr, Expr *RHSExpr) {
14888   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14889     if (Bop->getOpcode() == BO_LAnd) {
14890       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14891       if (EvaluatesAsFalse(S, RHSExpr))
14892         return;
14893       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14894       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14895         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14896     } else if (Bop->getOpcode() == BO_LOr) {
14897       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14898         // If it's "a || b && 1 || c" we didn't warn earlier for
14899         // "a || b && 1", but warn now.
14900         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14901           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14902       }
14903     }
14904   }
14905 }
14906 
14907 /// Look for '&&' in the right hand of a '||' expr.
14908 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14909                                              Expr *LHSExpr, Expr *RHSExpr) {
14910   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14911     if (Bop->getOpcode() == BO_LAnd) {
14912       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14913       if (EvaluatesAsFalse(S, LHSExpr))
14914         return;
14915       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14916       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14917         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14918     }
14919   }
14920 }
14921 
14922 /// Look for bitwise op in the left or right hand of a bitwise op with
14923 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14924 /// the '&' expression in parentheses.
14925 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14926                                          SourceLocation OpLoc, Expr *SubExpr) {
14927   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14928     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14929       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14930         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14931         << Bop->getSourceRange() << OpLoc;
14932       SuggestParentheses(S, Bop->getOperatorLoc(),
14933         S.PDiag(diag::note_precedence_silence)
14934           << Bop->getOpcodeStr(),
14935         Bop->getSourceRange());
14936     }
14937   }
14938 }
14939 
14940 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14941                                     Expr *SubExpr, StringRef Shift) {
14942   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14943     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14944       StringRef Op = Bop->getOpcodeStr();
14945       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14946           << Bop->getSourceRange() << OpLoc << Shift << Op;
14947       SuggestParentheses(S, Bop->getOperatorLoc(),
14948           S.PDiag(diag::note_precedence_silence) << Op,
14949           Bop->getSourceRange());
14950     }
14951   }
14952 }
14953 
14954 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14955                                  Expr *LHSExpr, Expr *RHSExpr) {
14956   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14957   if (!OCE)
14958     return;
14959 
14960   FunctionDecl *FD = OCE->getDirectCallee();
14961   if (!FD || !FD->isOverloadedOperator())
14962     return;
14963 
14964   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14965   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14966     return;
14967 
14968   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14969       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14970       << (Kind == OO_LessLess);
14971   SuggestParentheses(S, OCE->getOperatorLoc(),
14972                      S.PDiag(diag::note_precedence_silence)
14973                          << (Kind == OO_LessLess ? "<<" : ">>"),
14974                      OCE->getSourceRange());
14975   SuggestParentheses(
14976       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14977       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14978 }
14979 
14980 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14981 /// precedence.
14982 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14983                                     SourceLocation OpLoc, Expr *LHSExpr,
14984                                     Expr *RHSExpr){
14985   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14986   if (BinaryOperator::isBitwiseOp(Opc))
14987     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14988 
14989   // Diagnose "arg1 & arg2 | arg3"
14990   if ((Opc == BO_Or || Opc == BO_Xor) &&
14991       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14992     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14993     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14994   }
14995 
14996   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14997   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14998   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14999     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15000     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15001   }
15002 
15003   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15004       || Opc == BO_Shr) {
15005     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15006     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15007     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15008   }
15009 
15010   // Warn on overloaded shift operators and comparisons, such as:
15011   // cout << 5 == 4;
15012   if (BinaryOperator::isComparisonOp(Opc))
15013     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15014 }
15015 
15016 // Binary Operators.  'Tok' is the token for the operator.
15017 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15018                             tok::TokenKind Kind,
15019                             Expr *LHSExpr, Expr *RHSExpr) {
15020   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15021   assert(LHSExpr && "ActOnBinOp(): missing left expression");
15022   assert(RHSExpr && "ActOnBinOp(): missing right expression");
15023 
15024   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15025   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15026 
15027   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15028 }
15029 
15030 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15031                        UnresolvedSetImpl &Functions) {
15032   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15033   if (OverOp != OO_None && OverOp != OO_Equal)
15034     LookupOverloadedOperatorName(OverOp, S, Functions);
15035 
15036   // In C++20 onwards, we may have a second operator to look up.
15037   if (getLangOpts().CPlusPlus20) {
15038     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15039       LookupOverloadedOperatorName(ExtraOp, S, Functions);
15040   }
15041 }
15042 
15043 /// Build an overloaded binary operator expression in the given scope.
15044 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15045                                        BinaryOperatorKind Opc,
15046                                        Expr *LHS, Expr *RHS) {
15047   switch (Opc) {
15048   case BO_Assign:
15049   case BO_DivAssign:
15050   case BO_RemAssign:
15051   case BO_SubAssign:
15052   case BO_AndAssign:
15053   case BO_OrAssign:
15054   case BO_XorAssign:
15055     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15056     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15057     break;
15058   default:
15059     break;
15060   }
15061 
15062   // Find all of the overloaded operators visible from this point.
15063   UnresolvedSet<16> Functions;
15064   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15065 
15066   // Build the (potentially-overloaded, potentially-dependent)
15067   // binary operation.
15068   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15069 }
15070 
15071 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15072                             BinaryOperatorKind Opc,
15073                             Expr *LHSExpr, Expr *RHSExpr) {
15074   ExprResult LHS, RHS;
15075   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15076   if (!LHS.isUsable() || !RHS.isUsable())
15077     return ExprError();
15078   LHSExpr = LHS.get();
15079   RHSExpr = RHS.get();
15080 
15081   // We want to end up calling one of checkPseudoObjectAssignment
15082   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15083   // both expressions are overloadable or either is type-dependent),
15084   // or CreateBuiltinBinOp (in any other case).  We also want to get
15085   // any placeholder types out of the way.
15086 
15087   // Handle pseudo-objects in the LHS.
15088   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15089     // Assignments with a pseudo-object l-value need special analysis.
15090     if (pty->getKind() == BuiltinType::PseudoObject &&
15091         BinaryOperator::isAssignmentOp(Opc))
15092       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15093 
15094     // Don't resolve overloads if the other type is overloadable.
15095     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15096       // We can't actually test that if we still have a placeholder,
15097       // though.  Fortunately, none of the exceptions we see in that
15098       // code below are valid when the LHS is an overload set.  Note
15099       // that an overload set can be dependently-typed, but it never
15100       // instantiates to having an overloadable type.
15101       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15102       if (resolvedRHS.isInvalid()) return ExprError();
15103       RHSExpr = resolvedRHS.get();
15104 
15105       if (RHSExpr->isTypeDependent() ||
15106           RHSExpr->getType()->isOverloadableType())
15107         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15108     }
15109 
15110     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15111     // template, diagnose the missing 'template' keyword instead of diagnosing
15112     // an invalid use of a bound member function.
15113     //
15114     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15115     // to C++1z [over.over]/1.4, but we already checked for that case above.
15116     if (Opc == BO_LT && inTemplateInstantiation() &&
15117         (pty->getKind() == BuiltinType::BoundMember ||
15118          pty->getKind() == BuiltinType::Overload)) {
15119       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15120       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15121           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15122             return isa<FunctionTemplateDecl>(ND);
15123           })) {
15124         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15125                                 : OE->getNameLoc(),
15126              diag::err_template_kw_missing)
15127           << OE->getName().getAsString() << "";
15128         return ExprError();
15129       }
15130     }
15131 
15132     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15133     if (LHS.isInvalid()) return ExprError();
15134     LHSExpr = LHS.get();
15135   }
15136 
15137   // Handle pseudo-objects in the RHS.
15138   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15139     // An overload in the RHS can potentially be resolved by the type
15140     // being assigned to.
15141     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15142       if (getLangOpts().CPlusPlus &&
15143           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15144            LHSExpr->getType()->isOverloadableType()))
15145         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15146 
15147       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15148     }
15149 
15150     // Don't resolve overloads if the other type is overloadable.
15151     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15152         LHSExpr->getType()->isOverloadableType())
15153       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15154 
15155     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15156     if (!resolvedRHS.isUsable()) return ExprError();
15157     RHSExpr = resolvedRHS.get();
15158   }
15159 
15160   if (getLangOpts().CPlusPlus) {
15161     // If either expression is type-dependent, always build an
15162     // overloaded op.
15163     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15164       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15165 
15166     // Otherwise, build an overloaded op if either expression has an
15167     // overloadable type.
15168     if (LHSExpr->getType()->isOverloadableType() ||
15169         RHSExpr->getType()->isOverloadableType())
15170       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15171   }
15172 
15173   if (getLangOpts().RecoveryAST &&
15174       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15175     assert(!getLangOpts().CPlusPlus);
15176     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15177            "Should only occur in error-recovery path.");
15178     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15179       // C [6.15.16] p3:
15180       // An assignment expression has the value of the left operand after the
15181       // assignment, but is not an lvalue.
15182       return CompoundAssignOperator::Create(
15183           Context, LHSExpr, RHSExpr, Opc,
15184           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15185           OpLoc, CurFPFeatureOverrides());
15186     QualType ResultType;
15187     switch (Opc) {
15188     case BO_Assign:
15189       ResultType = LHSExpr->getType().getUnqualifiedType();
15190       break;
15191     case BO_LT:
15192     case BO_GT:
15193     case BO_LE:
15194     case BO_GE:
15195     case BO_EQ:
15196     case BO_NE:
15197     case BO_LAnd:
15198     case BO_LOr:
15199       // These operators have a fixed result type regardless of operands.
15200       ResultType = Context.IntTy;
15201       break;
15202     case BO_Comma:
15203       ResultType = RHSExpr->getType();
15204       break;
15205     default:
15206       ResultType = Context.DependentTy;
15207       break;
15208     }
15209     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15210                                   VK_PRValue, OK_Ordinary, OpLoc,
15211                                   CurFPFeatureOverrides());
15212   }
15213 
15214   // Build a built-in binary operation.
15215   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15216 }
15217 
15218 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15219   if (T.isNull() || T->isDependentType())
15220     return false;
15221 
15222   if (!T->isPromotableIntegerType())
15223     return true;
15224 
15225   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15226 }
15227 
15228 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15229                                       UnaryOperatorKind Opc,
15230                                       Expr *InputExpr) {
15231   ExprResult Input = InputExpr;
15232   ExprValueKind VK = VK_PRValue;
15233   ExprObjectKind OK = OK_Ordinary;
15234   QualType resultType;
15235   bool CanOverflow = false;
15236 
15237   bool ConvertHalfVec = false;
15238   if (getLangOpts().OpenCL) {
15239     QualType Ty = InputExpr->getType();
15240     // The only legal unary operation for atomics is '&'.
15241     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15242     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15243     // only with a builtin functions and therefore should be disallowed here.
15244         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15245         || Ty->isBlockPointerType())) {
15246       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15247                        << InputExpr->getType()
15248                        << Input.get()->getSourceRange());
15249     }
15250   }
15251 
15252   switch (Opc) {
15253   case UO_PreInc:
15254   case UO_PreDec:
15255   case UO_PostInc:
15256   case UO_PostDec:
15257     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15258                                                 OpLoc,
15259                                                 Opc == UO_PreInc ||
15260                                                 Opc == UO_PostInc,
15261                                                 Opc == UO_PreInc ||
15262                                                 Opc == UO_PreDec);
15263     CanOverflow = isOverflowingIntegerType(Context, resultType);
15264     break;
15265   case UO_AddrOf:
15266     resultType = CheckAddressOfOperand(Input, OpLoc);
15267     CheckAddressOfNoDeref(InputExpr);
15268     RecordModifiableNonNullParam(*this, InputExpr);
15269     break;
15270   case UO_Deref: {
15271     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15272     if (Input.isInvalid()) return ExprError();
15273     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15274     break;
15275   }
15276   case UO_Plus:
15277   case UO_Minus:
15278     CanOverflow = Opc == UO_Minus &&
15279                   isOverflowingIntegerType(Context, Input.get()->getType());
15280     Input = UsualUnaryConversions(Input.get());
15281     if (Input.isInvalid()) return ExprError();
15282     // Unary plus and minus require promoting an operand of half vector to a
15283     // float vector and truncating the result back to a half vector. For now, we
15284     // do this only when HalfArgsAndReturns is set (that is, when the target is
15285     // arm or arm64).
15286     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15287 
15288     // If the operand is a half vector, promote it to a float vector.
15289     if (ConvertHalfVec)
15290       Input = convertVector(Input.get(), Context.FloatTy, *this);
15291     resultType = Input.get()->getType();
15292     if (resultType->isDependentType())
15293       break;
15294     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15295       break;
15296     else if (resultType->isVectorType() &&
15297              // The z vector extensions don't allow + or - with bool vectors.
15298              (!Context.getLangOpts().ZVector ||
15299               resultType->castAs<VectorType>()->getVectorKind() !=
15300               VectorType::AltiVecBool))
15301       break;
15302     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15303              Opc == UO_Plus &&
15304              resultType->isPointerType())
15305       break;
15306 
15307     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15308       << resultType << Input.get()->getSourceRange());
15309 
15310   case UO_Not: // bitwise complement
15311     Input = UsualUnaryConversions(Input.get());
15312     if (Input.isInvalid())
15313       return ExprError();
15314     resultType = Input.get()->getType();
15315     if (resultType->isDependentType())
15316       break;
15317     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15318     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15319       // C99 does not support '~' for complex conjugation.
15320       Diag(OpLoc, diag::ext_integer_complement_complex)
15321           << resultType << Input.get()->getSourceRange();
15322     else if (resultType->hasIntegerRepresentation())
15323       break;
15324     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15325       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15326       // on vector float types.
15327       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15328       if (!T->isIntegerType())
15329         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15330                           << resultType << Input.get()->getSourceRange());
15331     } else {
15332       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15333                        << resultType << Input.get()->getSourceRange());
15334     }
15335     break;
15336 
15337   case UO_LNot: // logical negation
15338     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15339     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15340     if (Input.isInvalid()) return ExprError();
15341     resultType = Input.get()->getType();
15342 
15343     // Though we still have to promote half FP to float...
15344     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15345       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15346       resultType = Context.FloatTy;
15347     }
15348 
15349     if (resultType->isDependentType())
15350       break;
15351     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15352       // C99 6.5.3.3p1: ok, fallthrough;
15353       if (Context.getLangOpts().CPlusPlus) {
15354         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15355         // operand contextually converted to bool.
15356         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15357                                   ScalarTypeToBooleanCastKind(resultType));
15358       } else if (Context.getLangOpts().OpenCL &&
15359                  Context.getLangOpts().OpenCLVersion < 120) {
15360         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15361         // operate on scalar float types.
15362         if (!resultType->isIntegerType() && !resultType->isPointerType())
15363           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15364                            << resultType << Input.get()->getSourceRange());
15365       }
15366     } else if (resultType->isExtVectorType()) {
15367       if (Context.getLangOpts().OpenCL &&
15368           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15369         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15370         // operate on vector float types.
15371         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15372         if (!T->isIntegerType())
15373           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15374                            << resultType << Input.get()->getSourceRange());
15375       }
15376       // Vector logical not returns the signed variant of the operand type.
15377       resultType = GetSignedVectorType(resultType);
15378       break;
15379     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15380       const VectorType *VTy = resultType->castAs<VectorType>();
15381       if (VTy->getVectorKind() != VectorType::GenericVector)
15382         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15383                          << resultType << Input.get()->getSourceRange());
15384 
15385       // Vector logical not returns the signed variant of the operand type.
15386       resultType = GetSignedVectorType(resultType);
15387       break;
15388     } else {
15389       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15390         << resultType << Input.get()->getSourceRange());
15391     }
15392 
15393     // LNot always has type int. C99 6.5.3.3p5.
15394     // In C++, it's bool. C++ 5.3.1p8
15395     resultType = Context.getLogicalOperationType();
15396     break;
15397   case UO_Real:
15398   case UO_Imag:
15399     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15400     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15401     // complex l-values to ordinary l-values and all other values to r-values.
15402     if (Input.isInvalid()) return ExprError();
15403     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15404       if (Input.get()->isGLValue() &&
15405           Input.get()->getObjectKind() == OK_Ordinary)
15406         VK = Input.get()->getValueKind();
15407     } else if (!getLangOpts().CPlusPlus) {
15408       // In C, a volatile scalar is read by __imag. In C++, it is not.
15409       Input = DefaultLvalueConversion(Input.get());
15410     }
15411     break;
15412   case UO_Extension:
15413     resultType = Input.get()->getType();
15414     VK = Input.get()->getValueKind();
15415     OK = Input.get()->getObjectKind();
15416     break;
15417   case UO_Coawait:
15418     // It's unnecessary to represent the pass-through operator co_await in the
15419     // AST; just return the input expression instead.
15420     assert(!Input.get()->getType()->isDependentType() &&
15421                    "the co_await expression must be non-dependant before "
15422                    "building operator co_await");
15423     return Input;
15424   }
15425   if (resultType.isNull() || Input.isInvalid())
15426     return ExprError();
15427 
15428   // Check for array bounds violations in the operand of the UnaryOperator,
15429   // except for the '*' and '&' operators that have to be handled specially
15430   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15431   // that are explicitly defined as valid by the standard).
15432   if (Opc != UO_AddrOf && Opc != UO_Deref)
15433     CheckArrayAccess(Input.get());
15434 
15435   auto *UO =
15436       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15437                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15438 
15439   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15440       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15441       !isUnevaluatedContext())
15442     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15443 
15444   // Convert the result back to a half vector.
15445   if (ConvertHalfVec)
15446     return convertVector(UO, Context.HalfTy, *this);
15447   return UO;
15448 }
15449 
15450 /// Determine whether the given expression is a qualified member
15451 /// access expression, of a form that could be turned into a pointer to member
15452 /// with the address-of operator.
15453 bool Sema::isQualifiedMemberAccess(Expr *E) {
15454   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15455     if (!DRE->getQualifier())
15456       return false;
15457 
15458     ValueDecl *VD = DRE->getDecl();
15459     if (!VD->isCXXClassMember())
15460       return false;
15461 
15462     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15463       return true;
15464     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15465       return Method->isInstance();
15466 
15467     return false;
15468   }
15469 
15470   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15471     if (!ULE->getQualifier())
15472       return false;
15473 
15474     for (NamedDecl *D : ULE->decls()) {
15475       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15476         if (Method->isInstance())
15477           return true;
15478       } else {
15479         // Overload set does not contain methods.
15480         break;
15481       }
15482     }
15483 
15484     return false;
15485   }
15486 
15487   return false;
15488 }
15489 
15490 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15491                               UnaryOperatorKind Opc, Expr *Input) {
15492   // First things first: handle placeholders so that the
15493   // overloaded-operator check considers the right type.
15494   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15495     // Increment and decrement of pseudo-object references.
15496     if (pty->getKind() == BuiltinType::PseudoObject &&
15497         UnaryOperator::isIncrementDecrementOp(Opc))
15498       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15499 
15500     // extension is always a builtin operator.
15501     if (Opc == UO_Extension)
15502       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15503 
15504     // & gets special logic for several kinds of placeholder.
15505     // The builtin code knows what to do.
15506     if (Opc == UO_AddrOf &&
15507         (pty->getKind() == BuiltinType::Overload ||
15508          pty->getKind() == BuiltinType::UnknownAny ||
15509          pty->getKind() == BuiltinType::BoundMember))
15510       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15511 
15512     // Anything else needs to be handled now.
15513     ExprResult Result = CheckPlaceholderExpr(Input);
15514     if (Result.isInvalid()) return ExprError();
15515     Input = Result.get();
15516   }
15517 
15518   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15519       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15520       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15521     // Find all of the overloaded operators visible from this point.
15522     UnresolvedSet<16> Functions;
15523     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15524     if (S && OverOp != OO_None)
15525       LookupOverloadedOperatorName(OverOp, S, Functions);
15526 
15527     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15528   }
15529 
15530   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15531 }
15532 
15533 // Unary Operators.  'Tok' is the token for the operator.
15534 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15535                               tok::TokenKind Op, Expr *Input) {
15536   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15537 }
15538 
15539 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15540 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15541                                 LabelDecl *TheDecl) {
15542   TheDecl->markUsed(Context);
15543   // Create the AST node.  The address of a label always has type 'void*'.
15544   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15545                                      Context.getPointerType(Context.VoidTy));
15546 }
15547 
15548 void Sema::ActOnStartStmtExpr() {
15549   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15550 }
15551 
15552 void Sema::ActOnStmtExprError() {
15553   // Note that function is also called by TreeTransform when leaving a
15554   // StmtExpr scope without rebuilding anything.
15555 
15556   DiscardCleanupsInEvaluationContext();
15557   PopExpressionEvaluationContext();
15558 }
15559 
15560 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15561                                SourceLocation RPLoc) {
15562   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15563 }
15564 
15565 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15566                                SourceLocation RPLoc, unsigned TemplateDepth) {
15567   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15568   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15569 
15570   if (hasAnyUnrecoverableErrorsInThisFunction())
15571     DiscardCleanupsInEvaluationContext();
15572   assert(!Cleanup.exprNeedsCleanups() &&
15573          "cleanups within StmtExpr not correctly bound!");
15574   PopExpressionEvaluationContext();
15575 
15576   // FIXME: there are a variety of strange constraints to enforce here, for
15577   // example, it is not possible to goto into a stmt expression apparently.
15578   // More semantic analysis is needed.
15579 
15580   // If there are sub-stmts in the compound stmt, take the type of the last one
15581   // as the type of the stmtexpr.
15582   QualType Ty = Context.VoidTy;
15583   bool StmtExprMayBindToTemp = false;
15584   if (!Compound->body_empty()) {
15585     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15586     if (const auto *LastStmt =
15587             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15588       if (const Expr *Value = LastStmt->getExprStmt()) {
15589         StmtExprMayBindToTemp = true;
15590         Ty = Value->getType();
15591       }
15592     }
15593   }
15594 
15595   // FIXME: Check that expression type is complete/non-abstract; statement
15596   // expressions are not lvalues.
15597   Expr *ResStmtExpr =
15598       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15599   if (StmtExprMayBindToTemp)
15600     return MaybeBindToTemporary(ResStmtExpr);
15601   return ResStmtExpr;
15602 }
15603 
15604 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15605   if (ER.isInvalid())
15606     return ExprError();
15607 
15608   // Do function/array conversion on the last expression, but not
15609   // lvalue-to-rvalue.  However, initialize an unqualified type.
15610   ER = DefaultFunctionArrayConversion(ER.get());
15611   if (ER.isInvalid())
15612     return ExprError();
15613   Expr *E = ER.get();
15614 
15615   if (E->isTypeDependent())
15616     return E;
15617 
15618   // In ARC, if the final expression ends in a consume, splice
15619   // the consume out and bind it later.  In the alternate case
15620   // (when dealing with a retainable type), the result
15621   // initialization will create a produce.  In both cases the
15622   // result will be +1, and we'll need to balance that out with
15623   // a bind.
15624   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15625   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15626     return Cast->getSubExpr();
15627 
15628   // FIXME: Provide a better location for the initialization.
15629   return PerformCopyInitialization(
15630       InitializedEntity::InitializeStmtExprResult(
15631           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15632       SourceLocation(), E);
15633 }
15634 
15635 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15636                                       TypeSourceInfo *TInfo,
15637                                       ArrayRef<OffsetOfComponent> Components,
15638                                       SourceLocation RParenLoc) {
15639   QualType ArgTy = TInfo->getType();
15640   bool Dependent = ArgTy->isDependentType();
15641   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15642 
15643   // We must have at least one component that refers to the type, and the first
15644   // one is known to be a field designator.  Verify that the ArgTy represents
15645   // a struct/union/class.
15646   if (!Dependent && !ArgTy->isRecordType())
15647     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15648                        << ArgTy << TypeRange);
15649 
15650   // Type must be complete per C99 7.17p3 because a declaring a variable
15651   // with an incomplete type would be ill-formed.
15652   if (!Dependent
15653       && RequireCompleteType(BuiltinLoc, ArgTy,
15654                              diag::err_offsetof_incomplete_type, TypeRange))
15655     return ExprError();
15656 
15657   bool DidWarnAboutNonPOD = false;
15658   QualType CurrentType = ArgTy;
15659   SmallVector<OffsetOfNode, 4> Comps;
15660   SmallVector<Expr*, 4> Exprs;
15661   for (const OffsetOfComponent &OC : Components) {
15662     if (OC.isBrackets) {
15663       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15664       if (!CurrentType->isDependentType()) {
15665         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15666         if(!AT)
15667           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15668                            << CurrentType);
15669         CurrentType = AT->getElementType();
15670       } else
15671         CurrentType = Context.DependentTy;
15672 
15673       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15674       if (IdxRval.isInvalid())
15675         return ExprError();
15676       Expr *Idx = IdxRval.get();
15677 
15678       // The expression must be an integral expression.
15679       // FIXME: An integral constant expression?
15680       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15681           !Idx->getType()->isIntegerType())
15682         return ExprError(
15683             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15684             << Idx->getSourceRange());
15685 
15686       // Record this array index.
15687       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15688       Exprs.push_back(Idx);
15689       continue;
15690     }
15691 
15692     // Offset of a field.
15693     if (CurrentType->isDependentType()) {
15694       // We have the offset of a field, but we can't look into the dependent
15695       // type. Just record the identifier of the field.
15696       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15697       CurrentType = Context.DependentTy;
15698       continue;
15699     }
15700 
15701     // We need to have a complete type to look into.
15702     if (RequireCompleteType(OC.LocStart, CurrentType,
15703                             diag::err_offsetof_incomplete_type))
15704       return ExprError();
15705 
15706     // Look for the designated field.
15707     const RecordType *RC = CurrentType->getAs<RecordType>();
15708     if (!RC)
15709       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15710                        << CurrentType);
15711     RecordDecl *RD = RC->getDecl();
15712 
15713     // C++ [lib.support.types]p5:
15714     //   The macro offsetof accepts a restricted set of type arguments in this
15715     //   International Standard. type shall be a POD structure or a POD union
15716     //   (clause 9).
15717     // C++11 [support.types]p4:
15718     //   If type is not a standard-layout class (Clause 9), the results are
15719     //   undefined.
15720     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15721       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15722       unsigned DiagID =
15723         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15724                             : diag::ext_offsetof_non_pod_type;
15725 
15726       if (!IsSafe && !DidWarnAboutNonPOD &&
15727           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15728                               PDiag(DiagID)
15729                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15730                               << CurrentType))
15731         DidWarnAboutNonPOD = true;
15732     }
15733 
15734     // Look for the field.
15735     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15736     LookupQualifiedName(R, RD);
15737     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15738     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15739     if (!MemberDecl) {
15740       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15741         MemberDecl = IndirectMemberDecl->getAnonField();
15742     }
15743 
15744     if (!MemberDecl)
15745       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15746                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15747                                                               OC.LocEnd));
15748 
15749     // C99 7.17p3:
15750     //   (If the specified member is a bit-field, the behavior is undefined.)
15751     //
15752     // We diagnose this as an error.
15753     if (MemberDecl->isBitField()) {
15754       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15755         << MemberDecl->getDeclName()
15756         << SourceRange(BuiltinLoc, RParenLoc);
15757       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15758       return ExprError();
15759     }
15760 
15761     RecordDecl *Parent = MemberDecl->getParent();
15762     if (IndirectMemberDecl)
15763       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15764 
15765     // If the member was found in a base class, introduce OffsetOfNodes for
15766     // the base class indirections.
15767     CXXBasePaths Paths;
15768     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15769                       Paths)) {
15770       if (Paths.getDetectedVirtual()) {
15771         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15772           << MemberDecl->getDeclName()
15773           << SourceRange(BuiltinLoc, RParenLoc);
15774         return ExprError();
15775       }
15776 
15777       CXXBasePath &Path = Paths.front();
15778       for (const CXXBasePathElement &B : Path)
15779         Comps.push_back(OffsetOfNode(B.Base));
15780     }
15781 
15782     if (IndirectMemberDecl) {
15783       for (auto *FI : IndirectMemberDecl->chain()) {
15784         assert(isa<FieldDecl>(FI));
15785         Comps.push_back(OffsetOfNode(OC.LocStart,
15786                                      cast<FieldDecl>(FI), OC.LocEnd));
15787       }
15788     } else
15789       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15790 
15791     CurrentType = MemberDecl->getType().getNonReferenceType();
15792   }
15793 
15794   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15795                               Comps, Exprs, RParenLoc);
15796 }
15797 
15798 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15799                                       SourceLocation BuiltinLoc,
15800                                       SourceLocation TypeLoc,
15801                                       ParsedType ParsedArgTy,
15802                                       ArrayRef<OffsetOfComponent> Components,
15803                                       SourceLocation RParenLoc) {
15804 
15805   TypeSourceInfo *ArgTInfo;
15806   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15807   if (ArgTy.isNull())
15808     return ExprError();
15809 
15810   if (!ArgTInfo)
15811     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15812 
15813   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15814 }
15815 
15816 
15817 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15818                                  Expr *CondExpr,
15819                                  Expr *LHSExpr, Expr *RHSExpr,
15820                                  SourceLocation RPLoc) {
15821   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15822 
15823   ExprValueKind VK = VK_PRValue;
15824   ExprObjectKind OK = OK_Ordinary;
15825   QualType resType;
15826   bool CondIsTrue = false;
15827   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15828     resType = Context.DependentTy;
15829   } else {
15830     // The conditional expression is required to be a constant expression.
15831     llvm::APSInt condEval(32);
15832     ExprResult CondICE = VerifyIntegerConstantExpression(
15833         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15834     if (CondICE.isInvalid())
15835       return ExprError();
15836     CondExpr = CondICE.get();
15837     CondIsTrue = condEval.getZExtValue();
15838 
15839     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15840     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15841 
15842     resType = ActiveExpr->getType();
15843     VK = ActiveExpr->getValueKind();
15844     OK = ActiveExpr->getObjectKind();
15845   }
15846 
15847   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15848                                   resType, VK, OK, RPLoc, CondIsTrue);
15849 }
15850 
15851 //===----------------------------------------------------------------------===//
15852 // Clang Extensions.
15853 //===----------------------------------------------------------------------===//
15854 
15855 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15856 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15857   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15858 
15859   if (LangOpts.CPlusPlus) {
15860     MangleNumberingContext *MCtx;
15861     Decl *ManglingContextDecl;
15862     std::tie(MCtx, ManglingContextDecl) =
15863         getCurrentMangleNumberContext(Block->getDeclContext());
15864     if (MCtx) {
15865       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15866       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15867     }
15868   }
15869 
15870   PushBlockScope(CurScope, Block);
15871   CurContext->addDecl(Block);
15872   if (CurScope)
15873     PushDeclContext(CurScope, Block);
15874   else
15875     CurContext = Block;
15876 
15877   getCurBlock()->HasImplicitReturnType = true;
15878 
15879   // Enter a new evaluation context to insulate the block from any
15880   // cleanups from the enclosing full-expression.
15881   PushExpressionEvaluationContext(
15882       ExpressionEvaluationContext::PotentiallyEvaluated);
15883 }
15884 
15885 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15886                                Scope *CurScope) {
15887   assert(ParamInfo.getIdentifier() == nullptr &&
15888          "block-id should have no identifier!");
15889   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15890   BlockScopeInfo *CurBlock = getCurBlock();
15891 
15892   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15893   QualType T = Sig->getType();
15894 
15895   // FIXME: We should allow unexpanded parameter packs here, but that would,
15896   // in turn, make the block expression contain unexpanded parameter packs.
15897   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15898     // Drop the parameters.
15899     FunctionProtoType::ExtProtoInfo EPI;
15900     EPI.HasTrailingReturn = false;
15901     EPI.TypeQuals.addConst();
15902     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15903     Sig = Context.getTrivialTypeSourceInfo(T);
15904   }
15905 
15906   // GetTypeForDeclarator always produces a function type for a block
15907   // literal signature.  Furthermore, it is always a FunctionProtoType
15908   // unless the function was written with a typedef.
15909   assert(T->isFunctionType() &&
15910          "GetTypeForDeclarator made a non-function block signature");
15911 
15912   // Look for an explicit signature in that function type.
15913   FunctionProtoTypeLoc ExplicitSignature;
15914 
15915   if ((ExplicitSignature = Sig->getTypeLoc()
15916                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15917 
15918     // Check whether that explicit signature was synthesized by
15919     // GetTypeForDeclarator.  If so, don't save that as part of the
15920     // written signature.
15921     if (ExplicitSignature.getLocalRangeBegin() ==
15922         ExplicitSignature.getLocalRangeEnd()) {
15923       // This would be much cheaper if we stored TypeLocs instead of
15924       // TypeSourceInfos.
15925       TypeLoc Result = ExplicitSignature.getReturnLoc();
15926       unsigned Size = Result.getFullDataSize();
15927       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15928       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15929 
15930       ExplicitSignature = FunctionProtoTypeLoc();
15931     }
15932   }
15933 
15934   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15935   CurBlock->FunctionType = T;
15936 
15937   const auto *Fn = T->castAs<FunctionType>();
15938   QualType RetTy = Fn->getReturnType();
15939   bool isVariadic =
15940       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15941 
15942   CurBlock->TheDecl->setIsVariadic(isVariadic);
15943 
15944   // Context.DependentTy is used as a placeholder for a missing block
15945   // return type.  TODO:  what should we do with declarators like:
15946   //   ^ * { ... }
15947   // If the answer is "apply template argument deduction"....
15948   if (RetTy != Context.DependentTy) {
15949     CurBlock->ReturnType = RetTy;
15950     CurBlock->TheDecl->setBlockMissingReturnType(false);
15951     CurBlock->HasImplicitReturnType = false;
15952   }
15953 
15954   // Push block parameters from the declarator if we had them.
15955   SmallVector<ParmVarDecl*, 8> Params;
15956   if (ExplicitSignature) {
15957     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15958       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15959       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15960           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15961         // Diagnose this as an extension in C17 and earlier.
15962         if (!getLangOpts().C2x)
15963           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15964       }
15965       Params.push_back(Param);
15966     }
15967 
15968   // Fake up parameter variables if we have a typedef, like
15969   //   ^ fntype { ... }
15970   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15971     for (const auto &I : Fn->param_types()) {
15972       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15973           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15974       Params.push_back(Param);
15975     }
15976   }
15977 
15978   // Set the parameters on the block decl.
15979   if (!Params.empty()) {
15980     CurBlock->TheDecl->setParams(Params);
15981     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15982                              /*CheckParameterNames=*/false);
15983   }
15984 
15985   // Finally we can process decl attributes.
15986   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15987 
15988   // Put the parameter variables in scope.
15989   for (auto AI : CurBlock->TheDecl->parameters()) {
15990     AI->setOwningFunction(CurBlock->TheDecl);
15991 
15992     // If this has an identifier, add it to the scope stack.
15993     if (AI->getIdentifier()) {
15994       CheckShadow(CurBlock->TheScope, AI);
15995 
15996       PushOnScopeChains(AI, CurBlock->TheScope);
15997     }
15998   }
15999 }
16000 
16001 /// ActOnBlockError - If there is an error parsing a block, this callback
16002 /// is invoked to pop the information about the block from the action impl.
16003 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16004   // Leave the expression-evaluation context.
16005   DiscardCleanupsInEvaluationContext();
16006   PopExpressionEvaluationContext();
16007 
16008   // Pop off CurBlock, handle nested blocks.
16009   PopDeclContext();
16010   PopFunctionScopeInfo();
16011 }
16012 
16013 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16014 /// literal was successfully completed.  ^(int x){...}
16015 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16016                                     Stmt *Body, Scope *CurScope) {
16017   // If blocks are disabled, emit an error.
16018   if (!LangOpts.Blocks)
16019     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16020 
16021   // Leave the expression-evaluation context.
16022   if (hasAnyUnrecoverableErrorsInThisFunction())
16023     DiscardCleanupsInEvaluationContext();
16024   assert(!Cleanup.exprNeedsCleanups() &&
16025          "cleanups within block not correctly bound!");
16026   PopExpressionEvaluationContext();
16027 
16028   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16029   BlockDecl *BD = BSI->TheDecl;
16030 
16031   if (BSI->HasImplicitReturnType)
16032     deduceClosureReturnType(*BSI);
16033 
16034   QualType RetTy = Context.VoidTy;
16035   if (!BSI->ReturnType.isNull())
16036     RetTy = BSI->ReturnType;
16037 
16038   bool NoReturn = BD->hasAttr<NoReturnAttr>();
16039   QualType BlockTy;
16040 
16041   // If the user wrote a function type in some form, try to use that.
16042   if (!BSI->FunctionType.isNull()) {
16043     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16044 
16045     FunctionType::ExtInfo Ext = FTy->getExtInfo();
16046     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16047 
16048     // Turn protoless block types into nullary block types.
16049     if (isa<FunctionNoProtoType>(FTy)) {
16050       FunctionProtoType::ExtProtoInfo EPI;
16051       EPI.ExtInfo = Ext;
16052       BlockTy = Context.getFunctionType(RetTy, None, EPI);
16053 
16054     // Otherwise, if we don't need to change anything about the function type,
16055     // preserve its sugar structure.
16056     } else if (FTy->getReturnType() == RetTy &&
16057                (!NoReturn || FTy->getNoReturnAttr())) {
16058       BlockTy = BSI->FunctionType;
16059 
16060     // Otherwise, make the minimal modifications to the function type.
16061     } else {
16062       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16063       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16064       EPI.TypeQuals = Qualifiers();
16065       EPI.ExtInfo = Ext;
16066       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16067     }
16068 
16069   // If we don't have a function type, just build one from nothing.
16070   } else {
16071     FunctionProtoType::ExtProtoInfo EPI;
16072     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16073     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16074   }
16075 
16076   DiagnoseUnusedParameters(BD->parameters());
16077   BlockTy = Context.getBlockPointerType(BlockTy);
16078 
16079   // If needed, diagnose invalid gotos and switches in the block.
16080   if (getCurFunction()->NeedsScopeChecking() &&
16081       !PP.isCodeCompletionEnabled())
16082     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16083 
16084   BD->setBody(cast<CompoundStmt>(Body));
16085 
16086   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16087     DiagnoseUnguardedAvailabilityViolations(BD);
16088 
16089   // Try to apply the named return value optimization. We have to check again
16090   // if we can do this, though, because blocks keep return statements around
16091   // to deduce an implicit return type.
16092   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16093       !BD->isDependentContext())
16094     computeNRVO(Body, BSI);
16095 
16096   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16097       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16098     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16099                           NTCUK_Destruct|NTCUK_Copy);
16100 
16101   PopDeclContext();
16102 
16103   // Set the captured variables on the block.
16104   SmallVector<BlockDecl::Capture, 4> Captures;
16105   for (Capture &Cap : BSI->Captures) {
16106     if (Cap.isInvalid() || Cap.isThisCapture())
16107       continue;
16108 
16109     VarDecl *Var = Cap.getVariable();
16110     Expr *CopyExpr = nullptr;
16111     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16112       if (const RecordType *Record =
16113               Cap.getCaptureType()->getAs<RecordType>()) {
16114         // The capture logic needs the destructor, so make sure we mark it.
16115         // Usually this is unnecessary because most local variables have
16116         // their destructors marked at declaration time, but parameters are
16117         // an exception because it's technically only the call site that
16118         // actually requires the destructor.
16119         if (isa<ParmVarDecl>(Var))
16120           FinalizeVarWithDestructor(Var, Record);
16121 
16122         // Enter a separate potentially-evaluated context while building block
16123         // initializers to isolate their cleanups from those of the block
16124         // itself.
16125         // FIXME: Is this appropriate even when the block itself occurs in an
16126         // unevaluated operand?
16127         EnterExpressionEvaluationContext EvalContext(
16128             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16129 
16130         SourceLocation Loc = Cap.getLocation();
16131 
16132         ExprResult Result = BuildDeclarationNameExpr(
16133             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16134 
16135         // According to the blocks spec, the capture of a variable from
16136         // the stack requires a const copy constructor.  This is not true
16137         // of the copy/move done to move a __block variable to the heap.
16138         if (!Result.isInvalid() &&
16139             !Result.get()->getType().isConstQualified()) {
16140           Result = ImpCastExprToType(Result.get(),
16141                                      Result.get()->getType().withConst(),
16142                                      CK_NoOp, VK_LValue);
16143         }
16144 
16145         if (!Result.isInvalid()) {
16146           Result = PerformCopyInitialization(
16147               InitializedEntity::InitializeBlock(Var->getLocation(),
16148                                                  Cap.getCaptureType()),
16149               Loc, Result.get());
16150         }
16151 
16152         // Build a full-expression copy expression if initialization
16153         // succeeded and used a non-trivial constructor.  Recover from
16154         // errors by pretending that the copy isn't necessary.
16155         if (!Result.isInvalid() &&
16156             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16157                 ->isTrivial()) {
16158           Result = MaybeCreateExprWithCleanups(Result);
16159           CopyExpr = Result.get();
16160         }
16161       }
16162     }
16163 
16164     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16165                               CopyExpr);
16166     Captures.push_back(NewCap);
16167   }
16168   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16169 
16170   // Pop the block scope now but keep it alive to the end of this function.
16171   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16172   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16173 
16174   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16175 
16176   // If the block isn't obviously global, i.e. it captures anything at
16177   // all, then we need to do a few things in the surrounding context:
16178   if (Result->getBlockDecl()->hasCaptures()) {
16179     // First, this expression has a new cleanup object.
16180     ExprCleanupObjects.push_back(Result->getBlockDecl());
16181     Cleanup.setExprNeedsCleanups(true);
16182 
16183     // It also gets a branch-protected scope if any of the captured
16184     // variables needs destruction.
16185     for (const auto &CI : Result->getBlockDecl()->captures()) {
16186       const VarDecl *var = CI.getVariable();
16187       if (var->getType().isDestructedType() != QualType::DK_none) {
16188         setFunctionHasBranchProtectedScope();
16189         break;
16190       }
16191     }
16192   }
16193 
16194   if (getCurFunction())
16195     getCurFunction()->addBlock(BD);
16196 
16197   return Result;
16198 }
16199 
16200 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16201                             SourceLocation RPLoc) {
16202   TypeSourceInfo *TInfo;
16203   GetTypeFromParser(Ty, &TInfo);
16204   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16205 }
16206 
16207 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16208                                 Expr *E, TypeSourceInfo *TInfo,
16209                                 SourceLocation RPLoc) {
16210   Expr *OrigExpr = E;
16211   bool IsMS = false;
16212 
16213   // CUDA device code does not support varargs.
16214   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16215     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16216       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16217       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16218         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16219     }
16220   }
16221 
16222   // NVPTX does not support va_arg expression.
16223   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16224       Context.getTargetInfo().getTriple().isNVPTX())
16225     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16226 
16227   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16228   // as Microsoft ABI on an actual Microsoft platform, where
16229   // __builtin_ms_va_list and __builtin_va_list are the same.)
16230   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16231       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16232     QualType MSVaListType = Context.getBuiltinMSVaListType();
16233     if (Context.hasSameType(MSVaListType, E->getType())) {
16234       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16235         return ExprError();
16236       IsMS = true;
16237     }
16238   }
16239 
16240   // Get the va_list type
16241   QualType VaListType = Context.getBuiltinVaListType();
16242   if (!IsMS) {
16243     if (VaListType->isArrayType()) {
16244       // Deal with implicit array decay; for example, on x86-64,
16245       // va_list is an array, but it's supposed to decay to
16246       // a pointer for va_arg.
16247       VaListType = Context.getArrayDecayedType(VaListType);
16248       // Make sure the input expression also decays appropriately.
16249       ExprResult Result = UsualUnaryConversions(E);
16250       if (Result.isInvalid())
16251         return ExprError();
16252       E = Result.get();
16253     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16254       // If va_list is a record type and we are compiling in C++ mode,
16255       // check the argument using reference binding.
16256       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16257           Context, Context.getLValueReferenceType(VaListType), false);
16258       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16259       if (Init.isInvalid())
16260         return ExprError();
16261       E = Init.getAs<Expr>();
16262     } else {
16263       // Otherwise, the va_list argument must be an l-value because
16264       // it is modified by va_arg.
16265       if (!E->isTypeDependent() &&
16266           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16267         return ExprError();
16268     }
16269   }
16270 
16271   if (!IsMS && !E->isTypeDependent() &&
16272       !Context.hasSameType(VaListType, E->getType()))
16273     return ExprError(
16274         Diag(E->getBeginLoc(),
16275              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16276         << OrigExpr->getType() << E->getSourceRange());
16277 
16278   if (!TInfo->getType()->isDependentType()) {
16279     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16280                             diag::err_second_parameter_to_va_arg_incomplete,
16281                             TInfo->getTypeLoc()))
16282       return ExprError();
16283 
16284     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16285                                TInfo->getType(),
16286                                diag::err_second_parameter_to_va_arg_abstract,
16287                                TInfo->getTypeLoc()))
16288       return ExprError();
16289 
16290     if (!TInfo->getType().isPODType(Context)) {
16291       Diag(TInfo->getTypeLoc().getBeginLoc(),
16292            TInfo->getType()->isObjCLifetimeType()
16293              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16294              : diag::warn_second_parameter_to_va_arg_not_pod)
16295         << TInfo->getType()
16296         << TInfo->getTypeLoc().getSourceRange();
16297     }
16298 
16299     // Check for va_arg where arguments of the given type will be promoted
16300     // (i.e. this va_arg is guaranteed to have undefined behavior).
16301     QualType PromoteType;
16302     if (TInfo->getType()->isPromotableIntegerType()) {
16303       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16304       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16305       // and C2x 7.16.1.1p2 says, in part:
16306       //   If type is not compatible with the type of the actual next argument
16307       //   (as promoted according to the default argument promotions), the
16308       //   behavior is undefined, except for the following cases:
16309       //     - both types are pointers to qualified or unqualified versions of
16310       //       compatible types;
16311       //     - one type is a signed integer type, the other type is the
16312       //       corresponding unsigned integer type, and the value is
16313       //       representable in both types;
16314       //     - one type is pointer to qualified or unqualified void and the
16315       //       other is a pointer to a qualified or unqualified character type.
16316       // Given that type compatibility is the primary requirement (ignoring
16317       // qualifications), you would think we could call typesAreCompatible()
16318       // directly to test this. However, in C++, that checks for *same type*,
16319       // which causes false positives when passing an enumeration type to
16320       // va_arg. Instead, get the underlying type of the enumeration and pass
16321       // that.
16322       QualType UnderlyingType = TInfo->getType();
16323       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16324         UnderlyingType = ET->getDecl()->getIntegerType();
16325       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16326                                      /*CompareUnqualified*/ true))
16327         PromoteType = QualType();
16328 
16329       // If the types are still not compatible, we need to test whether the
16330       // promoted type and the underlying type are the same except for
16331       // signedness. Ask the AST for the correctly corresponding type and see
16332       // if that's compatible.
16333       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16334           PromoteType->isUnsignedIntegerType() !=
16335               UnderlyingType->isUnsignedIntegerType()) {
16336         UnderlyingType =
16337             UnderlyingType->isUnsignedIntegerType()
16338                 ? Context.getCorrespondingSignedType(UnderlyingType)
16339                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16340         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16341                                        /*CompareUnqualified*/ true))
16342           PromoteType = QualType();
16343       }
16344     }
16345     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16346       PromoteType = Context.DoubleTy;
16347     if (!PromoteType.isNull())
16348       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16349                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16350                           << TInfo->getType()
16351                           << PromoteType
16352                           << TInfo->getTypeLoc().getSourceRange());
16353   }
16354 
16355   QualType T = TInfo->getType().getNonLValueExprType(Context);
16356   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16357 }
16358 
16359 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16360   // The type of __null will be int or long, depending on the size of
16361   // pointers on the target.
16362   QualType Ty;
16363   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16364   if (pw == Context.getTargetInfo().getIntWidth())
16365     Ty = Context.IntTy;
16366   else if (pw == Context.getTargetInfo().getLongWidth())
16367     Ty = Context.LongTy;
16368   else if (pw == Context.getTargetInfo().getLongLongWidth())
16369     Ty = Context.LongLongTy;
16370   else {
16371     llvm_unreachable("I don't know size of pointer!");
16372   }
16373 
16374   return new (Context) GNUNullExpr(Ty, TokenLoc);
16375 }
16376 
16377 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16378   CXXRecordDecl *ImplDecl = nullptr;
16379 
16380   // Fetch the std::source_location::__impl decl.
16381   if (NamespaceDecl *Std = S.getStdNamespace()) {
16382     LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16383                           Loc, Sema::LookupOrdinaryName);
16384     if (S.LookupQualifiedName(ResultSL, Std)) {
16385       if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16386         LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16387                                 Loc, Sema::LookupOrdinaryName);
16388         if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16389             S.LookupQualifiedName(ResultImpl, SLDecl)) {
16390           ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16391         }
16392       }
16393     }
16394   }
16395 
16396   if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16397     S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16398     return nullptr;
16399   }
16400 
16401   // Verify that __impl is a trivial struct type, with no base classes, and with
16402   // only the four expected fields.
16403   if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16404       ImplDecl->getNumBases() != 0) {
16405     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16406     return nullptr;
16407   }
16408 
16409   unsigned Count = 0;
16410   for (FieldDecl *F : ImplDecl->fields()) {
16411     StringRef Name = F->getName();
16412 
16413     if (Name == "_M_file_name") {
16414       if (F->getType() !=
16415           S.Context.getPointerType(S.Context.CharTy.withConst()))
16416         break;
16417       Count++;
16418     } else if (Name == "_M_function_name") {
16419       if (F->getType() !=
16420           S.Context.getPointerType(S.Context.CharTy.withConst()))
16421         break;
16422       Count++;
16423     } else if (Name == "_M_line") {
16424       if (!F->getType()->isIntegerType())
16425         break;
16426       Count++;
16427     } else if (Name == "_M_column") {
16428       if (!F->getType()->isIntegerType())
16429         break;
16430       Count++;
16431     } else {
16432       Count = 100; // invalid
16433       break;
16434     }
16435   }
16436   if (Count != 4) {
16437     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16438     return nullptr;
16439   }
16440 
16441   return ImplDecl;
16442 }
16443 
16444 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16445                                     SourceLocation BuiltinLoc,
16446                                     SourceLocation RPLoc) {
16447   QualType ResultTy;
16448   switch (Kind) {
16449   case SourceLocExpr::File:
16450   case SourceLocExpr::Function: {
16451     QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16452     ResultTy =
16453         Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16454     break;
16455   }
16456   case SourceLocExpr::Line:
16457   case SourceLocExpr::Column:
16458     ResultTy = Context.UnsignedIntTy;
16459     break;
16460   case SourceLocExpr::SourceLocStruct:
16461     if (!StdSourceLocationImplDecl) {
16462       StdSourceLocationImplDecl =
16463           LookupStdSourceLocationImpl(*this, BuiltinLoc);
16464       if (!StdSourceLocationImplDecl)
16465         return ExprError();
16466     }
16467     ResultTy = Context.getPointerType(
16468         Context.getRecordType(StdSourceLocationImplDecl).withConst());
16469     break;
16470   }
16471 
16472   return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16473 }
16474 
16475 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16476                                     QualType ResultTy,
16477                                     SourceLocation BuiltinLoc,
16478                                     SourceLocation RPLoc,
16479                                     DeclContext *ParentContext) {
16480   return new (Context)
16481       SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16482 }
16483 
16484 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16485                                         bool Diagnose) {
16486   if (!getLangOpts().ObjC)
16487     return false;
16488 
16489   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16490   if (!PT)
16491     return false;
16492   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16493 
16494   // Ignore any parens, implicit casts (should only be
16495   // array-to-pointer decays), and not-so-opaque values.  The last is
16496   // important for making this trigger for property assignments.
16497   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16498   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16499     if (OV->getSourceExpr())
16500       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16501 
16502   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16503     if (!PT->isObjCIdType() &&
16504         !(ID && ID->getIdentifier()->isStr("NSString")))
16505       return false;
16506     if (!SL->isAscii())
16507       return false;
16508 
16509     if (Diagnose) {
16510       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16511           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16512       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16513     }
16514     return true;
16515   }
16516 
16517   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16518       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16519       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16520       !SrcExpr->isNullPointerConstant(
16521           getASTContext(), Expr::NPC_NeverValueDependent)) {
16522     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16523       return false;
16524     if (Diagnose) {
16525       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16526           << /*number*/1
16527           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16528       Expr *NumLit =
16529           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16530       if (NumLit)
16531         Exp = NumLit;
16532     }
16533     return true;
16534   }
16535 
16536   return false;
16537 }
16538 
16539 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16540                                               const Expr *SrcExpr) {
16541   if (!DstType->isFunctionPointerType() ||
16542       !SrcExpr->getType()->isFunctionType())
16543     return false;
16544 
16545   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16546   if (!DRE)
16547     return false;
16548 
16549   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16550   if (!FD)
16551     return false;
16552 
16553   return !S.checkAddressOfFunctionIsAvailable(FD,
16554                                               /*Complain=*/true,
16555                                               SrcExpr->getBeginLoc());
16556 }
16557 
16558 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16559                                     SourceLocation Loc,
16560                                     QualType DstType, QualType SrcType,
16561                                     Expr *SrcExpr, AssignmentAction Action,
16562                                     bool *Complained) {
16563   if (Complained)
16564     *Complained = false;
16565 
16566   // Decode the result (notice that AST's are still created for extensions).
16567   bool CheckInferredResultType = false;
16568   bool isInvalid = false;
16569   unsigned DiagKind = 0;
16570   ConversionFixItGenerator ConvHints;
16571   bool MayHaveConvFixit = false;
16572   bool MayHaveFunctionDiff = false;
16573   const ObjCInterfaceDecl *IFace = nullptr;
16574   const ObjCProtocolDecl *PDecl = nullptr;
16575 
16576   switch (ConvTy) {
16577   case Compatible:
16578       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16579       return false;
16580 
16581   case PointerToInt:
16582     if (getLangOpts().CPlusPlus) {
16583       DiagKind = diag::err_typecheck_convert_pointer_int;
16584       isInvalid = true;
16585     } else {
16586       DiagKind = diag::ext_typecheck_convert_pointer_int;
16587     }
16588     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16589     MayHaveConvFixit = true;
16590     break;
16591   case IntToPointer:
16592     if (getLangOpts().CPlusPlus) {
16593       DiagKind = diag::err_typecheck_convert_int_pointer;
16594       isInvalid = true;
16595     } else {
16596       DiagKind = diag::ext_typecheck_convert_int_pointer;
16597     }
16598     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16599     MayHaveConvFixit = true;
16600     break;
16601   case IncompatibleFunctionPointer:
16602     if (getLangOpts().CPlusPlus) {
16603       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16604       isInvalid = true;
16605     } else {
16606       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16607     }
16608     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16609     MayHaveConvFixit = true;
16610     break;
16611   case IncompatiblePointer:
16612     if (Action == AA_Passing_CFAudited) {
16613       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16614     } else if (getLangOpts().CPlusPlus) {
16615       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16616       isInvalid = true;
16617     } else {
16618       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16619     }
16620     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16621       SrcType->isObjCObjectPointerType();
16622     if (!CheckInferredResultType) {
16623       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16624     } else if (CheckInferredResultType) {
16625       SrcType = SrcType.getUnqualifiedType();
16626       DstType = DstType.getUnqualifiedType();
16627     }
16628     MayHaveConvFixit = true;
16629     break;
16630   case IncompatiblePointerSign:
16631     if (getLangOpts().CPlusPlus) {
16632       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16633       isInvalid = true;
16634     } else {
16635       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16636     }
16637     break;
16638   case FunctionVoidPointer:
16639     if (getLangOpts().CPlusPlus) {
16640       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16641       isInvalid = true;
16642     } else {
16643       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16644     }
16645     break;
16646   case IncompatiblePointerDiscardsQualifiers: {
16647     // Perform array-to-pointer decay if necessary.
16648     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16649 
16650     isInvalid = true;
16651 
16652     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16653     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16654     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16655       DiagKind = diag::err_typecheck_incompatible_address_space;
16656       break;
16657 
16658     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16659       DiagKind = diag::err_typecheck_incompatible_ownership;
16660       break;
16661     }
16662 
16663     llvm_unreachable("unknown error case for discarding qualifiers!");
16664     // fallthrough
16665   }
16666   case CompatiblePointerDiscardsQualifiers:
16667     // If the qualifiers lost were because we were applying the
16668     // (deprecated) C++ conversion from a string literal to a char*
16669     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16670     // Ideally, this check would be performed in
16671     // checkPointerTypesForAssignment. However, that would require a
16672     // bit of refactoring (so that the second argument is an
16673     // expression, rather than a type), which should be done as part
16674     // of a larger effort to fix checkPointerTypesForAssignment for
16675     // C++ semantics.
16676     if (getLangOpts().CPlusPlus &&
16677         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16678       return false;
16679     if (getLangOpts().CPlusPlus) {
16680       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16681       isInvalid = true;
16682     } else {
16683       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16684     }
16685 
16686     break;
16687   case IncompatibleNestedPointerQualifiers:
16688     if (getLangOpts().CPlusPlus) {
16689       isInvalid = true;
16690       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16691     } else {
16692       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16693     }
16694     break;
16695   case IncompatibleNestedPointerAddressSpaceMismatch:
16696     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16697     isInvalid = true;
16698     break;
16699   case IntToBlockPointer:
16700     DiagKind = diag::err_int_to_block_pointer;
16701     isInvalid = true;
16702     break;
16703   case IncompatibleBlockPointer:
16704     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16705     isInvalid = true;
16706     break;
16707   case IncompatibleObjCQualifiedId: {
16708     if (SrcType->isObjCQualifiedIdType()) {
16709       const ObjCObjectPointerType *srcOPT =
16710                 SrcType->castAs<ObjCObjectPointerType>();
16711       for (auto *srcProto : srcOPT->quals()) {
16712         PDecl = srcProto;
16713         break;
16714       }
16715       if (const ObjCInterfaceType *IFaceT =
16716             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16717         IFace = IFaceT->getDecl();
16718     }
16719     else if (DstType->isObjCQualifiedIdType()) {
16720       const ObjCObjectPointerType *dstOPT =
16721         DstType->castAs<ObjCObjectPointerType>();
16722       for (auto *dstProto : dstOPT->quals()) {
16723         PDecl = dstProto;
16724         break;
16725       }
16726       if (const ObjCInterfaceType *IFaceT =
16727             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16728         IFace = IFaceT->getDecl();
16729     }
16730     if (getLangOpts().CPlusPlus) {
16731       DiagKind = diag::err_incompatible_qualified_id;
16732       isInvalid = true;
16733     } else {
16734       DiagKind = diag::warn_incompatible_qualified_id;
16735     }
16736     break;
16737   }
16738   case IncompatibleVectors:
16739     if (getLangOpts().CPlusPlus) {
16740       DiagKind = diag::err_incompatible_vectors;
16741       isInvalid = true;
16742     } else {
16743       DiagKind = diag::warn_incompatible_vectors;
16744     }
16745     break;
16746   case IncompatibleObjCWeakRef:
16747     DiagKind = diag::err_arc_weak_unavailable_assign;
16748     isInvalid = true;
16749     break;
16750   case Incompatible:
16751     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16752       if (Complained)
16753         *Complained = true;
16754       return true;
16755     }
16756 
16757     DiagKind = diag::err_typecheck_convert_incompatible;
16758     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16759     MayHaveConvFixit = true;
16760     isInvalid = true;
16761     MayHaveFunctionDiff = true;
16762     break;
16763   }
16764 
16765   QualType FirstType, SecondType;
16766   switch (Action) {
16767   case AA_Assigning:
16768   case AA_Initializing:
16769     // The destination type comes first.
16770     FirstType = DstType;
16771     SecondType = SrcType;
16772     break;
16773 
16774   case AA_Returning:
16775   case AA_Passing:
16776   case AA_Passing_CFAudited:
16777   case AA_Converting:
16778   case AA_Sending:
16779   case AA_Casting:
16780     // The source type comes first.
16781     FirstType = SrcType;
16782     SecondType = DstType;
16783     break;
16784   }
16785 
16786   PartialDiagnostic FDiag = PDiag(DiagKind);
16787   if (Action == AA_Passing_CFAudited)
16788     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16789   else
16790     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16791 
16792   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16793       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16794     auto isPlainChar = [](const clang::Type *Type) {
16795       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16796              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16797     };
16798     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16799               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16800   }
16801 
16802   // If we can fix the conversion, suggest the FixIts.
16803   if (!ConvHints.isNull()) {
16804     for (FixItHint &H : ConvHints.Hints)
16805       FDiag << H;
16806   }
16807 
16808   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16809 
16810   if (MayHaveFunctionDiff)
16811     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16812 
16813   Diag(Loc, FDiag);
16814   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16815        DiagKind == diag::err_incompatible_qualified_id) &&
16816       PDecl && IFace && !IFace->hasDefinition())
16817     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16818         << IFace << PDecl;
16819 
16820   if (SecondType == Context.OverloadTy)
16821     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16822                               FirstType, /*TakingAddress=*/true);
16823 
16824   if (CheckInferredResultType)
16825     EmitRelatedResultTypeNote(SrcExpr);
16826 
16827   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16828     EmitRelatedResultTypeNoteForReturn(DstType);
16829 
16830   if (Complained)
16831     *Complained = true;
16832   return isInvalid;
16833 }
16834 
16835 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16836                                                  llvm::APSInt *Result,
16837                                                  AllowFoldKind CanFold) {
16838   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16839   public:
16840     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16841                                              QualType T) override {
16842       return S.Diag(Loc, diag::err_ice_not_integral)
16843              << T << S.LangOpts.CPlusPlus;
16844     }
16845     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16846       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16847     }
16848   } Diagnoser;
16849 
16850   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16851 }
16852 
16853 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16854                                                  llvm::APSInt *Result,
16855                                                  unsigned DiagID,
16856                                                  AllowFoldKind CanFold) {
16857   class IDDiagnoser : public VerifyICEDiagnoser {
16858     unsigned DiagID;
16859 
16860   public:
16861     IDDiagnoser(unsigned DiagID)
16862       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16863 
16864     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16865       return S.Diag(Loc, DiagID);
16866     }
16867   } Diagnoser(DiagID);
16868 
16869   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16870 }
16871 
16872 Sema::SemaDiagnosticBuilder
16873 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16874                                              QualType T) {
16875   return diagnoseNotICE(S, Loc);
16876 }
16877 
16878 Sema::SemaDiagnosticBuilder
16879 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16880   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16881 }
16882 
16883 ExprResult
16884 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16885                                       VerifyICEDiagnoser &Diagnoser,
16886                                       AllowFoldKind CanFold) {
16887   SourceLocation DiagLoc = E->getBeginLoc();
16888 
16889   if (getLangOpts().CPlusPlus11) {
16890     // C++11 [expr.const]p5:
16891     //   If an expression of literal class type is used in a context where an
16892     //   integral constant expression is required, then that class type shall
16893     //   have a single non-explicit conversion function to an integral or
16894     //   unscoped enumeration type
16895     ExprResult Converted;
16896     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16897       VerifyICEDiagnoser &BaseDiagnoser;
16898     public:
16899       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16900           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16901                                 BaseDiagnoser.Suppress, true),
16902             BaseDiagnoser(BaseDiagnoser) {}
16903 
16904       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16905                                            QualType T) override {
16906         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16907       }
16908 
16909       SemaDiagnosticBuilder diagnoseIncomplete(
16910           Sema &S, SourceLocation Loc, QualType T) override {
16911         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16912       }
16913 
16914       SemaDiagnosticBuilder diagnoseExplicitConv(
16915           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16916         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16917       }
16918 
16919       SemaDiagnosticBuilder noteExplicitConv(
16920           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16921         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16922                  << ConvTy->isEnumeralType() << ConvTy;
16923       }
16924 
16925       SemaDiagnosticBuilder diagnoseAmbiguous(
16926           Sema &S, SourceLocation Loc, QualType T) override {
16927         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16928       }
16929 
16930       SemaDiagnosticBuilder noteAmbiguous(
16931           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16932         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16933                  << ConvTy->isEnumeralType() << ConvTy;
16934       }
16935 
16936       SemaDiagnosticBuilder diagnoseConversion(
16937           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16938         llvm_unreachable("conversion functions are permitted");
16939       }
16940     } ConvertDiagnoser(Diagnoser);
16941 
16942     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16943                                                     ConvertDiagnoser);
16944     if (Converted.isInvalid())
16945       return Converted;
16946     E = Converted.get();
16947     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16948       return ExprError();
16949   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16950     // An ICE must be of integral or unscoped enumeration type.
16951     if (!Diagnoser.Suppress)
16952       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16953           << E->getSourceRange();
16954     return ExprError();
16955   }
16956 
16957   ExprResult RValueExpr = DefaultLvalueConversion(E);
16958   if (RValueExpr.isInvalid())
16959     return ExprError();
16960 
16961   E = RValueExpr.get();
16962 
16963   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16964   // in the non-ICE case.
16965   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16966     if (Result)
16967       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16968     if (!isa<ConstantExpr>(E))
16969       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16970                  : ConstantExpr::Create(Context, E);
16971     return E;
16972   }
16973 
16974   Expr::EvalResult EvalResult;
16975   SmallVector<PartialDiagnosticAt, 8> Notes;
16976   EvalResult.Diag = &Notes;
16977 
16978   // Try to evaluate the expression, and produce diagnostics explaining why it's
16979   // not a constant expression as a side-effect.
16980   bool Folded =
16981       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16982       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16983 
16984   if (!isa<ConstantExpr>(E))
16985     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16986 
16987   // In C++11, we can rely on diagnostics being produced for any expression
16988   // which is not a constant expression. If no diagnostics were produced, then
16989   // this is a constant expression.
16990   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16991     if (Result)
16992       *Result = EvalResult.Val.getInt();
16993     return E;
16994   }
16995 
16996   // If our only note is the usual "invalid subexpression" note, just point
16997   // the caret at its location rather than producing an essentially
16998   // redundant note.
16999   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17000         diag::note_invalid_subexpr_in_const_expr) {
17001     DiagLoc = Notes[0].first;
17002     Notes.clear();
17003   }
17004 
17005   if (!Folded || !CanFold) {
17006     if (!Diagnoser.Suppress) {
17007       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17008       for (const PartialDiagnosticAt &Note : Notes)
17009         Diag(Note.first, Note.second);
17010     }
17011 
17012     return ExprError();
17013   }
17014 
17015   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17016   for (const PartialDiagnosticAt &Note : Notes)
17017     Diag(Note.first, Note.second);
17018 
17019   if (Result)
17020     *Result = EvalResult.Val.getInt();
17021   return E;
17022 }
17023 
17024 namespace {
17025   // Handle the case where we conclude a expression which we speculatively
17026   // considered to be unevaluated is actually evaluated.
17027   class TransformToPE : public TreeTransform<TransformToPE> {
17028     typedef TreeTransform<TransformToPE> BaseTransform;
17029 
17030   public:
17031     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17032 
17033     // Make sure we redo semantic analysis
17034     bool AlwaysRebuild() { return true; }
17035     bool ReplacingOriginal() { return true; }
17036 
17037     // We need to special-case DeclRefExprs referring to FieldDecls which
17038     // are not part of a member pointer formation; normal TreeTransforming
17039     // doesn't catch this case because of the way we represent them in the AST.
17040     // FIXME: This is a bit ugly; is it really the best way to handle this
17041     // case?
17042     //
17043     // Error on DeclRefExprs referring to FieldDecls.
17044     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17045       if (isa<FieldDecl>(E->getDecl()) &&
17046           !SemaRef.isUnevaluatedContext())
17047         return SemaRef.Diag(E->getLocation(),
17048                             diag::err_invalid_non_static_member_use)
17049             << E->getDecl() << E->getSourceRange();
17050 
17051       return BaseTransform::TransformDeclRefExpr(E);
17052     }
17053 
17054     // Exception: filter out member pointer formation
17055     ExprResult TransformUnaryOperator(UnaryOperator *E) {
17056       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17057         return E;
17058 
17059       return BaseTransform::TransformUnaryOperator(E);
17060     }
17061 
17062     // The body of a lambda-expression is in a separate expression evaluation
17063     // context so never needs to be transformed.
17064     // FIXME: Ideally we wouldn't transform the closure type either, and would
17065     // just recreate the capture expressions and lambda expression.
17066     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17067       return SkipLambdaBody(E, Body);
17068     }
17069   };
17070 }
17071 
17072 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17073   assert(isUnevaluatedContext() &&
17074          "Should only transform unevaluated expressions");
17075   ExprEvalContexts.back().Context =
17076       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17077   if (isUnevaluatedContext())
17078     return E;
17079   return TransformToPE(*this).TransformExpr(E);
17080 }
17081 
17082 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17083   assert(isUnevaluatedContext() &&
17084          "Should only transform unevaluated expressions");
17085   ExprEvalContexts.back().Context =
17086       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17087   if (isUnevaluatedContext())
17088     return TInfo;
17089   return TransformToPE(*this).TransformType(TInfo);
17090 }
17091 
17092 void
17093 Sema::PushExpressionEvaluationContext(
17094     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17095     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17096   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17097                                 LambdaContextDecl, ExprContext);
17098 
17099   // Discarded statements and immediate contexts nested in other
17100   // discarded statements or immediate context are themselves
17101   // a discarded statement or an immediate context, respectively.
17102   ExprEvalContexts.back().InDiscardedStatement =
17103       ExprEvalContexts[ExprEvalContexts.size() - 2]
17104           .isDiscardedStatementContext();
17105   ExprEvalContexts.back().InImmediateFunctionContext =
17106       ExprEvalContexts[ExprEvalContexts.size() - 2]
17107           .isImmediateFunctionContext();
17108 
17109   Cleanup.reset();
17110   if (!MaybeODRUseExprs.empty())
17111     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17112 }
17113 
17114 void
17115 Sema::PushExpressionEvaluationContext(
17116     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17117     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17118   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17119   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17120 }
17121 
17122 namespace {
17123 
17124 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17125   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17126   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17127     if (E->getOpcode() == UO_Deref)
17128       return CheckPossibleDeref(S, E->getSubExpr());
17129   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17130     return CheckPossibleDeref(S, E->getBase());
17131   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17132     return CheckPossibleDeref(S, E->getBase());
17133   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17134     QualType Inner;
17135     QualType Ty = E->getType();
17136     if (const auto *Ptr = Ty->getAs<PointerType>())
17137       Inner = Ptr->getPointeeType();
17138     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17139       Inner = Arr->getElementType();
17140     else
17141       return nullptr;
17142 
17143     if (Inner->hasAttr(attr::NoDeref))
17144       return E;
17145   }
17146   return nullptr;
17147 }
17148 
17149 } // namespace
17150 
17151 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17152   for (const Expr *E : Rec.PossibleDerefs) {
17153     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17154     if (DeclRef) {
17155       const ValueDecl *Decl = DeclRef->getDecl();
17156       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17157           << Decl->getName() << E->getSourceRange();
17158       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17159     } else {
17160       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17161           << E->getSourceRange();
17162     }
17163   }
17164   Rec.PossibleDerefs.clear();
17165 }
17166 
17167 /// Check whether E, which is either a discarded-value expression or an
17168 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17169 /// and if so, remove it from the list of volatile-qualified assignments that
17170 /// we are going to warn are deprecated.
17171 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17172   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17173     return;
17174 
17175   // Note: ignoring parens here is not justified by the standard rules, but
17176   // ignoring parentheses seems like a more reasonable approach, and this only
17177   // drives a deprecation warning so doesn't affect conformance.
17178   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17179     if (BO->getOpcode() == BO_Assign) {
17180       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17181       llvm::erase_value(LHSs, BO->getLHS());
17182     }
17183   }
17184 }
17185 
17186 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17187   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17188       !Decl->isConsteval() || isConstantEvaluated() ||
17189       RebuildingImmediateInvocation || isImmediateFunctionContext())
17190     return E;
17191 
17192   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17193   /// It's OK if this fails; we'll also remove this in
17194   /// HandleImmediateInvocations, but catching it here allows us to avoid
17195   /// walking the AST looking for it in simple cases.
17196   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17197     if (auto *DeclRef =
17198             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17199       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17200 
17201   E = MaybeCreateExprWithCleanups(E);
17202 
17203   ConstantExpr *Res = ConstantExpr::Create(
17204       getASTContext(), E.get(),
17205       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17206                                    getASTContext()),
17207       /*IsImmediateInvocation*/ true);
17208   /// Value-dependent constant expressions should not be immediately
17209   /// evaluated until they are instantiated.
17210   if (!Res->isValueDependent())
17211     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17212   return Res;
17213 }
17214 
17215 static void EvaluateAndDiagnoseImmediateInvocation(
17216     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17217   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17218   Expr::EvalResult Eval;
17219   Eval.Diag = &Notes;
17220   ConstantExpr *CE = Candidate.getPointer();
17221   bool Result = CE->EvaluateAsConstantExpr(
17222       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17223   if (!Result || !Notes.empty()) {
17224     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17225     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17226       InnerExpr = FunctionalCast->getSubExpr();
17227     FunctionDecl *FD = nullptr;
17228     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17229       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17230     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17231       FD = Call->getConstructor();
17232     else
17233       llvm_unreachable("unhandled decl kind");
17234     assert(FD->isConsteval());
17235     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17236     for (auto &Note : Notes)
17237       SemaRef.Diag(Note.first, Note.second);
17238     return;
17239   }
17240   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17241 }
17242 
17243 static void RemoveNestedImmediateInvocation(
17244     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17245     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17246   struct ComplexRemove : TreeTransform<ComplexRemove> {
17247     using Base = TreeTransform<ComplexRemove>;
17248     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17249     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17250     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17251         CurrentII;
17252     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17253                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17254                   SmallVector<Sema::ImmediateInvocationCandidate,
17255                               4>::reverse_iterator Current)
17256         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17257     void RemoveImmediateInvocation(ConstantExpr* E) {
17258       auto It = std::find_if(CurrentII, IISet.rend(),
17259                              [E](Sema::ImmediateInvocationCandidate Elem) {
17260                                return Elem.getPointer() == E;
17261                              });
17262       assert(It != IISet.rend() &&
17263              "ConstantExpr marked IsImmediateInvocation should "
17264              "be present");
17265       It->setInt(1); // Mark as deleted
17266     }
17267     ExprResult TransformConstantExpr(ConstantExpr *E) {
17268       if (!E->isImmediateInvocation())
17269         return Base::TransformConstantExpr(E);
17270       RemoveImmediateInvocation(E);
17271       return Base::TransformExpr(E->getSubExpr());
17272     }
17273     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17274     /// we need to remove its DeclRefExpr from the DRSet.
17275     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17276       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17277       return Base::TransformCXXOperatorCallExpr(E);
17278     }
17279     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17280     /// here.
17281     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17282       if (!Init)
17283         return Init;
17284       /// ConstantExpr are the first layer of implicit node to be removed so if
17285       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17286       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17287         if (CE->isImmediateInvocation())
17288           RemoveImmediateInvocation(CE);
17289       return Base::TransformInitializer(Init, NotCopyInit);
17290     }
17291     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17292       DRSet.erase(E);
17293       return E;
17294     }
17295     bool AlwaysRebuild() { return false; }
17296     bool ReplacingOriginal() { return true; }
17297     bool AllowSkippingCXXConstructExpr() {
17298       bool Res = AllowSkippingFirstCXXConstructExpr;
17299       AllowSkippingFirstCXXConstructExpr = true;
17300       return Res;
17301     }
17302     bool AllowSkippingFirstCXXConstructExpr = true;
17303   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17304                 Rec.ImmediateInvocationCandidates, It);
17305 
17306   /// CXXConstructExpr with a single argument are getting skipped by
17307   /// TreeTransform in some situtation because they could be implicit. This
17308   /// can only occur for the top-level CXXConstructExpr because it is used
17309   /// nowhere in the expression being transformed therefore will not be rebuilt.
17310   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17311   /// skipping the first CXXConstructExpr.
17312   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17313     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17314 
17315   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17316   assert(Res.isUsable());
17317   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17318   It->getPointer()->setSubExpr(Res.get());
17319 }
17320 
17321 static void
17322 HandleImmediateInvocations(Sema &SemaRef,
17323                            Sema::ExpressionEvaluationContextRecord &Rec) {
17324   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17325        Rec.ReferenceToConsteval.size() == 0) ||
17326       SemaRef.RebuildingImmediateInvocation)
17327     return;
17328 
17329   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17330   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17331   /// need to remove ReferenceToConsteval in the immediate invocation.
17332   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17333 
17334     /// Prevent sema calls during the tree transform from adding pointers that
17335     /// are already in the sets.
17336     llvm::SaveAndRestore<bool> DisableIITracking(
17337         SemaRef.RebuildingImmediateInvocation, true);
17338 
17339     /// Prevent diagnostic during tree transfrom as they are duplicates
17340     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17341 
17342     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17343          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17344       if (!It->getInt())
17345         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17346   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17347              Rec.ReferenceToConsteval.size()) {
17348     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17349       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17350       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17351       bool VisitDeclRefExpr(DeclRefExpr *E) {
17352         DRSet.erase(E);
17353         return DRSet.size();
17354       }
17355     } Visitor(Rec.ReferenceToConsteval);
17356     Visitor.TraverseStmt(
17357         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17358   }
17359   for (auto CE : Rec.ImmediateInvocationCandidates)
17360     if (!CE.getInt())
17361       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17362   for (auto DR : Rec.ReferenceToConsteval) {
17363     auto *FD = cast<FunctionDecl>(DR->getDecl());
17364     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17365         << FD;
17366     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17367   }
17368 }
17369 
17370 void Sema::PopExpressionEvaluationContext() {
17371   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17372   unsigned NumTypos = Rec.NumTypos;
17373 
17374   if (!Rec.Lambdas.empty()) {
17375     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17376     if (!getLangOpts().CPlusPlus20 &&
17377         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17378          Rec.isUnevaluated() ||
17379          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17380       unsigned D;
17381       if (Rec.isUnevaluated()) {
17382         // C++11 [expr.prim.lambda]p2:
17383         //   A lambda-expression shall not appear in an unevaluated operand
17384         //   (Clause 5).
17385         D = diag::err_lambda_unevaluated_operand;
17386       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17387         // C++1y [expr.const]p2:
17388         //   A conditional-expression e is a core constant expression unless the
17389         //   evaluation of e, following the rules of the abstract machine, would
17390         //   evaluate [...] a lambda-expression.
17391         D = diag::err_lambda_in_constant_expression;
17392       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17393         // C++17 [expr.prim.lamda]p2:
17394         // A lambda-expression shall not appear [...] in a template-argument.
17395         D = diag::err_lambda_in_invalid_context;
17396       } else
17397         llvm_unreachable("Couldn't infer lambda error message.");
17398 
17399       for (const auto *L : Rec.Lambdas)
17400         Diag(L->getBeginLoc(), D);
17401     }
17402   }
17403 
17404   WarnOnPendingNoDerefs(Rec);
17405   HandleImmediateInvocations(*this, Rec);
17406 
17407   // Warn on any volatile-qualified simple-assignments that are not discarded-
17408   // value expressions nor unevaluated operands (those cases get removed from
17409   // this list by CheckUnusedVolatileAssignment).
17410   for (auto *BO : Rec.VolatileAssignmentLHSs)
17411     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17412         << BO->getType();
17413 
17414   // When are coming out of an unevaluated context, clear out any
17415   // temporaries that we may have created as part of the evaluation of
17416   // the expression in that context: they aren't relevant because they
17417   // will never be constructed.
17418   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17419     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17420                              ExprCleanupObjects.end());
17421     Cleanup = Rec.ParentCleanup;
17422     CleanupVarDeclMarking();
17423     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17424   // Otherwise, merge the contexts together.
17425   } else {
17426     Cleanup.mergeFrom(Rec.ParentCleanup);
17427     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17428                             Rec.SavedMaybeODRUseExprs.end());
17429   }
17430 
17431   // Pop the current expression evaluation context off the stack.
17432   ExprEvalContexts.pop_back();
17433 
17434   // The global expression evaluation context record is never popped.
17435   ExprEvalContexts.back().NumTypos += NumTypos;
17436 }
17437 
17438 void Sema::DiscardCleanupsInEvaluationContext() {
17439   ExprCleanupObjects.erase(
17440          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17441          ExprCleanupObjects.end());
17442   Cleanup.reset();
17443   MaybeODRUseExprs.clear();
17444 }
17445 
17446 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17447   ExprResult Result = CheckPlaceholderExpr(E);
17448   if (Result.isInvalid())
17449     return ExprError();
17450   E = Result.get();
17451   if (!E->getType()->isVariablyModifiedType())
17452     return E;
17453   return TransformToPotentiallyEvaluated(E);
17454 }
17455 
17456 /// Are we in a context that is potentially constant evaluated per C++20
17457 /// [expr.const]p12?
17458 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17459   /// C++2a [expr.const]p12:
17460   //   An expression or conversion is potentially constant evaluated if it is
17461   switch (SemaRef.ExprEvalContexts.back().Context) {
17462     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17463     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17464 
17465       // -- a manifestly constant-evaluated expression,
17466     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17467     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17468     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17469       // -- a potentially-evaluated expression,
17470     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17471       // -- an immediate subexpression of a braced-init-list,
17472 
17473       // -- [FIXME] an expression of the form & cast-expression that occurs
17474       //    within a templated entity
17475       // -- a subexpression of one of the above that is not a subexpression of
17476       // a nested unevaluated operand.
17477       return true;
17478 
17479     case Sema::ExpressionEvaluationContext::Unevaluated:
17480     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17481       // Expressions in this context are never evaluated.
17482       return false;
17483   }
17484   llvm_unreachable("Invalid context");
17485 }
17486 
17487 /// Return true if this function has a calling convention that requires mangling
17488 /// in the size of the parameter pack.
17489 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17490   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17491   // we don't need parameter type sizes.
17492   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17493   if (!TT.isOSWindows() || !TT.isX86())
17494     return false;
17495 
17496   // If this is C++ and this isn't an extern "C" function, parameters do not
17497   // need to be complete. In this case, C++ mangling will apply, which doesn't
17498   // use the size of the parameters.
17499   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17500     return false;
17501 
17502   // Stdcall, fastcall, and vectorcall need this special treatment.
17503   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17504   switch (CC) {
17505   case CC_X86StdCall:
17506   case CC_X86FastCall:
17507   case CC_X86VectorCall:
17508     return true;
17509   default:
17510     break;
17511   }
17512   return false;
17513 }
17514 
17515 /// Require that all of the parameter types of function be complete. Normally,
17516 /// parameter types are only required to be complete when a function is called
17517 /// or defined, but to mangle functions with certain calling conventions, the
17518 /// mangler needs to know the size of the parameter list. In this situation,
17519 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17520 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17521 /// result in a linker error. Clang doesn't implement this behavior, and instead
17522 /// attempts to error at compile time.
17523 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17524                                                   SourceLocation Loc) {
17525   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17526     FunctionDecl *FD;
17527     ParmVarDecl *Param;
17528 
17529   public:
17530     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17531         : FD(FD), Param(Param) {}
17532 
17533     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17534       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17535       StringRef CCName;
17536       switch (CC) {
17537       case CC_X86StdCall:
17538         CCName = "stdcall";
17539         break;
17540       case CC_X86FastCall:
17541         CCName = "fastcall";
17542         break;
17543       case CC_X86VectorCall:
17544         CCName = "vectorcall";
17545         break;
17546       default:
17547         llvm_unreachable("CC does not need mangling");
17548       }
17549 
17550       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17551           << Param->getDeclName() << FD->getDeclName() << CCName;
17552     }
17553   };
17554 
17555   for (ParmVarDecl *Param : FD->parameters()) {
17556     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17557     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17558   }
17559 }
17560 
17561 namespace {
17562 enum class OdrUseContext {
17563   /// Declarations in this context are not odr-used.
17564   None,
17565   /// Declarations in this context are formally odr-used, but this is a
17566   /// dependent context.
17567   Dependent,
17568   /// Declarations in this context are odr-used but not actually used (yet).
17569   FormallyOdrUsed,
17570   /// Declarations in this context are used.
17571   Used
17572 };
17573 }
17574 
17575 /// Are we within a context in which references to resolved functions or to
17576 /// variables result in odr-use?
17577 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17578   OdrUseContext Result;
17579 
17580   switch (SemaRef.ExprEvalContexts.back().Context) {
17581     case Sema::ExpressionEvaluationContext::Unevaluated:
17582     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17583     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17584       return OdrUseContext::None;
17585 
17586     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17587     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17588     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17589       Result = OdrUseContext::Used;
17590       break;
17591 
17592     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17593       Result = OdrUseContext::FormallyOdrUsed;
17594       break;
17595 
17596     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17597       // A default argument formally results in odr-use, but doesn't actually
17598       // result in a use in any real sense until it itself is used.
17599       Result = OdrUseContext::FormallyOdrUsed;
17600       break;
17601   }
17602 
17603   if (SemaRef.CurContext->isDependentContext())
17604     return OdrUseContext::Dependent;
17605 
17606   return Result;
17607 }
17608 
17609 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17610   if (!Func->isConstexpr())
17611     return false;
17612 
17613   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17614     return true;
17615   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17616   return CCD && CCD->getInheritedConstructor();
17617 }
17618 
17619 /// Mark a function referenced, and check whether it is odr-used
17620 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17621 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17622                                   bool MightBeOdrUse) {
17623   assert(Func && "No function?");
17624 
17625   Func->setReferenced();
17626 
17627   // Recursive functions aren't really used until they're used from some other
17628   // context.
17629   bool IsRecursiveCall = CurContext == Func;
17630 
17631   // C++11 [basic.def.odr]p3:
17632   //   A function whose name appears as a potentially-evaluated expression is
17633   //   odr-used if it is the unique lookup result or the selected member of a
17634   //   set of overloaded functions [...].
17635   //
17636   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17637   // can just check that here.
17638   OdrUseContext OdrUse =
17639       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17640   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17641     OdrUse = OdrUseContext::FormallyOdrUsed;
17642 
17643   // Trivial default constructors and destructors are never actually used.
17644   // FIXME: What about other special members?
17645   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17646       OdrUse == OdrUseContext::Used) {
17647     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17648       if (Constructor->isDefaultConstructor())
17649         OdrUse = OdrUseContext::FormallyOdrUsed;
17650     if (isa<CXXDestructorDecl>(Func))
17651       OdrUse = OdrUseContext::FormallyOdrUsed;
17652   }
17653 
17654   // C++20 [expr.const]p12:
17655   //   A function [...] is needed for constant evaluation if it is [...] a
17656   //   constexpr function that is named by an expression that is potentially
17657   //   constant evaluated
17658   bool NeededForConstantEvaluation =
17659       isPotentiallyConstantEvaluatedContext(*this) &&
17660       isImplicitlyDefinableConstexprFunction(Func);
17661 
17662   // Determine whether we require a function definition to exist, per
17663   // C++11 [temp.inst]p3:
17664   //   Unless a function template specialization has been explicitly
17665   //   instantiated or explicitly specialized, the function template
17666   //   specialization is implicitly instantiated when the specialization is
17667   //   referenced in a context that requires a function definition to exist.
17668   // C++20 [temp.inst]p7:
17669   //   The existence of a definition of a [...] function is considered to
17670   //   affect the semantics of the program if the [...] function is needed for
17671   //   constant evaluation by an expression
17672   // C++20 [basic.def.odr]p10:
17673   //   Every program shall contain exactly one definition of every non-inline
17674   //   function or variable that is odr-used in that program outside of a
17675   //   discarded statement
17676   // C++20 [special]p1:
17677   //   The implementation will implicitly define [defaulted special members]
17678   //   if they are odr-used or needed for constant evaluation.
17679   //
17680   // Note that we skip the implicit instantiation of templates that are only
17681   // used in unused default arguments or by recursive calls to themselves.
17682   // This is formally non-conforming, but seems reasonable in practice.
17683   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17684                                              NeededForConstantEvaluation);
17685 
17686   // C++14 [temp.expl.spec]p6:
17687   //   If a template [...] is explicitly specialized then that specialization
17688   //   shall be declared before the first use of that specialization that would
17689   //   cause an implicit instantiation to take place, in every translation unit
17690   //   in which such a use occurs
17691   if (NeedDefinition &&
17692       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17693        Func->getMemberSpecializationInfo()))
17694     checkSpecializationVisibility(Loc, Func);
17695 
17696   if (getLangOpts().CUDA)
17697     CheckCUDACall(Loc, Func);
17698 
17699   if (getLangOpts().SYCLIsDevice)
17700     checkSYCLDeviceFunction(Loc, Func);
17701 
17702   // If we need a definition, try to create one.
17703   if (NeedDefinition && !Func->getBody()) {
17704     runWithSufficientStackSpace(Loc, [&] {
17705       if (CXXConstructorDecl *Constructor =
17706               dyn_cast<CXXConstructorDecl>(Func)) {
17707         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17708         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17709           if (Constructor->isDefaultConstructor()) {
17710             if (Constructor->isTrivial() &&
17711                 !Constructor->hasAttr<DLLExportAttr>())
17712               return;
17713             DefineImplicitDefaultConstructor(Loc, Constructor);
17714           } else if (Constructor->isCopyConstructor()) {
17715             DefineImplicitCopyConstructor(Loc, Constructor);
17716           } else if (Constructor->isMoveConstructor()) {
17717             DefineImplicitMoveConstructor(Loc, Constructor);
17718           }
17719         } else if (Constructor->getInheritedConstructor()) {
17720           DefineInheritingConstructor(Loc, Constructor);
17721         }
17722       } else if (CXXDestructorDecl *Destructor =
17723                      dyn_cast<CXXDestructorDecl>(Func)) {
17724         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17725         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17726           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17727             return;
17728           DefineImplicitDestructor(Loc, Destructor);
17729         }
17730         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17731           MarkVTableUsed(Loc, Destructor->getParent());
17732       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17733         if (MethodDecl->isOverloadedOperator() &&
17734             MethodDecl->getOverloadedOperator() == OO_Equal) {
17735           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17736           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17737             if (MethodDecl->isCopyAssignmentOperator())
17738               DefineImplicitCopyAssignment(Loc, MethodDecl);
17739             else if (MethodDecl->isMoveAssignmentOperator())
17740               DefineImplicitMoveAssignment(Loc, MethodDecl);
17741           }
17742         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17743                    MethodDecl->getParent()->isLambda()) {
17744           CXXConversionDecl *Conversion =
17745               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17746           if (Conversion->isLambdaToBlockPointerConversion())
17747             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17748           else
17749             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17750         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17751           MarkVTableUsed(Loc, MethodDecl->getParent());
17752       }
17753 
17754       if (Func->isDefaulted() && !Func->isDeleted()) {
17755         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17756         if (DCK != DefaultedComparisonKind::None)
17757           DefineDefaultedComparison(Loc, Func, DCK);
17758       }
17759 
17760       // Implicit instantiation of function templates and member functions of
17761       // class templates.
17762       if (Func->isImplicitlyInstantiable()) {
17763         TemplateSpecializationKind TSK =
17764             Func->getTemplateSpecializationKindForInstantiation();
17765         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17766         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17767         if (FirstInstantiation) {
17768           PointOfInstantiation = Loc;
17769           if (auto *MSI = Func->getMemberSpecializationInfo())
17770             MSI->setPointOfInstantiation(Loc);
17771             // FIXME: Notify listener.
17772           else
17773             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17774         } else if (TSK != TSK_ImplicitInstantiation) {
17775           // Use the point of use as the point of instantiation, instead of the
17776           // point of explicit instantiation (which we track as the actual point
17777           // of instantiation). This gives better backtraces in diagnostics.
17778           PointOfInstantiation = Loc;
17779         }
17780 
17781         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17782             Func->isConstexpr()) {
17783           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17784               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17785               CodeSynthesisContexts.size())
17786             PendingLocalImplicitInstantiations.push_back(
17787                 std::make_pair(Func, PointOfInstantiation));
17788           else if (Func->isConstexpr())
17789             // Do not defer instantiations of constexpr functions, to avoid the
17790             // expression evaluator needing to call back into Sema if it sees a
17791             // call to such a function.
17792             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17793           else {
17794             Func->setInstantiationIsPending(true);
17795             PendingInstantiations.push_back(
17796                 std::make_pair(Func, PointOfInstantiation));
17797             // Notify the consumer that a function was implicitly instantiated.
17798             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17799           }
17800         }
17801       } else {
17802         // Walk redefinitions, as some of them may be instantiable.
17803         for (auto i : Func->redecls()) {
17804           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17805             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17806         }
17807       }
17808     });
17809   }
17810 
17811   // C++14 [except.spec]p17:
17812   //   An exception-specification is considered to be needed when:
17813   //   - the function is odr-used or, if it appears in an unevaluated operand,
17814   //     would be odr-used if the expression were potentially-evaluated;
17815   //
17816   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17817   // function is a pure virtual function we're calling, and in that case the
17818   // function was selected by overload resolution and we need to resolve its
17819   // exception specification for a different reason.
17820   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17821   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17822     ResolveExceptionSpec(Loc, FPT);
17823 
17824   // If this is the first "real" use, act on that.
17825   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17826     // Keep track of used but undefined functions.
17827     if (!Func->isDefined()) {
17828       if (mightHaveNonExternalLinkage(Func))
17829         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17830       else if (Func->getMostRecentDecl()->isInlined() &&
17831                !LangOpts.GNUInline &&
17832                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17833         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17834       else if (isExternalWithNoLinkageType(Func))
17835         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17836     }
17837 
17838     // Some x86 Windows calling conventions mangle the size of the parameter
17839     // pack into the name. Computing the size of the parameters requires the
17840     // parameter types to be complete. Check that now.
17841     if (funcHasParameterSizeMangling(*this, Func))
17842       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17843 
17844     // In the MS C++ ABI, the compiler emits destructor variants where they are
17845     // used. If the destructor is used here but defined elsewhere, mark the
17846     // virtual base destructors referenced. If those virtual base destructors
17847     // are inline, this will ensure they are defined when emitting the complete
17848     // destructor variant. This checking may be redundant if the destructor is
17849     // provided later in this TU.
17850     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17851       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17852         CXXRecordDecl *Parent = Dtor->getParent();
17853         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17854           CheckCompleteDestructorVariant(Loc, Dtor);
17855       }
17856     }
17857 
17858     Func->markUsed(Context);
17859   }
17860 }
17861 
17862 /// Directly mark a variable odr-used. Given a choice, prefer to use
17863 /// MarkVariableReferenced since it does additional checks and then
17864 /// calls MarkVarDeclODRUsed.
17865 /// If the variable must be captured:
17866 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17867 ///  - else capture it in the DeclContext that maps to the
17868 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17869 static void
17870 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17871                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17872   // Keep track of used but undefined variables.
17873   // FIXME: We shouldn't suppress this warning for static data members.
17874   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17875       (!Var->isExternallyVisible() || Var->isInline() ||
17876        SemaRef.isExternalWithNoLinkageType(Var)) &&
17877       !(Var->isStaticDataMember() && Var->hasInit())) {
17878     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17879     if (old.isInvalid())
17880       old = Loc;
17881   }
17882   QualType CaptureType, DeclRefType;
17883   if (SemaRef.LangOpts.OpenMP)
17884     SemaRef.tryCaptureOpenMPLambdas(Var);
17885   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17886     /*EllipsisLoc*/ SourceLocation(),
17887     /*BuildAndDiagnose*/ true,
17888     CaptureType, DeclRefType,
17889     FunctionScopeIndexToStopAt);
17890 
17891   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
17892     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17893     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17894     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17895     if (VarTarget == Sema::CVT_Host &&
17896         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17897          UserTarget == Sema::CFT_Global)) {
17898       // Diagnose ODR-use of host global variables in device functions.
17899       // Reference of device global variables in host functions is allowed
17900       // through shadow variables therefore it is not diagnosed.
17901       if (SemaRef.LangOpts.CUDAIsDevice) {
17902         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17903             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17904         SemaRef.targetDiag(Var->getLocation(),
17905                            Var->getType().isConstQualified()
17906                                ? diag::note_cuda_const_var_unpromoted
17907                                : diag::note_cuda_host_var);
17908       }
17909     } else if (VarTarget == Sema::CVT_Device &&
17910                (UserTarget == Sema::CFT_Host ||
17911                 UserTarget == Sema::CFT_HostDevice) &&
17912                !Var->hasExternalStorage()) {
17913       // Record a CUDA/HIP device side variable if it is ODR-used
17914       // by host code. This is done conservatively, when the variable is
17915       // referenced in any of the following contexts:
17916       //   - a non-function context
17917       //   - a host function
17918       //   - a host device function
17919       // This makes the ODR-use of the device side variable by host code to
17920       // be visible in the device compilation for the compiler to be able to
17921       // emit template variables instantiated by host code only and to
17922       // externalize the static device side variable ODR-used by host code.
17923       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17924     }
17925   }
17926 
17927   Var->markUsed(SemaRef.Context);
17928 }
17929 
17930 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17931                                              SourceLocation Loc,
17932                                              unsigned CapturingScopeIndex) {
17933   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17934 }
17935 
17936 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17937                                                ValueDecl *var) {
17938   DeclContext *VarDC = var->getDeclContext();
17939 
17940   //  If the parameter still belongs to the translation unit, then
17941   //  we're actually just using one parameter in the declaration of
17942   //  the next.
17943   if (isa<ParmVarDecl>(var) &&
17944       isa<TranslationUnitDecl>(VarDC))
17945     return;
17946 
17947   // For C code, don't diagnose about capture if we're not actually in code
17948   // right now; it's impossible to write a non-constant expression outside of
17949   // function context, so we'll get other (more useful) diagnostics later.
17950   //
17951   // For C++, things get a bit more nasty... it would be nice to suppress this
17952   // diagnostic for certain cases like using a local variable in an array bound
17953   // for a member of a local class, but the correct predicate is not obvious.
17954   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17955     return;
17956 
17957   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17958   unsigned ContextKind = 3; // unknown
17959   if (isa<CXXMethodDecl>(VarDC) &&
17960       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17961     ContextKind = 2;
17962   } else if (isa<FunctionDecl>(VarDC)) {
17963     ContextKind = 0;
17964   } else if (isa<BlockDecl>(VarDC)) {
17965     ContextKind = 1;
17966   }
17967 
17968   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17969     << var << ValueKind << ContextKind << VarDC;
17970   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17971       << var;
17972 
17973   // FIXME: Add additional diagnostic info about class etc. which prevents
17974   // capture.
17975 }
17976 
17977 
17978 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17979                                       bool &SubCapturesAreNested,
17980                                       QualType &CaptureType,
17981                                       QualType &DeclRefType) {
17982    // Check whether we've already captured it.
17983   if (CSI->CaptureMap.count(Var)) {
17984     // If we found a capture, any subcaptures are nested.
17985     SubCapturesAreNested = true;
17986 
17987     // Retrieve the capture type for this variable.
17988     CaptureType = CSI->getCapture(Var).getCaptureType();
17989 
17990     // Compute the type of an expression that refers to this variable.
17991     DeclRefType = CaptureType.getNonReferenceType();
17992 
17993     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17994     // are mutable in the sense that user can change their value - they are
17995     // private instances of the captured declarations.
17996     const Capture &Cap = CSI->getCapture(Var);
17997     if (Cap.isCopyCapture() &&
17998         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17999         !(isa<CapturedRegionScopeInfo>(CSI) &&
18000           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18001       DeclRefType.addConst();
18002     return true;
18003   }
18004   return false;
18005 }
18006 
18007 // Only block literals, captured statements, and lambda expressions can
18008 // capture; other scopes don't work.
18009 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18010                                  SourceLocation Loc,
18011                                  const bool Diagnose, Sema &S) {
18012   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18013     return getLambdaAwareParentOfDeclContext(DC);
18014   else if (Var->hasLocalStorage()) {
18015     if (Diagnose)
18016        diagnoseUncapturableValueReference(S, Loc, Var);
18017   }
18018   return nullptr;
18019 }
18020 
18021 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18022 // certain types of variables (unnamed, variably modified types etc.)
18023 // so check for eligibility.
18024 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18025                                  SourceLocation Loc,
18026                                  const bool Diagnose, Sema &S) {
18027 
18028   bool IsBlock = isa<BlockScopeInfo>(CSI);
18029   bool IsLambda = isa<LambdaScopeInfo>(CSI);
18030 
18031   // Lambdas are not allowed to capture unnamed variables
18032   // (e.g. anonymous unions).
18033   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18034   // assuming that's the intent.
18035   if (IsLambda && !Var->getDeclName()) {
18036     if (Diagnose) {
18037       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18038       S.Diag(Var->getLocation(), diag::note_declared_at);
18039     }
18040     return false;
18041   }
18042 
18043   // Prohibit variably-modified types in blocks; they're difficult to deal with.
18044   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18045     if (Diagnose) {
18046       S.Diag(Loc, diag::err_ref_vm_type);
18047       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18048     }
18049     return false;
18050   }
18051   // Prohibit structs with flexible array members too.
18052   // We cannot capture what is in the tail end of the struct.
18053   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18054     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18055       if (Diagnose) {
18056         if (IsBlock)
18057           S.Diag(Loc, diag::err_ref_flexarray_type);
18058         else
18059           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18060         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18061       }
18062       return false;
18063     }
18064   }
18065   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18066   // Lambdas and captured statements are not allowed to capture __block
18067   // variables; they don't support the expected semantics.
18068   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18069     if (Diagnose) {
18070       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18071       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18072     }
18073     return false;
18074   }
18075   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18076   if (S.getLangOpts().OpenCL && IsBlock &&
18077       Var->getType()->isBlockPointerType()) {
18078     if (Diagnose)
18079       S.Diag(Loc, diag::err_opencl_block_ref_block);
18080     return false;
18081   }
18082 
18083   return true;
18084 }
18085 
18086 // Returns true if the capture by block was successful.
18087 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18088                                  SourceLocation Loc,
18089                                  const bool BuildAndDiagnose,
18090                                  QualType &CaptureType,
18091                                  QualType &DeclRefType,
18092                                  const bool Nested,
18093                                  Sema &S, bool Invalid) {
18094   bool ByRef = false;
18095 
18096   // Blocks are not allowed to capture arrays, excepting OpenCL.
18097   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18098   // (decayed to pointers).
18099   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18100     if (BuildAndDiagnose) {
18101       S.Diag(Loc, diag::err_ref_array_type);
18102       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18103       Invalid = true;
18104     } else {
18105       return false;
18106     }
18107   }
18108 
18109   // Forbid the block-capture of autoreleasing variables.
18110   if (!Invalid &&
18111       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18112     if (BuildAndDiagnose) {
18113       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18114         << /*block*/ 0;
18115       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18116       Invalid = true;
18117     } else {
18118       return false;
18119     }
18120   }
18121 
18122   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18123   if (const auto *PT = CaptureType->getAs<PointerType>()) {
18124     QualType PointeeTy = PT->getPointeeType();
18125 
18126     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18127         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18128         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18129       if (BuildAndDiagnose) {
18130         SourceLocation VarLoc = Var->getLocation();
18131         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18132         S.Diag(VarLoc, diag::note_declare_parameter_strong);
18133       }
18134     }
18135   }
18136 
18137   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18138   if (HasBlocksAttr || CaptureType->isReferenceType() ||
18139       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18140     // Block capture by reference does not change the capture or
18141     // declaration reference types.
18142     ByRef = true;
18143   } else {
18144     // Block capture by copy introduces 'const'.
18145     CaptureType = CaptureType.getNonReferenceType().withConst();
18146     DeclRefType = CaptureType;
18147   }
18148 
18149   // Actually capture the variable.
18150   if (BuildAndDiagnose)
18151     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18152                     CaptureType, Invalid);
18153 
18154   return !Invalid;
18155 }
18156 
18157 
18158 /// Capture the given variable in the captured region.
18159 static bool captureInCapturedRegion(
18160     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18161     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18162     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18163     bool IsTopScope, Sema &S, bool Invalid) {
18164   // By default, capture variables by reference.
18165   bool ByRef = true;
18166   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18167     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18168   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18169     // Using an LValue reference type is consistent with Lambdas (see below).
18170     if (S.isOpenMPCapturedDecl(Var)) {
18171       bool HasConst = DeclRefType.isConstQualified();
18172       DeclRefType = DeclRefType.getUnqualifiedType();
18173       // Don't lose diagnostics about assignments to const.
18174       if (HasConst)
18175         DeclRefType.addConst();
18176     }
18177     // Do not capture firstprivates in tasks.
18178     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18179         OMPC_unknown)
18180       return true;
18181     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18182                                     RSI->OpenMPCaptureLevel);
18183   }
18184 
18185   if (ByRef)
18186     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18187   else
18188     CaptureType = DeclRefType;
18189 
18190   // Actually capture the variable.
18191   if (BuildAndDiagnose)
18192     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18193                     Loc, SourceLocation(), CaptureType, Invalid);
18194 
18195   return !Invalid;
18196 }
18197 
18198 /// Capture the given variable in the lambda.
18199 static bool captureInLambda(LambdaScopeInfo *LSI,
18200                             VarDecl *Var,
18201                             SourceLocation Loc,
18202                             const bool BuildAndDiagnose,
18203                             QualType &CaptureType,
18204                             QualType &DeclRefType,
18205                             const bool RefersToCapturedVariable,
18206                             const Sema::TryCaptureKind Kind,
18207                             SourceLocation EllipsisLoc,
18208                             const bool IsTopScope,
18209                             Sema &S, bool Invalid) {
18210   // Determine whether we are capturing by reference or by value.
18211   bool ByRef = false;
18212   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18213     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18214   } else {
18215     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18216   }
18217 
18218   // Compute the type of the field that will capture this variable.
18219   if (ByRef) {
18220     // C++11 [expr.prim.lambda]p15:
18221     //   An entity is captured by reference if it is implicitly or
18222     //   explicitly captured but not captured by copy. It is
18223     //   unspecified whether additional unnamed non-static data
18224     //   members are declared in the closure type for entities
18225     //   captured by reference.
18226     //
18227     // FIXME: It is not clear whether we want to build an lvalue reference
18228     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18229     // to do the former, while EDG does the latter. Core issue 1249 will
18230     // clarify, but for now we follow GCC because it's a more permissive and
18231     // easily defensible position.
18232     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18233   } else {
18234     // C++11 [expr.prim.lambda]p14:
18235     //   For each entity captured by copy, an unnamed non-static
18236     //   data member is declared in the closure type. The
18237     //   declaration order of these members is unspecified. The type
18238     //   of such a data member is the type of the corresponding
18239     //   captured entity if the entity is not a reference to an
18240     //   object, or the referenced type otherwise. [Note: If the
18241     //   captured entity is a reference to a function, the
18242     //   corresponding data member is also a reference to a
18243     //   function. - end note ]
18244     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18245       if (!RefType->getPointeeType()->isFunctionType())
18246         CaptureType = RefType->getPointeeType();
18247     }
18248 
18249     // Forbid the lambda copy-capture of autoreleasing variables.
18250     if (!Invalid &&
18251         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18252       if (BuildAndDiagnose) {
18253         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18254         S.Diag(Var->getLocation(), diag::note_previous_decl)
18255           << Var->getDeclName();
18256         Invalid = true;
18257       } else {
18258         return false;
18259       }
18260     }
18261 
18262     // Make sure that by-copy captures are of a complete and non-abstract type.
18263     if (!Invalid && BuildAndDiagnose) {
18264       if (!CaptureType->isDependentType() &&
18265           S.RequireCompleteSizedType(
18266               Loc, CaptureType,
18267               diag::err_capture_of_incomplete_or_sizeless_type,
18268               Var->getDeclName()))
18269         Invalid = true;
18270       else if (S.RequireNonAbstractType(Loc, CaptureType,
18271                                         diag::err_capture_of_abstract_type))
18272         Invalid = true;
18273     }
18274   }
18275 
18276   // Compute the type of a reference to this captured variable.
18277   if (ByRef)
18278     DeclRefType = CaptureType.getNonReferenceType();
18279   else {
18280     // C++ [expr.prim.lambda]p5:
18281     //   The closure type for a lambda-expression has a public inline
18282     //   function call operator [...]. This function call operator is
18283     //   declared const (9.3.1) if and only if the lambda-expression's
18284     //   parameter-declaration-clause is not followed by mutable.
18285     DeclRefType = CaptureType.getNonReferenceType();
18286     if (!LSI->Mutable && !CaptureType->isReferenceType())
18287       DeclRefType.addConst();
18288   }
18289 
18290   // Add the capture.
18291   if (BuildAndDiagnose)
18292     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18293                     Loc, EllipsisLoc, CaptureType, Invalid);
18294 
18295   return !Invalid;
18296 }
18297 
18298 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18299   // Offer a Copy fix even if the type is dependent.
18300   if (Var->getType()->isDependentType())
18301     return true;
18302   QualType T = Var->getType().getNonReferenceType();
18303   if (T.isTriviallyCopyableType(Context))
18304     return true;
18305   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18306 
18307     if (!(RD = RD->getDefinition()))
18308       return false;
18309     if (RD->hasSimpleCopyConstructor())
18310       return true;
18311     if (RD->hasUserDeclaredCopyConstructor())
18312       for (CXXConstructorDecl *Ctor : RD->ctors())
18313         if (Ctor->isCopyConstructor())
18314           return !Ctor->isDeleted();
18315   }
18316   return false;
18317 }
18318 
18319 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18320 /// default capture. Fixes may be omitted if they aren't allowed by the
18321 /// standard, for example we can't emit a default copy capture fix-it if we
18322 /// already explicitly copy capture capture another variable.
18323 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18324                                     VarDecl *Var) {
18325   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18326   // Don't offer Capture by copy of default capture by copy fixes if Var is
18327   // known not to be copy constructible.
18328   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18329 
18330   SmallString<32> FixBuffer;
18331   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18332   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18333     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18334     if (ShouldOfferCopyFix) {
18335       // Offer fixes to insert an explicit capture for the variable.
18336       // [] -> [VarName]
18337       // [OtherCapture] -> [OtherCapture, VarName]
18338       FixBuffer.assign({Separator, Var->getName()});
18339       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18340           << Var << /*value*/ 0
18341           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18342     }
18343     // As above but capture by reference.
18344     FixBuffer.assign({Separator, "&", Var->getName()});
18345     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18346         << Var << /*reference*/ 1
18347         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18348   }
18349 
18350   // Only try to offer default capture if there are no captures excluding this
18351   // and init captures.
18352   // [this]: OK.
18353   // [X = Y]: OK.
18354   // [&A, &B]: Don't offer.
18355   // [A, B]: Don't offer.
18356   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18357         return !C.isThisCapture() && !C.isInitCapture();
18358       }))
18359     return;
18360 
18361   // The default capture specifiers, '=' or '&', must appear first in the
18362   // capture body.
18363   SourceLocation DefaultInsertLoc =
18364       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18365 
18366   if (ShouldOfferCopyFix) {
18367     bool CanDefaultCopyCapture = true;
18368     // [=, *this] OK since c++17
18369     // [=, this] OK since c++20
18370     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18371       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18372                                   ? LSI->getCXXThisCapture().isCopyCapture()
18373                                   : false;
18374     // We can't use default capture by copy if any captures already specified
18375     // capture by copy.
18376     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18377           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18378         })) {
18379       FixBuffer.assign({"=", Separator});
18380       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18381           << /*value*/ 0
18382           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18383     }
18384   }
18385 
18386   // We can't use default capture by reference if any captures already specified
18387   // capture by reference.
18388   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18389         return !C.isInitCapture() && C.isReferenceCapture() &&
18390                !C.isThisCapture();
18391       })) {
18392     FixBuffer.assign({"&", Separator});
18393     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18394         << /*reference*/ 1
18395         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18396   }
18397 }
18398 
18399 bool Sema::tryCaptureVariable(
18400     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18401     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18402     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18403   // An init-capture is notionally from the context surrounding its
18404   // declaration, but its parent DC is the lambda class.
18405   DeclContext *VarDC = Var->getDeclContext();
18406   if (Var->isInitCapture())
18407     VarDC = VarDC->getParent();
18408 
18409   DeclContext *DC = CurContext;
18410   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18411       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18412   // We need to sync up the Declaration Context with the
18413   // FunctionScopeIndexToStopAt
18414   if (FunctionScopeIndexToStopAt) {
18415     unsigned FSIndex = FunctionScopes.size() - 1;
18416     while (FSIndex != MaxFunctionScopesIndex) {
18417       DC = getLambdaAwareParentOfDeclContext(DC);
18418       --FSIndex;
18419     }
18420   }
18421 
18422 
18423   // If the variable is declared in the current context, there is no need to
18424   // capture it.
18425   if (VarDC == DC) return true;
18426 
18427   // Capture global variables if it is required to use private copy of this
18428   // variable.
18429   bool IsGlobal = !Var->hasLocalStorage();
18430   if (IsGlobal &&
18431       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18432                                                 MaxFunctionScopesIndex)))
18433     return true;
18434   Var = Var->getCanonicalDecl();
18435 
18436   // Walk up the stack to determine whether we can capture the variable,
18437   // performing the "simple" checks that don't depend on type. We stop when
18438   // we've either hit the declared scope of the variable or find an existing
18439   // capture of that variable.  We start from the innermost capturing-entity
18440   // (the DC) and ensure that all intervening capturing-entities
18441   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18442   // declcontext can either capture the variable or have already captured
18443   // the variable.
18444   CaptureType = Var->getType();
18445   DeclRefType = CaptureType.getNonReferenceType();
18446   bool Nested = false;
18447   bool Explicit = (Kind != TryCapture_Implicit);
18448   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18449   do {
18450     // Only block literals, captured statements, and lambda expressions can
18451     // capture; other scopes don't work.
18452     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18453                                                               ExprLoc,
18454                                                               BuildAndDiagnose,
18455                                                               *this);
18456     // We need to check for the parent *first* because, if we *have*
18457     // private-captured a global variable, we need to recursively capture it in
18458     // intermediate blocks, lambdas, etc.
18459     if (!ParentDC) {
18460       if (IsGlobal) {
18461         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18462         break;
18463       }
18464       return true;
18465     }
18466 
18467     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18468     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18469 
18470 
18471     // Check whether we've already captured it.
18472     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18473                                              DeclRefType)) {
18474       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18475       break;
18476     }
18477     // If we are instantiating a generic lambda call operator body,
18478     // we do not want to capture new variables.  What was captured
18479     // during either a lambdas transformation or initial parsing
18480     // should be used.
18481     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18482       if (BuildAndDiagnose) {
18483         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18484         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18485           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18486           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18487           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18488           buildLambdaCaptureFixit(*this, LSI, Var);
18489         } else
18490           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18491       }
18492       return true;
18493     }
18494 
18495     // Try to capture variable-length arrays types.
18496     if (Var->getType()->isVariablyModifiedType()) {
18497       // We're going to walk down into the type and look for VLA
18498       // expressions.
18499       QualType QTy = Var->getType();
18500       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18501         QTy = PVD->getOriginalType();
18502       captureVariablyModifiedType(Context, QTy, CSI);
18503     }
18504 
18505     if (getLangOpts().OpenMP) {
18506       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18507         // OpenMP private variables should not be captured in outer scope, so
18508         // just break here. Similarly, global variables that are captured in a
18509         // target region should not be captured outside the scope of the region.
18510         if (RSI->CapRegionKind == CR_OpenMP) {
18511           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18512               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18513           // If the variable is private (i.e. not captured) and has variably
18514           // modified type, we still need to capture the type for correct
18515           // codegen in all regions, associated with the construct. Currently,
18516           // it is captured in the innermost captured region only.
18517           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18518               Var->getType()->isVariablyModifiedType()) {
18519             QualType QTy = Var->getType();
18520             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18521               QTy = PVD->getOriginalType();
18522             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18523                  I < E; ++I) {
18524               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18525                   FunctionScopes[FunctionScopesIndex - I]);
18526               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18527                      "Wrong number of captured regions associated with the "
18528                      "OpenMP construct.");
18529               captureVariablyModifiedType(Context, QTy, OuterRSI);
18530             }
18531           }
18532           bool IsTargetCap =
18533               IsOpenMPPrivateDecl != OMPC_private &&
18534               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18535                                          RSI->OpenMPCaptureLevel);
18536           // Do not capture global if it is not privatized in outer regions.
18537           bool IsGlobalCap =
18538               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18539                                                      RSI->OpenMPCaptureLevel);
18540 
18541           // When we detect target captures we are looking from inside the
18542           // target region, therefore we need to propagate the capture from the
18543           // enclosing region. Therefore, the capture is not initially nested.
18544           if (IsTargetCap)
18545             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18546 
18547           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18548               (IsGlobal && !IsGlobalCap)) {
18549             Nested = !IsTargetCap;
18550             bool HasConst = DeclRefType.isConstQualified();
18551             DeclRefType = DeclRefType.getUnqualifiedType();
18552             // Don't lose diagnostics about assignments to const.
18553             if (HasConst)
18554               DeclRefType.addConst();
18555             CaptureType = Context.getLValueReferenceType(DeclRefType);
18556             break;
18557           }
18558         }
18559       }
18560     }
18561     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18562       // No capture-default, and this is not an explicit capture
18563       // so cannot capture this variable.
18564       if (BuildAndDiagnose) {
18565         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18566         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18567         auto *LSI = cast<LambdaScopeInfo>(CSI);
18568         if (LSI->Lambda) {
18569           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18570           buildLambdaCaptureFixit(*this, LSI, Var);
18571         }
18572         // FIXME: If we error out because an outer lambda can not implicitly
18573         // capture a variable that an inner lambda explicitly captures, we
18574         // should have the inner lambda do the explicit capture - because
18575         // it makes for cleaner diagnostics later.  This would purely be done
18576         // so that the diagnostic does not misleadingly claim that a variable
18577         // can not be captured by a lambda implicitly even though it is captured
18578         // explicitly.  Suggestion:
18579         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18580         //    at the function head
18581         //  - cache the StartingDeclContext - this must be a lambda
18582         //  - captureInLambda in the innermost lambda the variable.
18583       }
18584       return true;
18585     }
18586 
18587     FunctionScopesIndex--;
18588     DC = ParentDC;
18589     Explicit = false;
18590   } while (!VarDC->Equals(DC));
18591 
18592   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18593   // computing the type of the capture at each step, checking type-specific
18594   // requirements, and adding captures if requested.
18595   // If the variable had already been captured previously, we start capturing
18596   // at the lambda nested within that one.
18597   bool Invalid = false;
18598   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18599        ++I) {
18600     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18601 
18602     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18603     // certain types of variables (unnamed, variably modified types etc.)
18604     // so check for eligibility.
18605     if (!Invalid)
18606       Invalid =
18607           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18608 
18609     // After encountering an error, if we're actually supposed to capture, keep
18610     // capturing in nested contexts to suppress any follow-on diagnostics.
18611     if (Invalid && !BuildAndDiagnose)
18612       return true;
18613 
18614     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18615       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18616                                DeclRefType, Nested, *this, Invalid);
18617       Nested = true;
18618     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18619       Invalid = !captureInCapturedRegion(
18620           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18621           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18622       Nested = true;
18623     } else {
18624       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18625       Invalid =
18626           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18627                            DeclRefType, Nested, Kind, EllipsisLoc,
18628                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18629       Nested = true;
18630     }
18631 
18632     if (Invalid && !BuildAndDiagnose)
18633       return true;
18634   }
18635   return Invalid;
18636 }
18637 
18638 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18639                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18640   QualType CaptureType;
18641   QualType DeclRefType;
18642   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18643                             /*BuildAndDiagnose=*/true, CaptureType,
18644                             DeclRefType, nullptr);
18645 }
18646 
18647 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18648   QualType CaptureType;
18649   QualType DeclRefType;
18650   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18651                              /*BuildAndDiagnose=*/false, CaptureType,
18652                              DeclRefType, nullptr);
18653 }
18654 
18655 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18656   QualType CaptureType;
18657   QualType DeclRefType;
18658 
18659   // Determine whether we can capture this variable.
18660   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18661                          /*BuildAndDiagnose=*/false, CaptureType,
18662                          DeclRefType, nullptr))
18663     return QualType();
18664 
18665   return DeclRefType;
18666 }
18667 
18668 namespace {
18669 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18670 // The produced TemplateArgumentListInfo* points to data stored within this
18671 // object, so should only be used in contexts where the pointer will not be
18672 // used after the CopiedTemplateArgs object is destroyed.
18673 class CopiedTemplateArgs {
18674   bool HasArgs;
18675   TemplateArgumentListInfo TemplateArgStorage;
18676 public:
18677   template<typename RefExpr>
18678   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18679     if (HasArgs)
18680       E->copyTemplateArgumentsInto(TemplateArgStorage);
18681   }
18682   operator TemplateArgumentListInfo*()
18683 #ifdef __has_cpp_attribute
18684 #if __has_cpp_attribute(clang::lifetimebound)
18685   [[clang::lifetimebound]]
18686 #endif
18687 #endif
18688   {
18689     return HasArgs ? &TemplateArgStorage : nullptr;
18690   }
18691 };
18692 }
18693 
18694 /// Walk the set of potential results of an expression and mark them all as
18695 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18696 ///
18697 /// \return A new expression if we found any potential results, ExprEmpty() if
18698 ///         not, and ExprError() if we diagnosed an error.
18699 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18700                                                       NonOdrUseReason NOUR) {
18701   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18702   // an object that satisfies the requirements for appearing in a
18703   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18704   // is immediately applied."  This function handles the lvalue-to-rvalue
18705   // conversion part.
18706   //
18707   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18708   // transform it into the relevant kind of non-odr-use node and rebuild the
18709   // tree of nodes leading to it.
18710   //
18711   // This is a mini-TreeTransform that only transforms a restricted subset of
18712   // nodes (and only certain operands of them).
18713 
18714   // Rebuild a subexpression.
18715   auto Rebuild = [&](Expr *Sub) {
18716     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18717   };
18718 
18719   // Check whether a potential result satisfies the requirements of NOUR.
18720   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18721     // Any entity other than a VarDecl is always odr-used whenever it's named
18722     // in a potentially-evaluated expression.
18723     auto *VD = dyn_cast<VarDecl>(D);
18724     if (!VD)
18725       return true;
18726 
18727     // C++2a [basic.def.odr]p4:
18728     //   A variable x whose name appears as a potentially-evalauted expression
18729     //   e is odr-used by e unless
18730     //   -- x is a reference that is usable in constant expressions, or
18731     //   -- x is a variable of non-reference type that is usable in constant
18732     //      expressions and has no mutable subobjects, and e is an element of
18733     //      the set of potential results of an expression of
18734     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18735     //      conversion is applied, or
18736     //   -- x is a variable of non-reference type, and e is an element of the
18737     //      set of potential results of a discarded-value expression to which
18738     //      the lvalue-to-rvalue conversion is not applied
18739     //
18740     // We check the first bullet and the "potentially-evaluated" condition in
18741     // BuildDeclRefExpr. We check the type requirements in the second bullet
18742     // in CheckLValueToRValueConversionOperand below.
18743     switch (NOUR) {
18744     case NOUR_None:
18745     case NOUR_Unevaluated:
18746       llvm_unreachable("unexpected non-odr-use-reason");
18747 
18748     case NOUR_Constant:
18749       // Constant references were handled when they were built.
18750       if (VD->getType()->isReferenceType())
18751         return true;
18752       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18753         if (RD->hasMutableFields())
18754           return true;
18755       if (!VD->isUsableInConstantExpressions(S.Context))
18756         return true;
18757       break;
18758 
18759     case NOUR_Discarded:
18760       if (VD->getType()->isReferenceType())
18761         return true;
18762       break;
18763     }
18764     return false;
18765   };
18766 
18767   // Mark that this expression does not constitute an odr-use.
18768   auto MarkNotOdrUsed = [&] {
18769     S.MaybeODRUseExprs.remove(E);
18770     if (LambdaScopeInfo *LSI = S.getCurLambda())
18771       LSI->markVariableExprAsNonODRUsed(E);
18772   };
18773 
18774   // C++2a [basic.def.odr]p2:
18775   //   The set of potential results of an expression e is defined as follows:
18776   switch (E->getStmtClass()) {
18777   //   -- If e is an id-expression, ...
18778   case Expr::DeclRefExprClass: {
18779     auto *DRE = cast<DeclRefExpr>(E);
18780     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18781       break;
18782 
18783     // Rebuild as a non-odr-use DeclRefExpr.
18784     MarkNotOdrUsed();
18785     return DeclRefExpr::Create(
18786         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18787         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18788         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18789         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18790   }
18791 
18792   case Expr::FunctionParmPackExprClass: {
18793     auto *FPPE = cast<FunctionParmPackExpr>(E);
18794     // If any of the declarations in the pack is odr-used, then the expression
18795     // as a whole constitutes an odr-use.
18796     for (VarDecl *D : *FPPE)
18797       if (IsPotentialResultOdrUsed(D))
18798         return ExprEmpty();
18799 
18800     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18801     // nothing cares about whether we marked this as an odr-use, but it might
18802     // be useful for non-compiler tools.
18803     MarkNotOdrUsed();
18804     break;
18805   }
18806 
18807   //   -- If e is a subscripting operation with an array operand...
18808   case Expr::ArraySubscriptExprClass: {
18809     auto *ASE = cast<ArraySubscriptExpr>(E);
18810     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18811     if (!OldBase->getType()->isArrayType())
18812       break;
18813     ExprResult Base = Rebuild(OldBase);
18814     if (!Base.isUsable())
18815       return Base;
18816     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18817     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18818     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18819     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18820                                      ASE->getRBracketLoc());
18821   }
18822 
18823   case Expr::MemberExprClass: {
18824     auto *ME = cast<MemberExpr>(E);
18825     // -- If e is a class member access expression [...] naming a non-static
18826     //    data member...
18827     if (isa<FieldDecl>(ME->getMemberDecl())) {
18828       ExprResult Base = Rebuild(ME->getBase());
18829       if (!Base.isUsable())
18830         return Base;
18831       return MemberExpr::Create(
18832           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18833           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18834           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18835           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18836           ME->getObjectKind(), ME->isNonOdrUse());
18837     }
18838 
18839     if (ME->getMemberDecl()->isCXXInstanceMember())
18840       break;
18841 
18842     // -- If e is a class member access expression naming a static data member,
18843     //    ...
18844     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18845       break;
18846 
18847     // Rebuild as a non-odr-use MemberExpr.
18848     MarkNotOdrUsed();
18849     return MemberExpr::Create(
18850         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18851         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18852         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18853         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18854   }
18855 
18856   case Expr::BinaryOperatorClass: {
18857     auto *BO = cast<BinaryOperator>(E);
18858     Expr *LHS = BO->getLHS();
18859     Expr *RHS = BO->getRHS();
18860     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18861     if (BO->getOpcode() == BO_PtrMemD) {
18862       ExprResult Sub = Rebuild(LHS);
18863       if (!Sub.isUsable())
18864         return Sub;
18865       LHS = Sub.get();
18866     //   -- If e is a comma expression, ...
18867     } else if (BO->getOpcode() == BO_Comma) {
18868       ExprResult Sub = Rebuild(RHS);
18869       if (!Sub.isUsable())
18870         return Sub;
18871       RHS = Sub.get();
18872     } else {
18873       break;
18874     }
18875     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18876                         LHS, RHS);
18877   }
18878 
18879   //   -- If e has the form (e1)...
18880   case Expr::ParenExprClass: {
18881     auto *PE = cast<ParenExpr>(E);
18882     ExprResult Sub = Rebuild(PE->getSubExpr());
18883     if (!Sub.isUsable())
18884       return Sub;
18885     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18886   }
18887 
18888   //   -- If e is a glvalue conditional expression, ...
18889   // We don't apply this to a binary conditional operator. FIXME: Should we?
18890   case Expr::ConditionalOperatorClass: {
18891     auto *CO = cast<ConditionalOperator>(E);
18892     ExprResult LHS = Rebuild(CO->getLHS());
18893     if (LHS.isInvalid())
18894       return ExprError();
18895     ExprResult RHS = Rebuild(CO->getRHS());
18896     if (RHS.isInvalid())
18897       return ExprError();
18898     if (!LHS.isUsable() && !RHS.isUsable())
18899       return ExprEmpty();
18900     if (!LHS.isUsable())
18901       LHS = CO->getLHS();
18902     if (!RHS.isUsable())
18903       RHS = CO->getRHS();
18904     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18905                                 CO->getCond(), LHS.get(), RHS.get());
18906   }
18907 
18908   // [Clang extension]
18909   //   -- If e has the form __extension__ e1...
18910   case Expr::UnaryOperatorClass: {
18911     auto *UO = cast<UnaryOperator>(E);
18912     if (UO->getOpcode() != UO_Extension)
18913       break;
18914     ExprResult Sub = Rebuild(UO->getSubExpr());
18915     if (!Sub.isUsable())
18916       return Sub;
18917     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18918                           Sub.get());
18919   }
18920 
18921   // [Clang extension]
18922   //   -- If e has the form _Generic(...), the set of potential results is the
18923   //      union of the sets of potential results of the associated expressions.
18924   case Expr::GenericSelectionExprClass: {
18925     auto *GSE = cast<GenericSelectionExpr>(E);
18926 
18927     SmallVector<Expr *, 4> AssocExprs;
18928     bool AnyChanged = false;
18929     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18930       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18931       if (AssocExpr.isInvalid())
18932         return ExprError();
18933       if (AssocExpr.isUsable()) {
18934         AssocExprs.push_back(AssocExpr.get());
18935         AnyChanged = true;
18936       } else {
18937         AssocExprs.push_back(OrigAssocExpr);
18938       }
18939     }
18940 
18941     return AnyChanged ? S.CreateGenericSelectionExpr(
18942                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18943                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18944                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18945                       : ExprEmpty();
18946   }
18947 
18948   // [Clang extension]
18949   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18950   //      results is the union of the sets of potential results of the
18951   //      second and third subexpressions.
18952   case Expr::ChooseExprClass: {
18953     auto *CE = cast<ChooseExpr>(E);
18954 
18955     ExprResult LHS = Rebuild(CE->getLHS());
18956     if (LHS.isInvalid())
18957       return ExprError();
18958 
18959     ExprResult RHS = Rebuild(CE->getLHS());
18960     if (RHS.isInvalid())
18961       return ExprError();
18962 
18963     if (!LHS.get() && !RHS.get())
18964       return ExprEmpty();
18965     if (!LHS.isUsable())
18966       LHS = CE->getLHS();
18967     if (!RHS.isUsable())
18968       RHS = CE->getRHS();
18969 
18970     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18971                              RHS.get(), CE->getRParenLoc());
18972   }
18973 
18974   // Step through non-syntactic nodes.
18975   case Expr::ConstantExprClass: {
18976     auto *CE = cast<ConstantExpr>(E);
18977     ExprResult Sub = Rebuild(CE->getSubExpr());
18978     if (!Sub.isUsable())
18979       return Sub;
18980     return ConstantExpr::Create(S.Context, Sub.get());
18981   }
18982 
18983   // We could mostly rely on the recursive rebuilding to rebuild implicit
18984   // casts, but not at the top level, so rebuild them here.
18985   case Expr::ImplicitCastExprClass: {
18986     auto *ICE = cast<ImplicitCastExpr>(E);
18987     // Only step through the narrow set of cast kinds we expect to encounter.
18988     // Anything else suggests we've left the region in which potential results
18989     // can be found.
18990     switch (ICE->getCastKind()) {
18991     case CK_NoOp:
18992     case CK_DerivedToBase:
18993     case CK_UncheckedDerivedToBase: {
18994       ExprResult Sub = Rebuild(ICE->getSubExpr());
18995       if (!Sub.isUsable())
18996         return Sub;
18997       CXXCastPath Path(ICE->path());
18998       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18999                                  ICE->getValueKind(), &Path);
19000     }
19001 
19002     default:
19003       break;
19004     }
19005     break;
19006   }
19007 
19008   default:
19009     break;
19010   }
19011 
19012   // Can't traverse through this node. Nothing to do.
19013   return ExprEmpty();
19014 }
19015 
19016 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19017   // Check whether the operand is or contains an object of non-trivial C union
19018   // type.
19019   if (E->getType().isVolatileQualified() &&
19020       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19021        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19022     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19023                           Sema::NTCUC_LValueToRValueVolatile,
19024                           NTCUK_Destruct|NTCUK_Copy);
19025 
19026   // C++2a [basic.def.odr]p4:
19027   //   [...] an expression of non-volatile-qualified non-class type to which
19028   //   the lvalue-to-rvalue conversion is applied [...]
19029   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19030     return E;
19031 
19032   ExprResult Result =
19033       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19034   if (Result.isInvalid())
19035     return ExprError();
19036   return Result.get() ? Result : E;
19037 }
19038 
19039 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19040   Res = CorrectDelayedTyposInExpr(Res);
19041 
19042   if (!Res.isUsable())
19043     return Res;
19044 
19045   // If a constant-expression is a reference to a variable where we delay
19046   // deciding whether it is an odr-use, just assume we will apply the
19047   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
19048   // (a non-type template argument), we have special handling anyway.
19049   return CheckLValueToRValueConversionOperand(Res.get());
19050 }
19051 
19052 void Sema::CleanupVarDeclMarking() {
19053   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19054   // call.
19055   MaybeODRUseExprSet LocalMaybeODRUseExprs;
19056   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19057 
19058   for (Expr *E : LocalMaybeODRUseExprs) {
19059     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19060       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19061                          DRE->getLocation(), *this);
19062     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19063       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19064                          *this);
19065     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19066       for (VarDecl *VD : *FP)
19067         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19068     } else {
19069       llvm_unreachable("Unexpected expression");
19070     }
19071   }
19072 
19073   assert(MaybeODRUseExprs.empty() &&
19074          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19075 }
19076 
19077 static void DoMarkVarDeclReferenced(
19078     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19079     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19080   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19081           isa<FunctionParmPackExpr>(E)) &&
19082          "Invalid Expr argument to DoMarkVarDeclReferenced");
19083   Var->setReferenced();
19084 
19085   if (Var->isInvalidDecl())
19086     return;
19087 
19088   auto *MSI = Var->getMemberSpecializationInfo();
19089   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19090                                        : Var->getTemplateSpecializationKind();
19091 
19092   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19093   bool UsableInConstantExpr =
19094       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19095 
19096   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19097     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19098   }
19099 
19100   // C++20 [expr.const]p12:
19101   //   A variable [...] is needed for constant evaluation if it is [...] a
19102   //   variable whose name appears as a potentially constant evaluated
19103   //   expression that is either a contexpr variable or is of non-volatile
19104   //   const-qualified integral type or of reference type
19105   bool NeededForConstantEvaluation =
19106       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19107 
19108   bool NeedDefinition =
19109       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19110 
19111   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19112          "Can't instantiate a partial template specialization.");
19113 
19114   // If this might be a member specialization of a static data member, check
19115   // the specialization is visible. We already did the checks for variable
19116   // template specializations when we created them.
19117   if (NeedDefinition && TSK != TSK_Undeclared &&
19118       !isa<VarTemplateSpecializationDecl>(Var))
19119     SemaRef.checkSpecializationVisibility(Loc, Var);
19120 
19121   // Perform implicit instantiation of static data members, static data member
19122   // templates of class templates, and variable template specializations. Delay
19123   // instantiations of variable templates, except for those that could be used
19124   // in a constant expression.
19125   if (NeedDefinition && isTemplateInstantiation(TSK)) {
19126     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19127     // instantiation declaration if a variable is usable in a constant
19128     // expression (among other cases).
19129     bool TryInstantiating =
19130         TSK == TSK_ImplicitInstantiation ||
19131         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19132 
19133     if (TryInstantiating) {
19134       SourceLocation PointOfInstantiation =
19135           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19136       bool FirstInstantiation = PointOfInstantiation.isInvalid();
19137       if (FirstInstantiation) {
19138         PointOfInstantiation = Loc;
19139         if (MSI)
19140           MSI->setPointOfInstantiation(PointOfInstantiation);
19141           // FIXME: Notify listener.
19142         else
19143           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19144       }
19145 
19146       if (UsableInConstantExpr) {
19147         // Do not defer instantiations of variables that could be used in a
19148         // constant expression.
19149         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19150           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19151         });
19152 
19153         // Re-set the member to trigger a recomputation of the dependence bits
19154         // for the expression.
19155         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19156           DRE->setDecl(DRE->getDecl());
19157         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19158           ME->setMemberDecl(ME->getMemberDecl());
19159       } else if (FirstInstantiation ||
19160                  isa<VarTemplateSpecializationDecl>(Var)) {
19161         // FIXME: For a specialization of a variable template, we don't
19162         // distinguish between "declaration and type implicitly instantiated"
19163         // and "implicit instantiation of definition requested", so we have
19164         // no direct way to avoid enqueueing the pending instantiation
19165         // multiple times.
19166         SemaRef.PendingInstantiations
19167             .push_back(std::make_pair(Var, PointOfInstantiation));
19168       }
19169     }
19170   }
19171 
19172   // C++2a [basic.def.odr]p4:
19173   //   A variable x whose name appears as a potentially-evaluated expression e
19174   //   is odr-used by e unless
19175   //   -- x is a reference that is usable in constant expressions
19176   //   -- x is a variable of non-reference type that is usable in constant
19177   //      expressions and has no mutable subobjects [FIXME], and e is an
19178   //      element of the set of potential results of an expression of
19179   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19180   //      conversion is applied
19181   //   -- x is a variable of non-reference type, and e is an element of the set
19182   //      of potential results of a discarded-value expression to which the
19183   //      lvalue-to-rvalue conversion is not applied [FIXME]
19184   //
19185   // We check the first part of the second bullet here, and
19186   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19187   // FIXME: To get the third bullet right, we need to delay this even for
19188   // variables that are not usable in constant expressions.
19189 
19190   // If we already know this isn't an odr-use, there's nothing more to do.
19191   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19192     if (DRE->isNonOdrUse())
19193       return;
19194   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19195     if (ME->isNonOdrUse())
19196       return;
19197 
19198   switch (OdrUse) {
19199   case OdrUseContext::None:
19200     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19201            "missing non-odr-use marking for unevaluated decl ref");
19202     break;
19203 
19204   case OdrUseContext::FormallyOdrUsed:
19205     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19206     // behavior.
19207     break;
19208 
19209   case OdrUseContext::Used:
19210     // If we might later find that this expression isn't actually an odr-use,
19211     // delay the marking.
19212     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19213       SemaRef.MaybeODRUseExprs.insert(E);
19214     else
19215       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19216     break;
19217 
19218   case OdrUseContext::Dependent:
19219     // If this is a dependent context, we don't need to mark variables as
19220     // odr-used, but we may still need to track them for lambda capture.
19221     // FIXME: Do we also need to do this inside dependent typeid expressions
19222     // (which are modeled as unevaluated at this point)?
19223     const bool RefersToEnclosingScope =
19224         (SemaRef.CurContext != Var->getDeclContext() &&
19225          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19226     if (RefersToEnclosingScope) {
19227       LambdaScopeInfo *const LSI =
19228           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19229       if (LSI && (!LSI->CallOperator ||
19230                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19231         // If a variable could potentially be odr-used, defer marking it so
19232         // until we finish analyzing the full expression for any
19233         // lvalue-to-rvalue
19234         // or discarded value conversions that would obviate odr-use.
19235         // Add it to the list of potential captures that will be analyzed
19236         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19237         // unless the variable is a reference that was initialized by a constant
19238         // expression (this will never need to be captured or odr-used).
19239         //
19240         // FIXME: We can simplify this a lot after implementing P0588R1.
19241         assert(E && "Capture variable should be used in an expression.");
19242         if (!Var->getType()->isReferenceType() ||
19243             !Var->isUsableInConstantExpressions(SemaRef.Context))
19244           LSI->addPotentialCapture(E->IgnoreParens());
19245       }
19246     }
19247     break;
19248   }
19249 }
19250 
19251 /// Mark a variable referenced, and check whether it is odr-used
19252 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19253 /// used directly for normal expressions referring to VarDecl.
19254 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19255   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19256 }
19257 
19258 static void
19259 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19260                    bool MightBeOdrUse,
19261                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19262   if (SemaRef.isInOpenMPDeclareTargetContext())
19263     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19264 
19265   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19266     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19267     return;
19268   }
19269 
19270   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19271 
19272   // If this is a call to a method via a cast, also mark the method in the
19273   // derived class used in case codegen can devirtualize the call.
19274   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19275   if (!ME)
19276     return;
19277   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19278   if (!MD)
19279     return;
19280   // Only attempt to devirtualize if this is truly a virtual call.
19281   bool IsVirtualCall = MD->isVirtual() &&
19282                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19283   if (!IsVirtualCall)
19284     return;
19285 
19286   // If it's possible to devirtualize the call, mark the called function
19287   // referenced.
19288   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19289       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19290   if (DM)
19291     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19292 }
19293 
19294 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19295 ///
19296 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19297 /// handled with care if the DeclRefExpr is not newly-created.
19298 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19299   // TODO: update this with DR# once a defect report is filed.
19300   // C++11 defect. The address of a pure member should not be an ODR use, even
19301   // if it's a qualified reference.
19302   bool OdrUse = true;
19303   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19304     if (Method->isVirtual() &&
19305         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19306       OdrUse = false;
19307 
19308   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19309     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19310         FD->isConsteval() && !RebuildingImmediateInvocation)
19311       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19312   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19313                      RefsMinusAssignments);
19314 }
19315 
19316 /// Perform reference-marking and odr-use handling for a MemberExpr.
19317 void Sema::MarkMemberReferenced(MemberExpr *E) {
19318   // C++11 [basic.def.odr]p2:
19319   //   A non-overloaded function whose name appears as a potentially-evaluated
19320   //   expression or a member of a set of candidate functions, if selected by
19321   //   overload resolution when referred to from a potentially-evaluated
19322   //   expression, is odr-used, unless it is a pure virtual function and its
19323   //   name is not explicitly qualified.
19324   bool MightBeOdrUse = true;
19325   if (E->performsVirtualDispatch(getLangOpts())) {
19326     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19327       if (Method->isPure())
19328         MightBeOdrUse = false;
19329   }
19330   SourceLocation Loc =
19331       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19332   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19333                      RefsMinusAssignments);
19334 }
19335 
19336 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19337 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19338   for (VarDecl *VD : *E)
19339     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19340                        RefsMinusAssignments);
19341 }
19342 
19343 /// Perform marking for a reference to an arbitrary declaration.  It
19344 /// marks the declaration referenced, and performs odr-use checking for
19345 /// functions and variables. This method should not be used when building a
19346 /// normal expression which refers to a variable.
19347 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19348                                  bool MightBeOdrUse) {
19349   if (MightBeOdrUse) {
19350     if (auto *VD = dyn_cast<VarDecl>(D)) {
19351       MarkVariableReferenced(Loc, VD);
19352       return;
19353     }
19354   }
19355   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19356     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19357     return;
19358   }
19359   D->setReferenced();
19360 }
19361 
19362 namespace {
19363   // Mark all of the declarations used by a type as referenced.
19364   // FIXME: Not fully implemented yet! We need to have a better understanding
19365   // of when we're entering a context we should not recurse into.
19366   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19367   // TreeTransforms rebuilding the type in a new context. Rather than
19368   // duplicating the TreeTransform logic, we should consider reusing it here.
19369   // Currently that causes problems when rebuilding LambdaExprs.
19370   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19371     Sema &S;
19372     SourceLocation Loc;
19373 
19374   public:
19375     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19376 
19377     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19378 
19379     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19380   };
19381 }
19382 
19383 bool MarkReferencedDecls::TraverseTemplateArgument(
19384     const TemplateArgument &Arg) {
19385   {
19386     // A non-type template argument is a constant-evaluated context.
19387     EnterExpressionEvaluationContext Evaluated(
19388         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19389     if (Arg.getKind() == TemplateArgument::Declaration) {
19390       if (Decl *D = Arg.getAsDecl())
19391         S.MarkAnyDeclReferenced(Loc, D, true);
19392     } else if (Arg.getKind() == TemplateArgument::Expression) {
19393       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19394     }
19395   }
19396 
19397   return Inherited::TraverseTemplateArgument(Arg);
19398 }
19399 
19400 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19401   MarkReferencedDecls Marker(*this, Loc);
19402   Marker.TraverseType(T);
19403 }
19404 
19405 namespace {
19406 /// Helper class that marks all of the declarations referenced by
19407 /// potentially-evaluated subexpressions as "referenced".
19408 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19409 public:
19410   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19411   bool SkipLocalVariables;
19412   ArrayRef<const Expr *> StopAt;
19413 
19414   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19415                       ArrayRef<const Expr *> StopAt)
19416       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19417 
19418   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19419     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19420   }
19421 
19422   void Visit(Expr *E) {
19423     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19424       return;
19425     Inherited::Visit(E);
19426   }
19427 
19428   void VisitDeclRefExpr(DeclRefExpr *E) {
19429     // If we were asked not to visit local variables, don't.
19430     if (SkipLocalVariables) {
19431       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19432         if (VD->hasLocalStorage())
19433           return;
19434     }
19435 
19436     // FIXME: This can trigger the instantiation of the initializer of a
19437     // variable, which can cause the expression to become value-dependent
19438     // or error-dependent. Do we need to propagate the new dependence bits?
19439     S.MarkDeclRefReferenced(E);
19440   }
19441 
19442   void VisitMemberExpr(MemberExpr *E) {
19443     S.MarkMemberReferenced(E);
19444     Visit(E->getBase());
19445   }
19446 };
19447 } // namespace
19448 
19449 /// Mark any declarations that appear within this expression or any
19450 /// potentially-evaluated subexpressions as "referenced".
19451 ///
19452 /// \param SkipLocalVariables If true, don't mark local variables as
19453 /// 'referenced'.
19454 /// \param StopAt Subexpressions that we shouldn't recurse into.
19455 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19456                                             bool SkipLocalVariables,
19457                                             ArrayRef<const Expr*> StopAt) {
19458   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19459 }
19460 
19461 /// Emit a diagnostic when statements are reachable.
19462 /// FIXME: check for reachability even in expressions for which we don't build a
19463 ///        CFG (eg, in the initializer of a global or in a constant expression).
19464 ///        For example,
19465 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19466 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19467                            const PartialDiagnostic &PD) {
19468   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19469     if (!FunctionScopes.empty())
19470       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19471           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19472     return true;
19473   }
19474 
19475   // The initializer of a constexpr variable or of the first declaration of a
19476   // static data member is not syntactically a constant evaluated constant,
19477   // but nonetheless is always required to be a constant expression, so we
19478   // can skip diagnosing.
19479   // FIXME: Using the mangling context here is a hack.
19480   if (auto *VD = dyn_cast_or_null<VarDecl>(
19481           ExprEvalContexts.back().ManglingContextDecl)) {
19482     if (VD->isConstexpr() ||
19483         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19484       return false;
19485     // FIXME: For any other kind of variable, we should build a CFG for its
19486     // initializer and check whether the context in question is reachable.
19487   }
19488 
19489   Diag(Loc, PD);
19490   return true;
19491 }
19492 
19493 /// Emit a diagnostic that describes an effect on the run-time behavior
19494 /// of the program being compiled.
19495 ///
19496 /// This routine emits the given diagnostic when the code currently being
19497 /// type-checked is "potentially evaluated", meaning that there is a
19498 /// possibility that the code will actually be executable. Code in sizeof()
19499 /// expressions, code used only during overload resolution, etc., are not
19500 /// potentially evaluated. This routine will suppress such diagnostics or,
19501 /// in the absolutely nutty case of potentially potentially evaluated
19502 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19503 /// later.
19504 ///
19505 /// This routine should be used for all diagnostics that describe the run-time
19506 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19507 /// Failure to do so will likely result in spurious diagnostics or failures
19508 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19509 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19510                                const PartialDiagnostic &PD) {
19511 
19512   if (ExprEvalContexts.back().isDiscardedStatementContext())
19513     return false;
19514 
19515   switch (ExprEvalContexts.back().Context) {
19516   case ExpressionEvaluationContext::Unevaluated:
19517   case ExpressionEvaluationContext::UnevaluatedList:
19518   case ExpressionEvaluationContext::UnevaluatedAbstract:
19519   case ExpressionEvaluationContext::DiscardedStatement:
19520     // The argument will never be evaluated, so don't complain.
19521     break;
19522 
19523   case ExpressionEvaluationContext::ConstantEvaluated:
19524   case ExpressionEvaluationContext::ImmediateFunctionContext:
19525     // Relevant diagnostics should be produced by constant evaluation.
19526     break;
19527 
19528   case ExpressionEvaluationContext::PotentiallyEvaluated:
19529   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19530     return DiagIfReachable(Loc, Stmts, PD);
19531   }
19532 
19533   return false;
19534 }
19535 
19536 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19537                                const PartialDiagnostic &PD) {
19538   return DiagRuntimeBehavior(
19539       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19540 }
19541 
19542 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19543                                CallExpr *CE, FunctionDecl *FD) {
19544   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19545     return false;
19546 
19547   // If we're inside a decltype's expression, don't check for a valid return
19548   // type or construct temporaries until we know whether this is the last call.
19549   if (ExprEvalContexts.back().ExprContext ==
19550       ExpressionEvaluationContextRecord::EK_Decltype) {
19551     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19552     return false;
19553   }
19554 
19555   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19556     FunctionDecl *FD;
19557     CallExpr *CE;
19558 
19559   public:
19560     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19561       : FD(FD), CE(CE) { }
19562 
19563     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19564       if (!FD) {
19565         S.Diag(Loc, diag::err_call_incomplete_return)
19566           << T << CE->getSourceRange();
19567         return;
19568       }
19569 
19570       S.Diag(Loc, diag::err_call_function_incomplete_return)
19571           << CE->getSourceRange() << FD << T;
19572       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19573           << FD->getDeclName();
19574     }
19575   } Diagnoser(FD, CE);
19576 
19577   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19578     return true;
19579 
19580   return false;
19581 }
19582 
19583 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19584 // will prevent this condition from triggering, which is what we want.
19585 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19586   SourceLocation Loc;
19587 
19588   unsigned diagnostic = diag::warn_condition_is_assignment;
19589   bool IsOrAssign = false;
19590 
19591   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19592     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19593       return;
19594 
19595     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19596 
19597     // Greylist some idioms by putting them into a warning subcategory.
19598     if (ObjCMessageExpr *ME
19599           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19600       Selector Sel = ME->getSelector();
19601 
19602       // self = [<foo> init...]
19603       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19604         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19605 
19606       // <foo> = [<bar> nextObject]
19607       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19608         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19609     }
19610 
19611     Loc = Op->getOperatorLoc();
19612   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19613     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19614       return;
19615 
19616     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19617     Loc = Op->getOperatorLoc();
19618   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19619     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19620   else {
19621     // Not an assignment.
19622     return;
19623   }
19624 
19625   Diag(Loc, diagnostic) << E->getSourceRange();
19626 
19627   SourceLocation Open = E->getBeginLoc();
19628   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19629   Diag(Loc, diag::note_condition_assign_silence)
19630         << FixItHint::CreateInsertion(Open, "(")
19631         << FixItHint::CreateInsertion(Close, ")");
19632 
19633   if (IsOrAssign)
19634     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19635       << FixItHint::CreateReplacement(Loc, "!=");
19636   else
19637     Diag(Loc, diag::note_condition_assign_to_comparison)
19638       << FixItHint::CreateReplacement(Loc, "==");
19639 }
19640 
19641 /// Redundant parentheses over an equality comparison can indicate
19642 /// that the user intended an assignment used as condition.
19643 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19644   // Don't warn if the parens came from a macro.
19645   SourceLocation parenLoc = ParenE->getBeginLoc();
19646   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19647     return;
19648   // Don't warn for dependent expressions.
19649   if (ParenE->isTypeDependent())
19650     return;
19651 
19652   Expr *E = ParenE->IgnoreParens();
19653 
19654   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19655     if (opE->getOpcode() == BO_EQ &&
19656         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19657                                                            == Expr::MLV_Valid) {
19658       SourceLocation Loc = opE->getOperatorLoc();
19659 
19660       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19661       SourceRange ParenERange = ParenE->getSourceRange();
19662       Diag(Loc, diag::note_equality_comparison_silence)
19663         << FixItHint::CreateRemoval(ParenERange.getBegin())
19664         << FixItHint::CreateRemoval(ParenERange.getEnd());
19665       Diag(Loc, diag::note_equality_comparison_to_assign)
19666         << FixItHint::CreateReplacement(Loc, "=");
19667     }
19668 }
19669 
19670 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19671                                        bool IsConstexpr) {
19672   DiagnoseAssignmentAsCondition(E);
19673   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19674     DiagnoseEqualityWithExtraParens(parenE);
19675 
19676   ExprResult result = CheckPlaceholderExpr(E);
19677   if (result.isInvalid()) return ExprError();
19678   E = result.get();
19679 
19680   if (!E->isTypeDependent()) {
19681     if (getLangOpts().CPlusPlus)
19682       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19683 
19684     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19685     if (ERes.isInvalid())
19686       return ExprError();
19687     E = ERes.get();
19688 
19689     QualType T = E->getType();
19690     if (!T->isScalarType()) { // C99 6.8.4.1p1
19691       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19692         << T << E->getSourceRange();
19693       return ExprError();
19694     }
19695     CheckBoolLikeConversion(E, Loc);
19696   }
19697 
19698   return E;
19699 }
19700 
19701 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19702                                            Expr *SubExpr, ConditionKind CK,
19703                                            bool MissingOK) {
19704   // MissingOK indicates whether having no condition expression is valid
19705   // (for loop) or invalid (e.g. while loop).
19706   if (!SubExpr)
19707     return MissingOK ? ConditionResult() : ConditionError();
19708 
19709   ExprResult Cond;
19710   switch (CK) {
19711   case ConditionKind::Boolean:
19712     Cond = CheckBooleanCondition(Loc, SubExpr);
19713     break;
19714 
19715   case ConditionKind::ConstexprIf:
19716     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19717     break;
19718 
19719   case ConditionKind::Switch:
19720     Cond = CheckSwitchCondition(Loc, SubExpr);
19721     break;
19722   }
19723   if (Cond.isInvalid()) {
19724     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19725                               {SubExpr}, PreferredConditionType(CK));
19726     if (!Cond.get())
19727       return ConditionError();
19728   }
19729   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19730   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19731   if (!FullExpr.get())
19732     return ConditionError();
19733 
19734   return ConditionResult(*this, nullptr, FullExpr,
19735                          CK == ConditionKind::ConstexprIf);
19736 }
19737 
19738 namespace {
19739   /// A visitor for rebuilding a call to an __unknown_any expression
19740   /// to have an appropriate type.
19741   struct RebuildUnknownAnyFunction
19742     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19743 
19744     Sema &S;
19745 
19746     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19747 
19748     ExprResult VisitStmt(Stmt *S) {
19749       llvm_unreachable("unexpected statement!");
19750     }
19751 
19752     ExprResult VisitExpr(Expr *E) {
19753       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19754         << E->getSourceRange();
19755       return ExprError();
19756     }
19757 
19758     /// Rebuild an expression which simply semantically wraps another
19759     /// expression which it shares the type and value kind of.
19760     template <class T> ExprResult rebuildSugarExpr(T *E) {
19761       ExprResult SubResult = Visit(E->getSubExpr());
19762       if (SubResult.isInvalid()) return ExprError();
19763 
19764       Expr *SubExpr = SubResult.get();
19765       E->setSubExpr(SubExpr);
19766       E->setType(SubExpr->getType());
19767       E->setValueKind(SubExpr->getValueKind());
19768       assert(E->getObjectKind() == OK_Ordinary);
19769       return E;
19770     }
19771 
19772     ExprResult VisitParenExpr(ParenExpr *E) {
19773       return rebuildSugarExpr(E);
19774     }
19775 
19776     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19777       return rebuildSugarExpr(E);
19778     }
19779 
19780     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19781       ExprResult SubResult = Visit(E->getSubExpr());
19782       if (SubResult.isInvalid()) return ExprError();
19783 
19784       Expr *SubExpr = SubResult.get();
19785       E->setSubExpr(SubExpr);
19786       E->setType(S.Context.getPointerType(SubExpr->getType()));
19787       assert(E->isPRValue());
19788       assert(E->getObjectKind() == OK_Ordinary);
19789       return E;
19790     }
19791 
19792     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19793       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19794 
19795       E->setType(VD->getType());
19796 
19797       assert(E->isPRValue());
19798       if (S.getLangOpts().CPlusPlus &&
19799           !(isa<CXXMethodDecl>(VD) &&
19800             cast<CXXMethodDecl>(VD)->isInstance()))
19801         E->setValueKind(VK_LValue);
19802 
19803       return E;
19804     }
19805 
19806     ExprResult VisitMemberExpr(MemberExpr *E) {
19807       return resolveDecl(E, E->getMemberDecl());
19808     }
19809 
19810     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19811       return resolveDecl(E, E->getDecl());
19812     }
19813   };
19814 }
19815 
19816 /// Given a function expression of unknown-any type, try to rebuild it
19817 /// to have a function type.
19818 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19819   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19820   if (Result.isInvalid()) return ExprError();
19821   return S.DefaultFunctionArrayConversion(Result.get());
19822 }
19823 
19824 namespace {
19825   /// A visitor for rebuilding an expression of type __unknown_anytype
19826   /// into one which resolves the type directly on the referring
19827   /// expression.  Strict preservation of the original source
19828   /// structure is not a goal.
19829   struct RebuildUnknownAnyExpr
19830     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19831 
19832     Sema &S;
19833 
19834     /// The current destination type.
19835     QualType DestType;
19836 
19837     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19838       : S(S), DestType(CastType) {}
19839 
19840     ExprResult VisitStmt(Stmt *S) {
19841       llvm_unreachable("unexpected statement!");
19842     }
19843 
19844     ExprResult VisitExpr(Expr *E) {
19845       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19846         << E->getSourceRange();
19847       return ExprError();
19848     }
19849 
19850     ExprResult VisitCallExpr(CallExpr *E);
19851     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19852 
19853     /// Rebuild an expression which simply semantically wraps another
19854     /// expression which it shares the type and value kind of.
19855     template <class T> ExprResult rebuildSugarExpr(T *E) {
19856       ExprResult SubResult = Visit(E->getSubExpr());
19857       if (SubResult.isInvalid()) return ExprError();
19858       Expr *SubExpr = SubResult.get();
19859       E->setSubExpr(SubExpr);
19860       E->setType(SubExpr->getType());
19861       E->setValueKind(SubExpr->getValueKind());
19862       assert(E->getObjectKind() == OK_Ordinary);
19863       return E;
19864     }
19865 
19866     ExprResult VisitParenExpr(ParenExpr *E) {
19867       return rebuildSugarExpr(E);
19868     }
19869 
19870     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19871       return rebuildSugarExpr(E);
19872     }
19873 
19874     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19875       const PointerType *Ptr = DestType->getAs<PointerType>();
19876       if (!Ptr) {
19877         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19878           << E->getSourceRange();
19879         return ExprError();
19880       }
19881 
19882       if (isa<CallExpr>(E->getSubExpr())) {
19883         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19884           << E->getSourceRange();
19885         return ExprError();
19886       }
19887 
19888       assert(E->isPRValue());
19889       assert(E->getObjectKind() == OK_Ordinary);
19890       E->setType(DestType);
19891 
19892       // Build the sub-expression as if it were an object of the pointee type.
19893       DestType = Ptr->getPointeeType();
19894       ExprResult SubResult = Visit(E->getSubExpr());
19895       if (SubResult.isInvalid()) return ExprError();
19896       E->setSubExpr(SubResult.get());
19897       return E;
19898     }
19899 
19900     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19901 
19902     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19903 
19904     ExprResult VisitMemberExpr(MemberExpr *E) {
19905       return resolveDecl(E, E->getMemberDecl());
19906     }
19907 
19908     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19909       return resolveDecl(E, E->getDecl());
19910     }
19911   };
19912 }
19913 
19914 /// Rebuilds a call expression which yielded __unknown_anytype.
19915 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19916   Expr *CalleeExpr = E->getCallee();
19917 
19918   enum FnKind {
19919     FK_MemberFunction,
19920     FK_FunctionPointer,
19921     FK_BlockPointer
19922   };
19923 
19924   FnKind Kind;
19925   QualType CalleeType = CalleeExpr->getType();
19926   if (CalleeType == S.Context.BoundMemberTy) {
19927     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19928     Kind = FK_MemberFunction;
19929     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19930   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19931     CalleeType = Ptr->getPointeeType();
19932     Kind = FK_FunctionPointer;
19933   } else {
19934     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19935     Kind = FK_BlockPointer;
19936   }
19937   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19938 
19939   // Verify that this is a legal result type of a function.
19940   if (DestType->isArrayType() || DestType->isFunctionType()) {
19941     unsigned diagID = diag::err_func_returning_array_function;
19942     if (Kind == FK_BlockPointer)
19943       diagID = diag::err_block_returning_array_function;
19944 
19945     S.Diag(E->getExprLoc(), diagID)
19946       << DestType->isFunctionType() << DestType;
19947     return ExprError();
19948   }
19949 
19950   // Otherwise, go ahead and set DestType as the call's result.
19951   E->setType(DestType.getNonLValueExprType(S.Context));
19952   E->setValueKind(Expr::getValueKindForType(DestType));
19953   assert(E->getObjectKind() == OK_Ordinary);
19954 
19955   // Rebuild the function type, replacing the result type with DestType.
19956   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19957   if (Proto) {
19958     // __unknown_anytype(...) is a special case used by the debugger when
19959     // it has no idea what a function's signature is.
19960     //
19961     // We want to build this call essentially under the K&R
19962     // unprototyped rules, but making a FunctionNoProtoType in C++
19963     // would foul up all sorts of assumptions.  However, we cannot
19964     // simply pass all arguments as variadic arguments, nor can we
19965     // portably just call the function under a non-variadic type; see
19966     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19967     // However, it turns out that in practice it is generally safe to
19968     // call a function declared as "A foo(B,C,D);" under the prototype
19969     // "A foo(B,C,D,...);".  The only known exception is with the
19970     // Windows ABI, where any variadic function is implicitly cdecl
19971     // regardless of its normal CC.  Therefore we change the parameter
19972     // types to match the types of the arguments.
19973     //
19974     // This is a hack, but it is far superior to moving the
19975     // corresponding target-specific code from IR-gen to Sema/AST.
19976 
19977     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19978     SmallVector<QualType, 8> ArgTypes;
19979     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19980       ArgTypes.reserve(E->getNumArgs());
19981       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19982         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19983       }
19984       ParamTypes = ArgTypes;
19985     }
19986     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19987                                          Proto->getExtProtoInfo());
19988   } else {
19989     DestType = S.Context.getFunctionNoProtoType(DestType,
19990                                                 FnType->getExtInfo());
19991   }
19992 
19993   // Rebuild the appropriate pointer-to-function type.
19994   switch (Kind) {
19995   case FK_MemberFunction:
19996     // Nothing to do.
19997     break;
19998 
19999   case FK_FunctionPointer:
20000     DestType = S.Context.getPointerType(DestType);
20001     break;
20002 
20003   case FK_BlockPointer:
20004     DestType = S.Context.getBlockPointerType(DestType);
20005     break;
20006   }
20007 
20008   // Finally, we can recurse.
20009   ExprResult CalleeResult = Visit(CalleeExpr);
20010   if (!CalleeResult.isUsable()) return ExprError();
20011   E->setCallee(CalleeResult.get());
20012 
20013   // Bind a temporary if necessary.
20014   return S.MaybeBindToTemporary(E);
20015 }
20016 
20017 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20018   // Verify that this is a legal result type of a call.
20019   if (DestType->isArrayType() || DestType->isFunctionType()) {
20020     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20021       << DestType->isFunctionType() << DestType;
20022     return ExprError();
20023   }
20024 
20025   // Rewrite the method result type if available.
20026   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20027     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20028     Method->setReturnType(DestType);
20029   }
20030 
20031   // Change the type of the message.
20032   E->setType(DestType.getNonReferenceType());
20033   E->setValueKind(Expr::getValueKindForType(DestType));
20034 
20035   return S.MaybeBindToTemporary(E);
20036 }
20037 
20038 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20039   // The only case we should ever see here is a function-to-pointer decay.
20040   if (E->getCastKind() == CK_FunctionToPointerDecay) {
20041     assert(E->isPRValue());
20042     assert(E->getObjectKind() == OK_Ordinary);
20043 
20044     E->setType(DestType);
20045 
20046     // Rebuild the sub-expression as the pointee (function) type.
20047     DestType = DestType->castAs<PointerType>()->getPointeeType();
20048 
20049     ExprResult Result = Visit(E->getSubExpr());
20050     if (!Result.isUsable()) return ExprError();
20051 
20052     E->setSubExpr(Result.get());
20053     return E;
20054   } else if (E->getCastKind() == CK_LValueToRValue) {
20055     assert(E->isPRValue());
20056     assert(E->getObjectKind() == OK_Ordinary);
20057 
20058     assert(isa<BlockPointerType>(E->getType()));
20059 
20060     E->setType(DestType);
20061 
20062     // The sub-expression has to be a lvalue reference, so rebuild it as such.
20063     DestType = S.Context.getLValueReferenceType(DestType);
20064 
20065     ExprResult Result = Visit(E->getSubExpr());
20066     if (!Result.isUsable()) return ExprError();
20067 
20068     E->setSubExpr(Result.get());
20069     return E;
20070   } else {
20071     llvm_unreachable("Unhandled cast type!");
20072   }
20073 }
20074 
20075 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20076   ExprValueKind ValueKind = VK_LValue;
20077   QualType Type = DestType;
20078 
20079   // We know how to make this work for certain kinds of decls:
20080 
20081   //  - functions
20082   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20083     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20084       DestType = Ptr->getPointeeType();
20085       ExprResult Result = resolveDecl(E, VD);
20086       if (Result.isInvalid()) return ExprError();
20087       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20088                                  VK_PRValue);
20089     }
20090 
20091     if (!Type->isFunctionType()) {
20092       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20093         << VD << E->getSourceRange();
20094       return ExprError();
20095     }
20096     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20097       // We must match the FunctionDecl's type to the hack introduced in
20098       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20099       // type. See the lengthy commentary in that routine.
20100       QualType FDT = FD->getType();
20101       const FunctionType *FnType = FDT->castAs<FunctionType>();
20102       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20103       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20104       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20105         SourceLocation Loc = FD->getLocation();
20106         FunctionDecl *NewFD = FunctionDecl::Create(
20107             S.Context, FD->getDeclContext(), Loc, Loc,
20108             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20109             SC_None, S.getCurFPFeatures().isFPConstrained(),
20110             false /*isInlineSpecified*/, FD->hasPrototype(),
20111             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20112 
20113         if (FD->getQualifier())
20114           NewFD->setQualifierInfo(FD->getQualifierLoc());
20115 
20116         SmallVector<ParmVarDecl*, 16> Params;
20117         for (const auto &AI : FT->param_types()) {
20118           ParmVarDecl *Param =
20119             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20120           Param->setScopeInfo(0, Params.size());
20121           Params.push_back(Param);
20122         }
20123         NewFD->setParams(Params);
20124         DRE->setDecl(NewFD);
20125         VD = DRE->getDecl();
20126       }
20127     }
20128 
20129     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20130       if (MD->isInstance()) {
20131         ValueKind = VK_PRValue;
20132         Type = S.Context.BoundMemberTy;
20133       }
20134 
20135     // Function references aren't l-values in C.
20136     if (!S.getLangOpts().CPlusPlus)
20137       ValueKind = VK_PRValue;
20138 
20139   //  - variables
20140   } else if (isa<VarDecl>(VD)) {
20141     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20142       Type = RefTy->getPointeeType();
20143     } else if (Type->isFunctionType()) {
20144       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20145         << VD << E->getSourceRange();
20146       return ExprError();
20147     }
20148 
20149   //  - nothing else
20150   } else {
20151     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20152       << VD << E->getSourceRange();
20153     return ExprError();
20154   }
20155 
20156   // Modifying the declaration like this is friendly to IR-gen but
20157   // also really dangerous.
20158   VD->setType(DestType);
20159   E->setType(Type);
20160   E->setValueKind(ValueKind);
20161   return E;
20162 }
20163 
20164 /// Check a cast of an unknown-any type.  We intentionally only
20165 /// trigger this for C-style casts.
20166 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20167                                      Expr *CastExpr, CastKind &CastKind,
20168                                      ExprValueKind &VK, CXXCastPath &Path) {
20169   // The type we're casting to must be either void or complete.
20170   if (!CastType->isVoidType() &&
20171       RequireCompleteType(TypeRange.getBegin(), CastType,
20172                           diag::err_typecheck_cast_to_incomplete))
20173     return ExprError();
20174 
20175   // Rewrite the casted expression from scratch.
20176   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20177   if (!result.isUsable()) return ExprError();
20178 
20179   CastExpr = result.get();
20180   VK = CastExpr->getValueKind();
20181   CastKind = CK_NoOp;
20182 
20183   return CastExpr;
20184 }
20185 
20186 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20187   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20188 }
20189 
20190 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20191                                     Expr *arg, QualType &paramType) {
20192   // If the syntactic form of the argument is not an explicit cast of
20193   // any sort, just do default argument promotion.
20194   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20195   if (!castArg) {
20196     ExprResult result = DefaultArgumentPromotion(arg);
20197     if (result.isInvalid()) return ExprError();
20198     paramType = result.get()->getType();
20199     return result;
20200   }
20201 
20202   // Otherwise, use the type that was written in the explicit cast.
20203   assert(!arg->hasPlaceholderType());
20204   paramType = castArg->getTypeAsWritten();
20205 
20206   // Copy-initialize a parameter of that type.
20207   InitializedEntity entity =
20208     InitializedEntity::InitializeParameter(Context, paramType,
20209                                            /*consumed*/ false);
20210   return PerformCopyInitialization(entity, callLoc, arg);
20211 }
20212 
20213 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20214   Expr *orig = E;
20215   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20216   while (true) {
20217     E = E->IgnoreParenImpCasts();
20218     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20219       E = call->getCallee();
20220       diagID = diag::err_uncasted_call_of_unknown_any;
20221     } else {
20222       break;
20223     }
20224   }
20225 
20226   SourceLocation loc;
20227   NamedDecl *d;
20228   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20229     loc = ref->getLocation();
20230     d = ref->getDecl();
20231   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20232     loc = mem->getMemberLoc();
20233     d = mem->getMemberDecl();
20234   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20235     diagID = diag::err_uncasted_call_of_unknown_any;
20236     loc = msg->getSelectorStartLoc();
20237     d = msg->getMethodDecl();
20238     if (!d) {
20239       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20240         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20241         << orig->getSourceRange();
20242       return ExprError();
20243     }
20244   } else {
20245     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20246       << E->getSourceRange();
20247     return ExprError();
20248   }
20249 
20250   S.Diag(loc, diagID) << d << orig->getSourceRange();
20251 
20252   // Never recoverable.
20253   return ExprError();
20254 }
20255 
20256 /// Check for operands with placeholder types and complain if found.
20257 /// Returns ExprError() if there was an error and no recovery was possible.
20258 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20259   if (!Context.isDependenceAllowed()) {
20260     // C cannot handle TypoExpr nodes on either side of a binop because it
20261     // doesn't handle dependent types properly, so make sure any TypoExprs have
20262     // been dealt with before checking the operands.
20263     ExprResult Result = CorrectDelayedTyposInExpr(E);
20264     if (!Result.isUsable()) return ExprError();
20265     E = Result.get();
20266   }
20267 
20268   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20269   if (!placeholderType) return E;
20270 
20271   switch (placeholderType->getKind()) {
20272 
20273   // Overloaded expressions.
20274   case BuiltinType::Overload: {
20275     // Try to resolve a single function template specialization.
20276     // This is obligatory.
20277     ExprResult Result = E;
20278     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20279       return Result;
20280 
20281     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20282     // leaves Result unchanged on failure.
20283     Result = E;
20284     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20285       return Result;
20286 
20287     // If that failed, try to recover with a call.
20288     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20289                          /*complain*/ true);
20290     return Result;
20291   }
20292 
20293   // Bound member functions.
20294   case BuiltinType::BoundMember: {
20295     ExprResult result = E;
20296     const Expr *BME = E->IgnoreParens();
20297     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20298     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20299     if (isa<CXXPseudoDestructorExpr>(BME)) {
20300       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20301     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20302       if (ME->getMemberNameInfo().getName().getNameKind() ==
20303           DeclarationName::CXXDestructorName)
20304         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20305     }
20306     tryToRecoverWithCall(result, PD,
20307                          /*complain*/ true);
20308     return result;
20309   }
20310 
20311   // ARC unbridged casts.
20312   case BuiltinType::ARCUnbridgedCast: {
20313     Expr *realCast = stripARCUnbridgedCast(E);
20314     diagnoseARCUnbridgedCast(realCast);
20315     return realCast;
20316   }
20317 
20318   // Expressions of unknown type.
20319   case BuiltinType::UnknownAny:
20320     return diagnoseUnknownAnyExpr(*this, E);
20321 
20322   // Pseudo-objects.
20323   case BuiltinType::PseudoObject:
20324     return checkPseudoObjectRValue(E);
20325 
20326   case BuiltinType::BuiltinFn: {
20327     // Accept __noop without parens by implicitly converting it to a call expr.
20328     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20329     if (DRE) {
20330       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20331       if (FD->getBuiltinID() == Builtin::BI__noop) {
20332         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20333                               CK_BuiltinFnToFnPtr)
20334                 .get();
20335         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20336                                 VK_PRValue, SourceLocation(),
20337                                 FPOptionsOverride());
20338       }
20339     }
20340 
20341     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20342     return ExprError();
20343   }
20344 
20345   case BuiltinType::IncompleteMatrixIdx:
20346     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20347              ->getRowIdx()
20348              ->getBeginLoc(),
20349          diag::err_matrix_incomplete_index);
20350     return ExprError();
20351 
20352   // Expressions of unknown type.
20353   case BuiltinType::OMPArraySection:
20354     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20355     return ExprError();
20356 
20357   // Expressions of unknown type.
20358   case BuiltinType::OMPArrayShaping:
20359     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20360 
20361   case BuiltinType::OMPIterator:
20362     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20363 
20364   // Everything else should be impossible.
20365 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20366   case BuiltinType::Id:
20367 #include "clang/Basic/OpenCLImageTypes.def"
20368 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20369   case BuiltinType::Id:
20370 #include "clang/Basic/OpenCLExtensionTypes.def"
20371 #define SVE_TYPE(Name, Id, SingletonId) \
20372   case BuiltinType::Id:
20373 #include "clang/Basic/AArch64SVEACLETypes.def"
20374 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20375   case BuiltinType::Id:
20376 #include "clang/Basic/PPCTypes.def"
20377 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20378 #include "clang/Basic/RISCVVTypes.def"
20379 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20380 #define PLACEHOLDER_TYPE(Id, SingletonId)
20381 #include "clang/AST/BuiltinTypes.def"
20382     break;
20383   }
20384 
20385   llvm_unreachable("invalid placeholder type!");
20386 }
20387 
20388 bool Sema::CheckCaseExpression(Expr *E) {
20389   if (E->isTypeDependent())
20390     return true;
20391   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20392     return E->getType()->isIntegralOrEnumerationType();
20393   return false;
20394 }
20395 
20396 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20397 ExprResult
20398 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20399   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20400          "Unknown Objective-C Boolean value!");
20401   QualType BoolT = Context.ObjCBuiltinBoolTy;
20402   if (!Context.getBOOLDecl()) {
20403     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20404                         Sema::LookupOrdinaryName);
20405     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20406       NamedDecl *ND = Result.getFoundDecl();
20407       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20408         Context.setBOOLDecl(TD);
20409     }
20410   }
20411   if (Context.getBOOLDecl())
20412     BoolT = Context.getBOOLType();
20413   return new (Context)
20414       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20415 }
20416 
20417 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20418     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20419     SourceLocation RParen) {
20420   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20421     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20422       return Spec.getPlatform() == Platform;
20423     });
20424     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20425     // for "maccatalyst" if "maccatalyst" is not specified.
20426     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20427       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20428         return Spec.getPlatform() == "ios";
20429       });
20430     }
20431     if (Spec == AvailSpecs.end())
20432       return None;
20433     return Spec->getVersion();
20434   };
20435 
20436   VersionTuple Version;
20437   if (auto MaybeVersion =
20438           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20439     Version = *MaybeVersion;
20440 
20441   // The use of `@available` in the enclosing context should be analyzed to
20442   // warn when it's used inappropriately (i.e. not if(@available)).
20443   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20444     Context->HasPotentialAvailabilityViolations = true;
20445 
20446   return new (Context)
20447       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20448 }
20449 
20450 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20451                                     ArrayRef<Expr *> SubExprs, QualType T) {
20452   if (!Context.getLangOpts().RecoveryAST)
20453     return ExprError();
20454 
20455   if (isSFINAEContext())
20456     return ExprError();
20457 
20458   if (T.isNull() || T->isUndeducedType() ||
20459       !Context.getLangOpts().RecoveryASTType)
20460     // We don't know the concrete type, fallback to dependent type.
20461     T = Context.DependentTy;
20462 
20463   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20464 }
20465